diff --git a/.dbg/login-401.env b/.dbg/login-401.env new file mode 100644 index 00000000..9d3c97a9 --- /dev/null +++ b/.dbg/login-401.env @@ -0,0 +1,2 @@ +DEBUG_SERVER_URL=http://127.0.0.1:7778/event +DEBUG_SESSION_ID=login-401 diff --git a/.dbg/trae-debug-log-app-open-error.ndjson b/.dbg/trae-debug-log-app-open-error.ndjson new file mode 100644 index 00000000..fa20368d --- /dev/null +++ b/.dbg/trae-debug-log-app-open-error.ndjson @@ -0,0 +1,2 @@ +{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927} +{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938} diff --git a/.env.prod b/.env.prod index 91db32c4..fce5c594 100644 --- a/.env.prod +++ b/.env.prod @@ -120,12 +120,12 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭) -SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false -SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL= +SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true +SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.230:8100/ SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10 SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300 SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10 -SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2 +SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=3 SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000 SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000 SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3 @@ -141,7 +141,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 企微心跳告警总开关(默认关闭;需要时改为 true) SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 +SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 diff --git a/.env.shared b/.env.shared index 7fe2717b..2907ddb6 100644 --- a/.env.shared +++ b/.env.shared @@ -53,6 +53,7 @@ CONTRACT_DMS_2026_FOLDER_ID=4e63b520-0da9-4731-a3dd-ec48f278dce0 CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE={year}年设备合同书 CONTRACT_DMS_TEMP_FOLDER_NAME=暂存 CONTRACT_DMS_LOOKUP_WINDOW_DAYS=30 + CONTRACT_PAYMENT_ENABLED=true CONTRACT_PAYMENT_OA_BASE_URL=http://192.168.100.221:8888 CONTRACT_PAYMENT_OA_USERNAME=AIuser @@ -73,6 +74,17 @@ CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD=bm CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD=zz CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD=jfl +# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*) +# VOUCHER_CHECK_ERP_DSN= +# VOUCHER_CHECK_ERP_USERNAME= +# VOUCHER_CHECK_ERP_PASSWORD= + +VOUCHER_CHECK_DMS_BASE_URL=http://192.168.8.158:8071 +VOUCHER_CHECK_DMS_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8 +VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=727c3683-dcdb-4d62-a5b1-b164224162bc +VOUCHER_CHECK_DMS_USERNAME=AIuser +VOUCHER_CHECK_DMS_PASSWORD=123456 + # chat回答的评分与评论 FEEDBACK_ENABLED=true @@ -197,6 +209,24 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420 # --- 9. 业务模块 --- +# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值) +IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3 +IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=3 +IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=3 +IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60 +IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60 +IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600 +IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3 +IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5 +IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7 +# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件) +# IN_TRANSIT_TRANSFER_ERP_ENDPOINT= +# IN_TRANSIT_TRANSFER_ERP_USERNAME= +# IN_TRANSIT_TRANSFER_ERP_PASSWORD= +IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG= +# 归档 bucket(MinIO;凭据复用 MINIO_*) +IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer + # chat回答的评分与评论 FEEDBACK_ENABLED=true # 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表) diff --git a/.env.test b/.env.test index 06c08011..40158b13 100644 --- a/.env.test +++ b/.env.test @@ -161,7 +161,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 两者皆无则告警只写日志、不会发企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 +SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true # 企微发送中短锁秒数(发送失败过期后可重试,默认 120) SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 @@ -175,7 +175,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queu SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选) +# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选) # SHIPPING_NOTICE_RPA_WORKER_MOCK=true # SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 # SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index fadd2a89..bcf4d5e7 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -41,10 +41,12 @@ def register_blueprints(app: Flask) -> None: workspace_shipping_notice_bp, workspace_voucher_check_bp, ) - from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp + from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp from app.api.files import files_bp from app.api.procurement_contract_tools import procurement_contract_bp from app.api.contract_payment import contract_payment_bp + from app.api.in_transit_transfer import in_transit_transfer_bp + from app.api.integration_connector import integration_connector_bp app.register_blueprint(chat_bp, url_prefix='/api/chat') app.register_blueprint(admin_bp, url_prefix='/api/admin') @@ -64,7 +66,6 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') app.register_blueprint(file_check_bp, url_prefix='/api/file-check') - app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check') app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context') app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') app.register_blueprint(speech_bp, url_prefix='/api/speech') @@ -75,3 +76,5 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(files_bp, url_prefix='/api/files') app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract') app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment') + app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer') + app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector') diff --git a/backend/app/api/admin/shipping_customers.py b/backend/app/api/admin/shipping_customers.py index 5345af7c..7cb869d4 100644 --- a/backend/app/api/admin/shipping_customers.py +++ b/backend/app/api/admin/shipping_customers.py @@ -26,10 +26,8 @@ from app.services.shipping_notice.customer_shadow_resolution import ( label_shadow_resolution, ) from app.services.shipping_notice.customer_auto_resolution import ( - correct_numbered_task_customer, get_auto_resolution_metrics, ) -from app.services.shipping_notice.query_service import get_task_by_ref XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' @@ -287,32 +285,6 @@ def get_shipping_customer_shadow_report(): return jsonify(report) -@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST']) -@require_admin -def correct_shipping_numbered_task_customer(): - """管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。""" - data = request.get_json(silent=True) or {} - task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper() - if not task_ref: - raise ValidationError( - 'Task reference is required', - code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED', - ) - try: - customer_id = int(data.get('customer_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc - task = get_task_by_ref(task_ref) - if task is None: - raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING') - return jsonify(correct_numbered_task_customer( - task, - customer_id=customer_id, - reason=str(data.get('reason') or ''), - actor_id=_actor_id(), - )) - - @admin_bp.route('/shipping-customer-shadow-resolutions//label', methods=['PUT']) @require_admin def label_shipping_customer_shadow_resolution(resolution_id: int): diff --git a/backend/app/api/admin/shipping_order_schema.py b/backend/app/api/admin/shipping_order_schema.py index c11ec17e..63cd774c 100644 --- a/backend/app/api/admin/shipping_order_schema.py +++ b/backend/app/api/admin/shipping_order_schema.py @@ -234,25 +234,22 @@ def simulate_shipping_order_schema_derivation(version_id: int): """ 对 Schema 版本派生规则做样本模拟(不创建或修改订单)。 - 请求体:lines[] 或 sample_ref=`extraction:`;可选 derivation_rules。 - 事务:服务层只写入审计实体,本路由统一 commit。 + 硬切换后该能力已停用;line_no 由系统按单据内顺序生成。 """ - payload = service.simulate_derivation( - version_id, - request.get_json(silent=True) or {}, - actor_id=_actor_id(), - request_id=getattr(g, 'request_id', None), + raise ValidationError( + 'Schema derivation is disabled; line_no is system-generated', + code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED', ) - db.session.commit() - return _ok(payload) @admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET']) @require_admin def list_shipping_order_schema_derivation_simulate_samples(): """列出可供派生规则模拟的历史 Extraction 样本摘要。""" - limit = request.args.get('limit', 20, type=int) - return _ok(service.list_derivation_simulate_samples(limit=limit or 20)) + raise ValidationError( + 'Schema derivation is disabled; line_no is system-generated', + code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED', + ) @admin_bp.route('/shipping-order-schema/published-contract', methods=['GET']) @require_admin diff --git a/backend/app/api/chat/__init__.py b/backend/app/api/chat/__init__.py index e3cf8b3a..89728b3e 100644 --- a/backend/app/api/chat/__init__.py +++ b/backend/app/api/chat/__init__.py @@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__) # 子模块导入时在同一 Blueprint 上注册原有 URL。 from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401 +from .shared import ( # noqa: E402, F401 + CHAT_USER_ATTACHMENT_LIMIT, + CHAT_USER_ATTACHMENT_MAX_SIZE, + CHAT_USER_ATTACHMENT_SOURCES, + CHAT_USER_ATTACHMENT_TYPES, + _merge_user_attachments_from_terminal_event, + _normalize_user_attachments, +) from app.api.chat_turns import register_chat_turn_routes # noqa: E402 register_chat_turn_routes(chat_bp) -__all__ = ['chat_bp'] +__all__ = [ + 'chat_bp', + 'CHAT_USER_ATTACHMENT_LIMIT', + 'CHAT_USER_ATTACHMENT_MAX_SIZE', + 'CHAT_USER_ATTACHMENT_SOURCES', + 'CHAT_USER_ATTACHMENT_TYPES', + '_merge_user_attachments_from_terminal_event', + '_normalize_user_attachments', +] diff --git a/backend/app/api/chat/sessions.py b/backend/app/api/chat/sessions.py index fa55ebac..a46ab083 100644 --- a/backend/app/api/chat/sessions.py +++ b/backend/app/api/chat/sessions.py @@ -8,6 +8,7 @@ api/chat/sessions.py from __future__ import annotations from .shared import * # noqa: F403 +from .shared import _normalize_user_attachments from . import chat_bp from .core import ( _chat_logs_for_session, @@ -194,19 +195,32 @@ def get_chat_messages(): messages = [] agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic' for log in logs: - if log.query: - messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)}) + raw_payload = log.payload if isinstance(log.payload, dict) else {} + user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments')) + assistant_payload = { + key: value + for key, value in raw_payload.items() + if key != 'user_attachments' + } + if log.query or user_attachments: + user_msg = { + 'role': 'user', + 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code), + } + if user_attachments: + user_msg['attachments'] = user_attachments + messages.append(user_msg) if ( not log.answer and not log.message_type - and not log.payload + and not assistant_payload ): continue if ( log.query and log.answer == log.query and (not log.message_type or log.message_type == 'text') - and not log.payload + and not assistant_payload ): continue assistant_msg = { @@ -220,8 +234,8 @@ def get_chat_messages(): assistant_msg['run_id'] = log.run_id if log.message_type: assistant_msg['type'] = log.message_type - if log.payload: - assistant_msg['payload'] = log.payload + if assistant_payload: + assistant_msg['payload'] = assistant_payload messages.append(assistant_msg) return jsonify(messages) diff --git a/backend/app/api/chat/shared.py b/backend/app/api/chat/shared.py index 64fdb848..faf3c128 100644 --- a/backend/app/api/chat/shared.py +++ b/backend/app/api/chat/shared.py @@ -12,6 +12,7 @@ import ntpath import posixpath import tempfile import os +import re import subprocess import uuid import json @@ -41,6 +42,95 @@ from app.core.errors import ( ) SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' +# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。 +CHAT_USER_ATTACHMENT_LIMIT = 20 +CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 +CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} +CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} + + +def _normalize_user_attachments(value) -> list[dict]: + """ + 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 + + 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。 + + Args: + value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。 + + Returns: + 可安全写入 JSON 的附件快照列表;非法项目被忽略。 + """ + if not isinstance(value, list): + return [] + normalized: list[dict] = [] + for item in value[:CHAT_USER_ATTACHMENT_LIMIT]: + if not isinstance(item, dict): + continue + raw_name = str(item.get('name') or '') + basename = re.split(r'[\\/]+', raw_name)[-1] + name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255] + attachment_type = str(item.get('type') or '').strip().lower() + source = str(item.get('source') or '').strip().lower() + if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES: + continue + snapshot = { + 'name': name, + 'type': attachment_type, + 'source': source, + } + extension = str(item.get('extension') or '').strip().lower() + if re.fullmatch(r'[a-z0-9]{1,16}', extension): + snapshot['extension'] = extension + try: + size = int(item.get('size')) if item.get('size') is not None else None + except (TypeError, ValueError): + size = None + if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE: + snapshot['size'] = size + normalized.append(snapshot) + return normalized + + +def _merge_user_attachments_from_terminal_event( + event_data: dict, + *, + user_id: int, + agent_id: int, + session_id: str, + user_attachments: list[dict], +) -> bool: + """ + 在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。 + + Args: + event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。 + user_id: 当前用户 ID。 + agent_id: 当前 Agent ID。 + session_id: 当前 HXOPS 本地会话 ID。 + user_attachments: 已完成白名单校验的附件快照。 + + Returns: + 找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。 + """ + if not user_attachments: + return False + try: + chat_log_id = int(event_data.get('chat_log_id') or 0) + except (TypeError, ValueError): + return False + if chat_log_id <= 0: + return False + from app.services.chat.log_service import merge_chat_log_payload + return merge_chat_log_payload( + chat_log_id=chat_log_id, + user_id=int(user_id or 0), + agent_id=int(agent_id or 0), + session_id=session_id, + payload_patch={'user_attachments': user_attachments}, + ) + + PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip() diff --git a/backend/app/api/in_transit_transfer.py b/backend/app/api/in_transit_transfer.py new file mode 100644 index 00000000..4fae26b8 --- /dev/null +++ b/backend/app/api/in_transit_transfer.py @@ -0,0 +1,428 @@ +"""backend/app/api/in_transit_transfer.py + +用途:在途仓自动调拨用户态 API(仓库管理人员)。 +依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。 +逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id); + Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。 +""" + +from __future__ import annotations + +from functools import wraps +from typing import Any + +from flask import Blueprint, g, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError +from app.core.response import ok +from app.models import Agent +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.cancellation import cancel_run +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook +from app.services.in_transit_transfer.execution_service import ( + execute_precheck, + get_run, + serialize_run_result, +) +from app.services.in_transit_transfer.manual_close_service import manual_close_item +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from app.services.in_transit_transfer.retry_service import retry_item +from app.services.in_transit_transfer.serializers import ( + serialize_item, + serialize_source, + serialize_summary, +) + +in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__) + +TRANSFER_AGENT_CODE = "in_transit_transfer" + + +def _require_user(): + """校验当前登录用户;未认证抛 UnauthorizedError。""" + user = get_current_user() + if not user: + raise UnauthorizedError("Unauthorized") + return user + + +def require_transfer_permission(f): + """装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。""" + + @wraps(f) + def decorated(*args, **kwargs): + user = _require_user() + if user.role == "admin": + return f(*args, **kwargs) + agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first() + if agent is None or agent not in user.agents: + raise ForbiddenError("Transfer agent permission required") + return f(*args, **kwargs) + + return decorated + + +def _ok(payload: Any, *, status: int = 200): + """统一成功 envelope(带 request_id)。""" + return ok(payload, request_id=getattr(g, "request_id", None), status=status) + + +@in_transit_transfer_bp.route("/prechecks", methods=["POST"]) +@require_transfer_permission +def create_precheck_api(): + """创建或复用一次调拨预检(只读,不写 ERP)。 + + 请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。 + 响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。 + """ + body = request.get_json(silent=True) or {} + if not isinstance(body, dict): + raise ValidationError("request body must be a JSON object") + source_codes = body.get("source_codes") + if not isinstance(source_codes, list) or not source_codes: + raise ValidationError("source_codes is required") + business_date = str(body.get("business_date") or business_date_now()) + deps = transfer_deps.get_transfer_dependencies() + summary = create_precheck( + source_codes=[str(item).strip() for item in source_codes], + business_date=business_date, + deps=deps, + ) + return _ok(serialize_summary(summary), status=201) + + +@in_transit_transfer_bp.route("/prechecks/", methods=["GET"]) +@require_transfer_permission +def get_precheck_api(precheck_id: str): + """恢复预检进度与明细(页面刷新/会话恢复)。""" + restored = restore_precheck(precheck_id) + return _ok({ + "summary": serialize_summary(restored["summary"]), + "items": [serialize_item(item) for item in restored["items"]], + "sources": [serialize_source(source) for source in restored["sources"]], + }) + + +@in_transit_transfer_bp.route("/prechecks//execute", methods=["POST"]) +@require_transfer_permission +def execute_precheck_api(precheck_id: str): + """确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。 + + 请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。 + 响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。 + """ + body = request.get_json(silent=True) or {} + invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None + if invoice_nos is not None and not isinstance(invoice_nos, list): + raise ValidationError("invoice_nos must be a list") + deps = transfer_deps.get_transfer_dependencies() + outcome = execute_precheck( + precheck_id=precheck_id, + deps=deps, + selected_invoice_nos=invoice_nos, + ) + return _ok({ + "run_no": outcome.run_no, + "status": outcome.status, + "result": serialize_run_result(outcome.result), + }, status=201) + + +@in_transit_transfer_bp.route("/runs/", methods=["GET"]) +@require_transfer_permission +def get_run_api(run_no: str): + """恢复 Run 最终结果(页面刷新/会话恢复)。""" + return _ok(get_run(run_no)) + + +@in_transit_transfer_bp.route("/runs//cancel", methods=["POST"]) +@require_transfer_permission +def cancel_run_api(run_no: str): + """请求停止剩余任务(原因必填,已成功单据保留)。""" + body = request.get_json(silent=True) or {} + reason = body.get("reason") if isinstance(body, dict) else None + return _ok(cancel_run(run_no=run_no, reason=reason)) + + +@in_transit_transfer_bp.route("/items//retry", methods=["POST"]) +@require_transfer_permission +def retry_item_api(item_id: int): + """人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。 + + 请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。 + """ + body = request.get_json(silent=True) or {} + kind = body.get("kind") if isinstance(body, dict) else None + deps = transfer_deps.get_transfer_dependencies() + return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck")) + + +@in_transit_transfer_bp.route("/items//manual-close", methods=["POST"]) +@require_transfer_permission +def manual_close_item_api(item_id: int): + """人工关闭异常项(原因必填,永久排除)。""" + body = request.get_json(silent=True) or {} + reason = body.get("reason") if isinstance(body, dict) else None + return _ok(manual_close_item(item_id=item_id, reason=reason)) + + +@in_transit_transfer_bp.route("/runs//exceptions.xlsx", methods=["GET"]) +@require_transfer_permission +def exceptions_excel_api(run_no: str): + """下载本次 Run 的七 Sheet 异常 Excel(下载行为记录访问审计)。""" + import io + + from app import db + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + data = build_exceptions_workbook(run_no) + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_EXCEL_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(data), + mimetype=_MIME, + as_attachment=True, + download_name=f"transfer-exceptions-{run_no}.xlsx", + ) + + +@in_transit_transfer_bp.route("/runs//receipt-files", methods=["GET"]) +@require_transfer_permission +def receipt_files_api(run_no: str): + """下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。""" + import io + import json + import zipfile + + from app import db + from app.models import TransferInvoiceItem, TransferRun + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + precheck = run.prechecks[0] if run.prechecks else None + file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {} + + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + for source_code in run.source_codes_json: + manifest = { + "source_code": source_code, + "business_date": run.business_date, + **dict(file_snapshot.get(source_code) or {}), + } + archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2)) + rows = [] + for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all(): + for line in (item.raw_lines_json or []): + rows.append({ + "invoice_no": item.invoice_no, "source_code": item.source_code, + "sheet": line.get("sheet", ""), "row_no": line.get("row_no", ""), + "file_version": line.get("file_version", ""), + }) + archive.writestr("raw-line-trace.json", json.dumps(rows, ensure_ascii=False, indent=2)) + + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(buffer.getvalue()), + mimetype="application/zip", + as_attachment=True, + download_name=f"receipt-files-{run_no}.zip", + ) + + +@in_transit_transfer_bp.route("/runs//erp-inventory", methods=["GET"]) +@require_transfer_permission +def erp_inventory_api(run_no: str): + """下载本次预检冻结的 ERP 库存表(csv);记录访问审计。""" + import io + + from app import db + from app.models import TransferInvoiceItem, TransferRun + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"] + for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all(): + lines.append(",".join([ + str(item.invoice_no), str(item.source_code), str(item.material_no), + str(item.from_warehouse), str(item.to_warehouse), + str(item.receipt_quantity), str(item.erp_quantity or ""), + str(item.result_code or item.status), str(item.erp_document_no or ""), + ])) + data = ("\n".join(lines) + "\n").encode("utf-8") + + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(data), + mimetype="text/csv", + as_attachment=True, + download_name=f"erp-inventory-{run_no}.csv", + ) + + +@in_transit_transfer_bp.route("/metrics", methods=["GET"]) +@require_transfer_permission +def transfer_metrics_api(): + """调拨运营指标(成功率/失败类型/待处理老化/通知失败),供运营看板。""" + from app.services.in_transit_transfer.metrics import collect_metrics + + return _ok(collect_metrics()) + + +@in_transit_transfer_bp.route("/sources", methods=["GET"]) +@require_transfer_permission +def transfer_sources_api(): + """来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。 + + 每来源附收料文件状态(ready/fetching/failed/none + has_ready_file), + 供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。 + """ + from app.models import ShippingInventorySource + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + + rows = ShippingInventorySource.query.filter_by(enabled=True).order_by( + ShippingInventorySource.connector_type, ShippingInventorySource.source_code, + ).all() + return _ok([ + { + "source_code": source.source_code, + "display_name": source.display_name, + "platform": source.connector_type, + "enabled": bool(source.enabled), + **resolve_source_file_status(source_code=source.source_code), + } + for source in rows + ]) + + +@in_transit_transfer_bp.route("/sources//retry-rpa", methods=["POST"]) +@require_transfer_permission +def retry_source_rpa_api(source_code: str): + """对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。 + + 响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。 + """ + from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + from app.services.in_transit_transfer.date_policy import business_date_now + + source_code = str(source_code).strip() + outcome = trigger_receipt_rpa( + source_code=source_code, + business_date=str(business_date_now()), + reason="transfer_retry_receipt", + ) + status = resolve_source_file_status(source_code=source_code) + if not outcome.get("ok"): + return _ok({ + "source_code": source_code, + "ok": False, + "file_status": status["file_status"], + "error_code": outcome.get("error_code"), + }) + return _ok({ + "source_code": source_code, + "ok": True, + "file_status": "fetching", + "callback_id": outcome.get("callback_id"), + }, status=202) + + +@in_transit_transfer_bp.route("/backlog", methods=["GET"]) +@require_transfer_permission +def backlog_api(): + """待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。""" + from app import db + from app.services.in_transit_transfer.audit import build_transfer_audit_event + from app.services.in_transit_transfer.backlog_service import list_backlog + + items = list_backlog() + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type='TRANSFER_BACKLOG_VIEWED', + aggregate_type='transfer_backlog', + aggregate_id='backlog', + actor_type='user', + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, 'name', '') or ''), + request_id=getattr(g, 'request_id', None), + result='success', + after={'item_count': len(items)}, + )) + db.session.commit() + return _ok([_serialize_backlog_item(item) for item in items]) + + +@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"]) +@require_transfer_permission +def backlog_summary_api(): + """待处理异常汇总(含 3/5/7 天老化分级)。""" + from app.services.in_transit_transfer.backlog_service import backlog_summary + + summary = backlog_summary() + return _ok({ + 'recoverable': summary.recoverable_count, + 'closed': summary.closed_count, + 'unknown': summary.unknown_count, + 'aging': { + 'warn_3d': summary.warn_3d, + 'escalate_5d': summary.escalate_5d, + 'critical_7d': summary.critical_7d, + }, + }) + + +def _serialize_backlog_item(item) -> dict[str, Any]: + """待处理池项序列化。""" + return { + 'item_id': item.item_id, + 'source_code': item.source_code, + 'invoice_no': item.invoice_no, + 'material_no': item.material_no, + 'status': item.status, + 'reason': item.reason, + 'age_days': item.age_days, + 'aging_level': item.aging_level, + 'last_attempt_at': item.last_attempt_at, + } diff --git a/backend/app/api/integration_connector.py b/backend/app/api/integration_connector.py new file mode 100644 index 00000000..c41b7773 --- /dev/null +++ b/backend/app/api/integration_connector.py @@ -0,0 +1,447 @@ +"""api/integration_connector.py + +用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。 +依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。 +逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key}, + 拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。 +注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有 + /api/integration Dify 文件代理)。 +""" + +from __future__ import annotations + +import uuid + +from flask import Blueprint, request + +from app.core.decorators import require_admin +from app.core.errors import NotFoundError, ValidationError +from app.core.response import ok +from app.models import ( + IntegrationBinding, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) +from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities +from app.services.integration_connector.gateway import get_capability_gateway +from app.services.integration_connector.transports.base import IntegrationCallResult + +integration_connector_bp = Blueprint('integration_connector', __name__) + +VALID_CONNECTOR_TYPES = ('rest', 'soap') +VALID_STATUSES = ('draft', 'published', 'retired') + + +def _require(value, field: str) -> None: + """字段必填校验。""" + if value is None or (isinstance(value, str) and not value.strip()): + raise ValidationError(f'{field} is required', details={'field': field}) + + +def _serialize_client(client) -> dict: + return { + 'id': client.id, 'code': client.code, 'name': client.name, + 'connector_type': client.connector_type, 'environment': client.environment, + 'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds, + 'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code, + 'enabled': client.enabled, + } + + +def _serialize_interface(iface) -> dict: + return { + 'id': iface.id, 'code': iface.code, 'name': iface.name, + 'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type, + 'http_method': iface.http_method, 'request_path': iface.request_path, + 'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {}, + 'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {}, + 'version': iface.version, 'status': iface.status, 'enabled': iface.enabled, + } + + +def _serialize_binding(binding) -> dict: + return { + 'id': binding.id, 'capability': binding.capability, + 'context_selector_json': binding.context_selector_json or {}, + 'context_source_code': binding.context_source_code, + 'client_instance_code': binding.client_instance_code, + 'interface_definition_code': binding.interface_definition_code, + 'mapping_version': binding.mapping_version, 'priority': binding.priority, + 'environment': binding.environment, 'effective_from': binding.effective_from, + 'effective_to': binding.effective_to, 'status': binding.status, + } + + +def _serialize_credential(cred) -> dict: + return { + 'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref, + 'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type, + 'version': cred.version, 'status': cred.status, + 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, + } + + +def _result_to_dict(result: IntegrationCallResult) -> dict: + return { + 'status': result.status, + 'data': result.data, + 'error_code': result.error_code, + 'error_message': result.error_message, + 'document_no': result.document_no, + 'trace_id': result.trace_id, + } + + +# ---- 能力清单与调用 ---- + +@integration_connector_bp.route('/capabilities', methods=['GET']) +@require_admin +def list_capabilities_endpoint(): + ensure_capabilities_loaded() + data = [{ + 'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency, + 'input_schema': spec.input_schema, 'output_schema': spec.output_schema, + } for spec in list_capabilities()] + return ok(data) + + +@integration_connector_bp.route('/capabilities/', methods=['POST']) +@require_admin +def call_capability(capability): + body = request.get_json(silent=True) or {} + if body.get('interface_id') is not None: + raise ValidationError( + 'interface_id is not allowed for capability calls', + code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED', + ) + params = body.get('params') or {} + context = body.get('context') or {} + operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}') + idempotency_key = body.get('idempotency_key') + result = get_capability_gateway().call( + capability=capability, context=context, params=params, + operation_id=operation_id, idempotency_key=idempotency_key, + ) + return ok(_result_to_dict(result)) + + +# ---- 客户端实例 ---- + +@integration_connector_bp.route('/client-instances', methods=['GET']) +@require_admin +def list_client_instances(): + rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all() + return ok([_serialize_client(row) for row in rows]) + + +@integration_connector_bp.route('/client-instances', methods=['POST']) +@require_admin +def create_client_instance(): + body = request.get_json(silent=True) or {} + connector_type = str(body.get('connector_type') or '').strip() + _require(body.get('code'), 'code') + _require(body.get('name'), 'name') + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + if IntegrationClientInstance.query.filter_by(code=body['code']).first(): + raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT') + client = IntegrationClientInstance( + code=str(body['code']).strip(), name=str(body['name']).strip(), + connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(), + endpoint=(str(body.get('endpoint') or '').strip() or None), + timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None), + config_json=body.get('config_json') or {}, + credential_ref_code=body.get('credential_ref_code'), + enabled=bool(body.get('enabled', True)), + ) + from app import db + db.session.add(client) + db.session.commit() + return ok(_serialize_client(client), status=201) + + +@integration_connector_bp.route('/client-instances/', methods=['GET']) +@require_admin +def get_client_instance(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND') + return ok(_serialize_client(client)) + + +@integration_connector_bp.route('/client-instances/', methods=['DELETE']) +@require_admin +def delete_client_instance(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found') + from app import db + db.session.delete(client) + db.session.commit() + return ok({'deleted': True}) + + +@integration_connector_bp.route('/client-instances/', methods=['PUT']) +@require_admin +def update_client_instance(code): + """更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。""" + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND') + body = request.get_json(silent=True) or {} + connector_type = str(body.get('connector_type') or client.connector_type) + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + if body.get('name') is not None: + _require(body.get('name'), 'name') + client.name = str(body['name']).strip() + if body.get('connector_type') is not None: + client.connector_type = connector_type + if body.get('environment') is not None: + client.environment = str(body['environment']).strip() + if 'endpoint' in body: + client.endpoint = str(body.get('endpoint') or '').strip() or None + if 'timeout_seconds' in body: + client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None + if 'config_json' in body: + client.config_json = body.get('config_json') or {} + if 'credential_ref_code' in body: + client.credential_ref_code = body.get('credential_ref_code') + if 'enabled' in body: + client.enabled = bool(body.get('enabled', True)) + from app import db + db.session.commit() + return ok(_serialize_client(client)) + + +# ---- 接口定义 ---- + +@integration_connector_bp.route('/interface-definitions', methods=['GET']) +@require_admin +def list_interface_definitions(): + rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all() + return ok([_serialize_interface(row) for row in rows]) + + +@integration_connector_bp.route('/interface-definitions', methods=['POST']) +@require_admin +def create_interface_definition(): + body = request.get_json(silent=True) or {} + code = str(body.get('code') or '').strip() + _require(code, 'code') + _require(body.get('client_instance_code'), 'client_instance_code') + connector_type = str(body.get('connector_type') or '') + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + status = str(body.get('status') or 'draft') + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + iface = IntegrationInterfaceDefinition( + code=code, name=str(body.get('name') or code).strip(), + client_instance_code=body['client_instance_code'], connector_type=connector_type, + http_method=(str(body.get('http_method') or '').strip().upper() or None), + request_path=(str(body.get('request_path') or '').strip() or None), + request_spec_json=body.get('request_spec_json') or {}, + input_schema_json=body.get('input_schema_json') or {}, + response_mapping_json=body.get('response_mapping_json') or {}, + output_schema_json=body.get('output_schema_json') or {}, + version=int(body.get('version') or 1), status=status, + enabled=bool(body.get('enabled', True)), + ) + from app import db + db.session.add(iface) + db.session.commit() + return ok(_serialize_interface(iface), status=201) + + +@integration_connector_bp.route('/interface-definitions/', methods=['PUT']) +@require_admin +def update_interface_definition(code): + """更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。""" + iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first() + if iface is None: + raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND') + body = request.get_json(silent=True) or {} + if body.get('name') is not None: + _require(body.get('name'), 'name') + iface.name = str(body['name']).strip() + if body.get('client_instance_code') is not None: + _require(body.get('client_instance_code'), 'client_instance_code') + iface.client_instance_code = body['client_instance_code'] + if body.get('connector_type') is not None: + connector_type = str(body['connector_type']) + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + iface.connector_type = connector_type + if 'http_method' in body: + iface.http_method = str(body.get('http_method') or '').strip().upper() or None + if 'request_path' in body: + iface.request_path = str(body.get('request_path') or '').strip() or None + for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'): + if json_field in body: + setattr(iface, json_field, body.get(json_field) or {}) + if body.get('version') is not None: + iface.version = int(body.get('version') or 1) + if body.get('status') is not None: + status = str(body['status']) + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + iface.status = status + if 'enabled' in body: + iface.enabled = bool(body.get('enabled', True)) + from app import db + db.session.commit() + return ok(_serialize_interface(iface)) + + +# ---- Binding ---- + +@integration_connector_bp.route('/bindings', methods=['GET']) +@require_admin +def list_bindings(): + rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all() + return ok([_serialize_binding(row) for row in rows]) + + +@integration_connector_bp.route('/bindings', methods=['POST']) +@require_admin +def create_binding(): + body = request.get_json(silent=True) or {} + _require(body.get('capability'), 'capability') + _require(body.get('client_instance_code'), 'client_instance_code') + _require(body.get('interface_definition_code'), 'interface_definition_code') + status = str(body.get('status') or 'draft') + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + binding = IntegrationBinding( + capability=body['capability'], + context_selector_json=body.get('context_selector_json') or {}, + context_source_code=(str(body.get('context_source_code') or '').strip() or None), + client_instance_code=body['client_instance_code'], + interface_definition_code=body['interface_definition_code'], + mapping_version=int(body.get('mapping_version') or 1), + priority=int(body.get('priority') or 0), + environment=str(body.get('environment') or 'prod').strip(), + status=status, + ) + from app import db + db.session.add(binding) + db.session.commit() + return ok(_serialize_binding(binding), status=201) + + +@integration_connector_bp.route('/bindings/', methods=['PUT']) +@require_admin +def update_binding(binding_id): + """更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。""" + from app import db + binding = db.session.get(IntegrationBinding, binding_id) + if binding is None: + raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND') + body = request.get_json(silent=True) or {} + if body.get('capability') is not None: + _require(body.get('capability'), 'capability') + binding.capability = body['capability'] + if 'context_selector_json' in body: + binding.context_selector_json = body.get('context_selector_json') or {} + if 'context_source_code' in body: + binding.context_source_code = str(body.get('context_source_code') or '').strip() or None + if body.get('client_instance_code') is not None: + _require(body.get('client_instance_code'), 'client_instance_code') + binding.client_instance_code = body['client_instance_code'] + if body.get('interface_definition_code') is not None: + _require(body.get('interface_definition_code'), 'interface_definition_code') + binding.interface_definition_code = body['interface_definition_code'] + if body.get('mapping_version') is not None: + binding.mapping_version = int(body.get('mapping_version') or 1) + if body.get('priority') is not None: + binding.priority = int(body.get('priority') or 0) + if body.get('environment') is not None: + binding.environment = str(body['environment']).strip() + if body.get('effective_from') is not None: + binding.effective_from = body['effective_from'] or None + if body.get('effective_to') is not None: + binding.effective_to = body['effective_to'] or None + if body.get('status') is not None: + status = str(body['status']) + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + binding.status = status + from app import db + db.session.commit() + return ok(_serialize_binding(binding)) + + +# ---- 凭据引用 ---- + +@integration_connector_bp.route('/credential-references', methods=['GET']) +@require_admin +def list_credential_references(): + rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all() + return ok([_serialize_credential(row) for row in rows]) + + +@integration_connector_bp.route('/credential-references', methods=['POST']) +@require_admin +def create_credential_reference(): + body = request.get_json(silent=True) or {} + _require(body.get('code'), 'code') + _require(body.get('secret_ref'), 'secret_ref') + from app import db + cred = IntegrationCredentialReference( + code=str(body['code']).strip(), + secret_ref=str(body['secret_ref']).strip(), + secret_provider=str(body.get('secret_provider') or 'env').strip(), + credential_type=str(body.get('credential_type') or 'password').strip(), + version=int(body.get('version') or 1), + status=str(body.get('status') or 'active'), + ) + db.session.add(cred) + db.session.commit() + # 永不回显真实凭据值;只回元数据。 + return ok(_serialize_credential(cred), status=201) + + +@integration_connector_bp.route('/credential-references/', methods=['PUT']) +@require_admin +def update_credential_reference(code): + """更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。""" + cred = IntegrationCredentialReference.query.filter_by(code=code).first() + if cred is None: + raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND') + body = request.get_json(silent=True) or {} + if body.get('secret_ref') is not None: + _require(body.get('secret_ref'), 'secret_ref') + cred.secret_ref = str(body['secret_ref']).strip() + if body.get('secret_provider') is not None: + cred.secret_provider = str(body['secret_provider']).strip() + if body.get('credential_type') is not None: + cred.credential_type = str(body['credential_type']).strip() + if body.get('status') is not None: + cred.status = str(body['status']).strip() + from app import db + db.session.commit() + return ok(_serialize_credential(cred)) + + +# ---- 连接测试 ---- + +@integration_connector_bp.route('/client-instances//test', methods=['POST']) +@require_admin +def test_connection(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found') + gateway = get_capability_gateway() + transport = gateway.transports.get(client.connector_type) + if transport is None: + raise ValidationError( + 'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN', + ) + raw = transport.call( + client={'config_json': client.config_json or {}, 'credential': {}}, + interface={'request_spec_json': {}}, + request={}, + ) + return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw}) diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 44041498..4b69c224 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -256,15 +256,6 @@ def tool_match_inventory(): resume_gate_code='inventory_matching', )) -@shipping_notice_bp.route('/tools/submit_decision', methods=['POST']) -def tool_submit_decision(): - """ - 提交人工决策。 - 【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。 - """ - return jsonify(shipping_tools.submit_decision(_payload())) - - @shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) def tool_confirm_customer(): """ diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py index dde84dcb..d05d0a1e 100644 --- a/backend/app/api/tools/__init__.py +++ b/backend/app/api/tools/__init__.py @@ -2,11 +2,10 @@ backend/app/api/tools/__init__.py 用途:Dify HTTP Tool API Blueprint 聚合。 -逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。 +逻辑:re-export shipping_notice、file_check、maintenance tools。 """ from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401 from app.api.tools.file_check import file_check_bp # noqa: F401 from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401 -from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401 -__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp'] +__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp'] diff --git a/backend/app/api/tools/voucher_check.py b/backend/app/api/tools/voucher_check.py deleted file mode 100644 index f06e6f84..00000000 --- a/backend/app/api/tools/voucher_check.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -backend/app/api/tools/voucher_check.py - -用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。 -依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。 -逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。 -""" - -from __future__ import annotations - -from flask import Blueprint, jsonify, request - -from app.core.errors import AppError -from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE -from app.services.integration_tool_auth import require_integration_tool_auth -from app.services.voucher_check import query_service -from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec - -voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__) - - -@voucher_check_tools_bp.before_request -def _verify_tool_access(): - """openapi.json 免鉴权,其余端点校验 Tool API Key。""" - if request.path.endswith("/openapi.json"): - return None - require_integration_tool_auth() - return None - - -def _tool_error(exc: AppError): - """将 AppError 映射为 Tool 非 envelope 错误体。""" - code = str(exc.code or "").lower().replace(".", "_") - message = str(exc.message or "").strip() - # 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支 - if message in {"missing_auth", "invalid_auth"}: - code = message - return jsonify({ - "ok": False, - "error_code": code, - "message": message or code, - "details": exc.details or {}, - }), exc.http_status - - -@voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"]) -def voucher_check_openapi_spec(): - """ - 返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。 - 【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。 - """ - return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) - - -@voucher_check_tools_bp.route("/tools/tasks//missing", methods=["GET"]) -def tool_list_missing(task_id: int): - """ - 查询当前月或指定月缺资料票。 - 【AI 触发时机】:用户说「查询缺资料发票」时调用。 - """ - try: - data = query_service.list_missing_states( - task_id=task_id, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - limit=request.args.get("limit", default=200, type=int) or 200, - ) - return jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) - - -@voucher_check_tools_bp.route("/tools/runs//items", methods=["GET"]) -def tool_list_run_items(run_id: int): - """ - 查询批次明细,可按 result 过滤。 - 【AI 触发时机】:用户查询某批次结果明细时调用。 - """ - try: - data = query_service.list_run_items( - run_id=run_id, - result=request.args.get("result"), - page=request.args.get("page", default=1, type=int) or 1, - page_size=request.args.get("page_size", default=50, type=int) or 50, - ) - return jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) - - -@voucher_check_tools_bp.route("/tools/invoices//latest", methods=["GET"]) -def tool_invoice_latest(invoice_no: str): - """ - 查询指定发票最新状态。 - 【AI 触发时机】:用户询问某张发票检核结论时调用。 - """ - try: - data = query_service.get_invoice_latest( - invoice_no=invoice_no, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - ) - return jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) diff --git a/backend/app/api/user/auth_local.py b/backend/app/api/user/auth_local.py index 234a22c6..6e134ba3 100644 --- a/backend/app/api/user/auth_local.py +++ b/backend/app/api/user/auth_local.py @@ -101,7 +101,7 @@ def login(): @auth_bp.post('/change-password', endpoint='change_password') def change_password(): - """校验当前身份并同步更新本地与 Casdoor 密码。""" + """校验当前身份并同步更新本地与 Casdoor 密码;新密码与原密码相同直接 400。""" user = _compat._get_current_user() if not user: raise UnauthorizedError('Unauthorized') @@ -110,6 +110,12 @@ def change_password(): new_password = data.get('new_password') if not current_password or not new_password: raise ValidationError('Current and new password are required') + if current_password == new_password: + raise AppError( + code='AUTH.PASSWORD_UNCHANGED', + message='New password must differ from the current password', + http_status=400, + ) try: _compat._verify_current_password_for_change(user, current_password) _compat._sync_casdoor_password(user.username, current_password, new_password) diff --git a/backend/app/api/user/auth_support.py b/backend/app/api/user/auth_support.py index f47704f7..30fbea84 100644 --- a/backend/app/api/user/auth_support.py +++ b/backend/app/api/user/auth_support.py @@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro from app.services.agent_registry.serialization import serialize_registry_fields 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 +from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError from sqlalchemy import and_, or_, inspect, insert from datetime import datetime, timedelta @@ -324,12 +324,15 @@ def _verify_current_password_for_change(user, current_password: str): raise def _sync_casdoor_password(username: str, current_password: str, new_password: str): + """将用户自助改密同步到 Casdoor;新密码未变化原样抛出,原密码错误转为 403。""" if not _is_casdoor_configured(): return user_owner = _casdoor_user_owner() try: _casdoor_set_password(user_owner, username, current_password, new_password) except AppError as first_error: + if first_error.code == 'AUTH.PASSWORD_UNCHANGED': + raise if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'): _raise_incorrect_current_password() raise diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 3587f846..4249ef79 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -22,12 +22,12 @@ from app import db from app.core.auth.jwt import get_current_user from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.response import ok -from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice +from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.constants import ( AUTO_CHAIN_FALLBACK, - CP_EXPORT_GENERATED, - CP_NOTICE_TEXT_EXTRACTION_FAILED, + POSITION_EXPORT_GENERATED, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, ) from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership from app.services.shipping_notice.query_service import ( @@ -53,7 +53,6 @@ from app.services.shipping_notice.customer_identity_gate import ( confirm_task_customer, list_customer_options, ) -from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) @@ -145,6 +144,16 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No ) +def _require_formal_notice(task: Any) -> ShippingNotice: + """正式 Notice 专属接口的实体守卫;OT 在库存门禁前不得进入通知/上传写路径。""" + if not isinstance(task, ShippingNotice): + raise ValidationError( + 'Formal shipping notice is required for this operation', + code='SHIPPING.FORMAL_NOTICE_REQUIRED', + ) + return task + + @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): """分页列出当前用户可见的发货任务,可按处理状态过滤。""" @@ -214,7 +223,7 @@ def _batch_task_nos(data: dict) -> list[str]: return normalized -def _can_dispose_task(user, task: ShippingNotice) -> bool: +def _can_dispose_task(user, task) -> bool: """管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。""" return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id} @@ -372,96 +381,6 @@ def workspace_confirm_shipping_customer(task_no: str): return _ok(serialize_task_detail(updated)) -@workspace_shipping_notice_bp.route( - '/shipping-order-extractions//customer-matches//confirm', - methods=['POST'], -) -def workspace_confirm_order_customer_match(extraction_id: int, role: str): - """确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。""" - user = _require_user() - extraction = ( - db.session.query(ShippingOrderExtraction) - .join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id) - .filter( - ShippingOrderExtraction.id == extraction_id, - ShippingOrderIntake.user_id == user.id, - ) - .one_or_none() - ) - if extraction is None: - raise NotFoundError( - 'Order extraction not found', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - data = request.get_json(silent=True) or {} - try: - customer_id = int(data.get('customer_id')) - site_id = int(data['site_id']) if data.get('site_id') is not None else None - except (TypeError, ValueError) as exc: - raise ValidationError( - 'Customer id is required', - code='SHIPPING.ORDER_CUSTOMER_REQUIRED', - details={'field': 'customer_id'}, - ) from exc - result = confirm_order_customer_match( - extraction.id, - role=role, - customer_id=customer_id, - site_id=site_id, - actor_id=user.id, - reason=str(data.get('reason') or ''), - commit=False, - ) - # [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。 - # 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。 - if role == 'bill_to': - from app.models import ( - ShippingOrderCandidate, - ShippingOrderReviewCase, - ShippingOrderReviewStream, - ) - from app.services.shipping_notice.order_review_auto_progress_coordinator import ( - reconcile_single_case_for_auto_progress, - ) - _TERMINAL = frozenset({ - 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', - }) - candidates = list( - ShippingOrderCandidate.query - .filter_by(order_extraction_id=int(extraction.id)) - .all() - ) - candidate_ids = {int(c.id) for c in candidates} - case = None - if candidate_ids: - case = ( - ShippingOrderReviewCase.query - .join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ) - .filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids)) - .first() - ) - if case is None and extraction.run_id: - case = ( - ShippingOrderReviewCase.query - .join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ) - .filter(ShippingOrderReviewCase.run_id == int(extraction.run_id)) - .first() - ) - if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id: - reconcile_single_case_for_auto_progress( - case=case, - trigger='extraction_customer_confirmed', - refresh_validation=True, - ) - db.session.commit() - return _ok(result) - @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) def workspace_create_shipping_task_from_notice(): """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" @@ -491,12 +410,15 @@ def workspace_create_shipping_task_from_notice(): task_no=task_id, ) if not intake.accepted: - return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED}) - task = ShippingNotice.query.filter_by(task_no=task_id).first() + return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED}) + from app.models import ShippingOrderTask + from app.models import ShippingOrderIntake + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() if task: - task.raw_content = intake.text - task.source_file_name = intake.filename or task.source_file_name - task.source_file_type = intake.source_file_type or task.source_file_type + intake_row = db.session.get(ShippingOrderIntake, task.intake_id) if task.intake_id else None + if intake_row is not None: + intake_row.extracted_text = intake.text + intake_row.parse_warnings_json = list(intake.warnings or []) db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator orchestrator_started = start_task_orchestrator(task_id) @@ -540,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str): 返回指定任务的详情快照与内嵌 UI State。 核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到 - checkpoint / actions / steps,减少前端二次推导与竞态刷新。 + position / user_mode / actions / steps,减少前端二次推导与竞态刷新。 """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' @@ -548,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str): task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin) if not task: raise NotFoundError('Not found') - # [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段, - # 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。 + # [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich; + # 缺省/非法值一律回退 full,保持兼容。 view = str(request.args.get('view', 'full') or 'full').strip().lower() if view not in ('full', 'workbench'): view = 'full' @@ -637,6 +559,7 @@ def workspace_update_shipping_notice_fields(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} fields = data.get('fields') if not isinstance(fields, dict) or not fields: @@ -683,6 +606,7 @@ def workspace_update_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} try: line_index = int(data.get('line_index')) @@ -771,6 +695,7 @@ def workspace_add_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} line = data.get('line') if not isinstance(line, dict) or not line: @@ -796,6 +721,7 @@ def workspace_remove_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} try: line_index = int(data.get('line_index')) @@ -834,11 +760,15 @@ def workspace_auto_progress_shipping_task(task_no: str): str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id), ) - # 兼容旧前端:若仍有 export 路径则附带 download_url。 + # 导出下载路径只从当前有效 Artifact 读取,Notice 不再保存文件投影。 if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}: - # 重新加载任务以读取 export_file_path(若决策器已推进到导出)。 refreshed = get_task_for_user(task_no, user.id) - export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None + artifact = None + if refreshed is not None: + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + artifact = latest_export_artifact(refreshed) + export_path = getattr(artifact, 'file_path', None) if export_path: result = { **result, @@ -862,6 +792,7 @@ def workspace_mark_manual_uploaded(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) _assert_fulfillment_task_ownership(task, user.id) from app.services.shipping_notice import tools as shipping_tools data = request.get_json(silent=True) or {} @@ -1139,6 +1070,7 @@ def workspace_shipping_task_export(task_no: str): """下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" user = _require_user() task = get_task_for_user(task_no, user.id) + task = _require_formal_notice(task) err_msg = task_export_error_message(task) if err_msg: raise NotFoundError(err_msg) @@ -1900,19 +1832,17 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//fields/', methods=['PATCH']) -def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str): - """修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。""" +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//fields/', methods=['PATCH']) +def workspace_patch_shipping_order_review_line_field(case_no: str, draft_line_id: str, field_id: str): + """修改或恢复一个复核订单行字段;行只接受服务端返回的 draft_line_id。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import patch_line_field payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed') result = patch_line_field( - user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'), + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, field_id=field_id, value=payload.get('value'), expected_draft_version=payload.get('expected_draft_version'), restore_machine=bool(payload.get('restore_machine')), - override_reason_code=payload.get('override_reason_code'), - override_reason_text=payload.get('override_reason_text'), ) db.session.commit() return _ok(result) @@ -1930,30 +1860,30 @@ def workspace_add_shipping_order_review_line(case_no: str): return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//copy', methods=['POST']) -def workspace_copy_shipping_order_review_line(case_no: str, line_key: str): +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//copy', methods=['POST']) +def workspace_copy_shipping_order_review_line(case_no: str, draft_line_id: str): """复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import copy_line payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied') result = copy_line( - user_id=user.id, case_no=case_no, line_key=line_key, + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, expected_draft_version=payload.get('expected_draft_version'), ) db.session.commit() return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines/', methods=['DELETE']) -def workspace_delete_shipping_order_review_line(case_no: str, line_key: str): +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines/', methods=['DELETE']) +def workspace_delete_shipping_order_review_line(case_no: str, draft_line_id: str): """删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import delete_line payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted') result = delete_line( - user_id=user.id, case_no=case_no, line_key=line_key, + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, expected_draft_version=payload.get('expected_draft_version'), ) db.session.commit() @@ -1992,7 +1922,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str): """ 按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。 - 核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。 + 核心逻辑:可选 draft_line_id;携带 expected_draft_version 与幂等键。 """ user = _require_user() from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing @@ -2005,7 +1935,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str): case_no=case_no, expected_draft_version=payload.get('expected_draft_version'), idempotency_key=payload.get('idempotency_key'), - line_key=payload.get('line_key'), + draft_line_id=payload.get('draft_line_id'), ) db.session.commit() return _ok(result) @@ -2122,7 +2052,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str): """ 写入行级履约决定。 - Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version? + Body: draft_line_id, decision_code, reason?, release_field_values?, expected_draft_version? """ user = _require_user() data = request.get_json(silent=True) or {} @@ -2134,7 +2064,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str): result = decide_review_line_fulfillment( user_id=user.id, case_no=case_no, - line_key=str(data.get('line_key') or ''), + draft_line_id=str(data.get('draft_line_id') or ''), decision_code=str(data.get('decision_code') or ''), reason=str(data.get('reason') or '').strip() or None, release_field_values=( @@ -2156,7 +2086,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): """ 为选中完整明细行创建履约波次。 - Body: line_keys[], expected_draft_version, idempotency_key, reason? + Body: snapshot_line_ids[], expected_draft_version, idempotency_key, reason? 只允许正式 OT 走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须 先完成正式建单,避免同一业务动作存在两套推进事实。 @@ -2171,14 +2101,14 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or '')) formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False} - line_keys = list(data.get('line_keys') or []) + snapshot_line_ids = list(data.get('snapshot_line_ids') or []) idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key') reason = str(data.get('reason') or '').strip() or None if formal.get('has_formal_ot'): result = create_post_ot_fulfillment_wave( case_no=str(case_no), - line_keys=line_keys, + snapshot_line_ids=snapshot_line_ids, decision_source='user', actor_user_id=int(user.id), reason=reason, @@ -2190,7 +2120,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): progress = schedule_post_ot_wave_progress( task_no=str(result.get('task_no') or ''), wave_no=result.get('wave_no'), - line_keys=list(result.get('accepted_line_keys') or line_keys), + snapshot_line_ids=list(result.get('accepted_snapshot_line_ids') or snapshot_line_ids), review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None, idempotency_row_id=result.get('idempotency_row_id'), request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None, @@ -2223,7 +2153,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str): """ 关闭行级或 Case 剩余开放行。 - Body: reason, line_keys?, expected_draft_version? + Body: reason, draft_line_ids?, expected_draft_version? """ user = _require_user() data = request.get_json(silent=True) or {} @@ -2236,7 +2166,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str): user_id=user.id, case_no=case_no, reason=str(data.get('reason') or ''), - line_keys=list(data.get('line_keys') or []) or None, + draft_line_ids=list(data.get('draft_line_ids') or []) or None, expected_draft_version=data.get('expected_draft_version'), actor_is_admin=is_admin, ) @@ -2349,9 +2279,7 @@ def workspace_confirm_shipping_order_review_case(case_no: str): user = _require_user() from app.services.shipping_notice.order_review_confirmation_service import ( confirm_review_case, - finalize_sync_auto_progress_after_commit, resolve_confirm_outcome, - schedule_auto_progress_after_review_confirm, ) payload = _review_draft_payload( @@ -2366,14 +2294,22 @@ def workspace_confirm_shipping_order_review_case(case_no: str): warning_acknowledgements=payload.get('warning_acknowledgements'), ) # [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。 + # 复核确认只产生 OT;正式 ShippingNotice 尚未生成,不能把 OT 编号投递到 + # 旧的 notice-run Job。库存源候选的裁决/冻结确认后由正式 inventory_source_routing + # Gate 负责;通过 schedule_auto_progress_after_review_confirm 入队自动推进, + # 使 OT 在不冻结候选的情况下仍能走到库存链路。 + from app.services.shipping_notice.order_review_confirmation_service import ( + finalize_sync_auto_progress_after_commit, + schedule_auto_progress_after_review_confirm, + ) progress = schedule_auto_progress_after_review_confirm( - task_no=result.get('task_no'), + task_no=str(result.get('task_no')), idempotent_replay=bool(result.get('idempotent_replay')), created_by_id=int(user.id), commit=False, ) # [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op) - if result.get('task_no') and not result.get('idempotent_replay'): + if result.get('shipping_notice_no') and not result.get('idempotent_replay'): from app.services.shipping_notice.line_auto_fulfill_coordinator import ( enqueue_post_ot_auto_fulfill_job, ) @@ -2383,8 +2319,8 @@ def workspace_confirm_shipping_order_review_case(case_no: str): commit=False, ) db.session.commit() - # [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。 progress = finalize_sync_auto_progress_after_commit(progress) + # [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。 result = dict(result) result.pop('trigger_auto_progress', None) result['confirm_ok'] = True @@ -2395,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str): 'message': '无需调度自动推进,或任务已离开待推进态', } else: + # [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。 + position = progress.get('position') + user_mode = progress.get('user_mode') + if not position or not user_mode: + try: + from app.models import ShippingOrderTask + from app.services.shipping_notice.progress_workflow import ( + _entry_position, + _entry_user_mode, + ) + + ot = ( + db.session.query(ShippingOrderTask) + .filter( + ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper() + ) + .first() + ) + if ot is not None: + position = position or _entry_position(ot) + user_mode = user_mode or _entry_user_mode(ot) + except Exception: + pass result['auto_progress_started'] = bool(progress.get('auto_progress_started')) result['auto_progress'] = { 'status': progress.get('status'), 'message': progress.get('message'), 'enqueue_result': progress.get('enqueue_result'), - 'checkpoint': progress.get('checkpoint'), + 'position': position, + 'user_mode': user_mode, } result['confirm_outcome'] = resolve_confirm_outcome( { @@ -2632,7 +2592,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str): user_id=user.id, case_no=case_no, field_id=str(payload.get('field_id') or ''), - line_key=payload.get('line_key'), + draft_line_id=payload.get('draft_line_id'), evidence_level=payload.get('evidence_level'), issue_code=payload.get('issue_code'), allow_full_pdf=bool(payload.get('allow_full_pdf')), diff --git a/backend/app/api/workspace/voucher_check.py b/backend/app/api/workspace/voucher_check.py index 4a471c7e..4a5e8d96 100644 --- a/backend/app/api/workspace/voucher_check.py +++ b/backend/app/api/workspace/voucher_check.py @@ -1,9 +1,9 @@ """ backend/app/api/workspace/voucher_check.py -用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。 +用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。 依赖:auth.jwt、response_utils envelope、voucher_check.query_service。 -逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。 +逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。 """ from __future__ import annotations @@ -11,7 +11,7 @@ from __future__ import annotations from flask import Blueprint, request from app.core.auth.jwt import get_current_user -from app.core.errors import UnauthorizedError +from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError from app.core.response import ok from app.services.voucher_check import query_service @@ -25,11 +25,55 @@ def _require_user(): return user +def _require_admin(): + """工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。""" + user = _require_user() + if getattr(user, "role", None) != "admin": + raise ForbiddenError("Admin privilege required") + return user + + +@workspace_voucher_check_bp.route("/accounting-voucher-check/runs", methods=["GET"]) +def workspace_voucher_runs(): + """ + 分页查看检核任务列表。 + 核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。 + """ + _require_user() + data = query_service.list_runs( + period=request.args.get("period"), + profile_code=request.args.get("profile_code"), + status=request.args.get("status"), + page=request.args.get("page", default=1, type=int) or 1, + page_size=request.args.get("page_size", default=50, type=int) or 50, + ) + return ok(data) + + +@workspace_voucher_check_bp.route("/accounting-voucher-check/runs", methods=["POST"]) +def workspace_voucher_force_run(): + """ + 强制重检上一个自然月(不走增量跳过)。 + 核心逻辑:body.mode 仅接受 force_all;入队默认周批排程,由 schedule worker 执行。 + """ + user = _require_admin() + payload = request.get_json(silent=True) or {} + mode = str(payload.get("mode") or "force_all").strip().lower() + if mode != "force_all": + raise ValidationError( + "工作台仅支持 force_all", + code="VOUCHER_CHECK.CONFIG_INVALID", + details={"mode": mode}, + ) + data = query_service.enqueue_force_all_run(triggered_by_user_id=getattr(user, "id", None)) + return ok(data) + + @workspace_voucher_check_bp.route("/accounting-voucher-check/runs//items", methods=["GET"]) def workspace_voucher_run_items(run_id: int): """ 分页查看批次明细。 - 核心逻辑:委托 query_service.list_run_items,可按 result 过滤。 + 核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。 """ _require_user() data = query_service.list_run_items( @@ -41,30 +85,17 @@ def workspace_voucher_run_items(run_id: int): return ok(data) -@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"]) -def workspace_voucher_states(): +@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"]) +def workspace_voucher_notifications(): """ - 按月份、状态、发票号筛选最新状态。 + 分页查看企微缺件汇总发送记录。 + 核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。 """ _require_user() - data = query_service.list_states( - scope_code=str(request.args.get("scope_code") or "HXJM"), + data = query_service.list_notifications( period=request.args.get("period"), - status=request.args.get("status"), - invoice_no=request.args.get("invoice_no"), + send_status=request.args.get("send_status"), page=request.args.get("page", default=1, type=int) or 1, page_size=request.args.get("page_size", default=50, type=int) or 50, ) return ok(data) - - -@workspace_voucher_check_bp.route("/accounting-voucher-check/states/", methods=["GET"]) -def workspace_voucher_state_detail(invoice_no: str): - """查看单票最近状态和历史批次快照。""" - _require_user() - data = query_service.get_invoice_latest( - invoice_no=invoice_no, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - ) - return ok(data) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 50c71be7..b35906f0 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -216,8 +216,8 @@ class Config: # 统一改用通用 ERP 连接变量(ERP_DB_DSN / ERP_USERNAME / ERP_PASSWORD / ERP_TIMEOUT_SECONDS,已并入 env.shared), # 并保留模块级 CONTRACT_PAYMENT_ERP_* 覆盖与旧回退(VOUCHER_CHECK_ERP_*)兼容。 CONTRACT_PAYMENT_ERP_DSN = os.getenv('CONTRACT_PAYMENT_ERP_DSN') or os.getenv('ERP_DB_DSN', '') - CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') or os.getenv('VOUCHER_CHECK_ERP_USERNAME', '') - CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') or os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '') + CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') + CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30') CONTRACT_DMS_BASE_URL = os.getenv('CONTRACT_DMS_BASE_URL', '').strip().rstrip('/') CONTRACT_DMS_USERNAME = os.getenv('CONTRACT_DMS_USERNAME', '') @@ -329,6 +329,28 @@ class Config: SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower() SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2')) SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2')) + # 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。 + IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2')) + IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2')) + IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1')) + IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60' + ) + IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60' + ) + IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600' + ) + IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3') + IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') + IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') + # ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。 + IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip() + IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip() + IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip() + IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip() + IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') ) @@ -630,17 +652,26 @@ class Config: FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser') FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod') - # 立账凭证检核:共享盘只读根 + Oracle 只读账号(密码仅 env) - VOUCHER_CHECK_SHARE_UNC = os.getenv('VOUCHER_CHECK_SHARE_UNC', '').strip() - VOUCHER_CHECK_LOCAL_ROOT = os.getenv('VOUCHER_CHECK_LOCAL_ROOT', '').strip() - VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH = os.getenv( - 'VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH', - '.hxops-share-ready', - ).strip() or '.hxops-share-ready' + # 立账凭证检核:ERP 只读 + 销售开票附件文档库根目录(密码仅 env) VOUCHER_CHECK_ERP_DSN = os.getenv('VOUCHER_CHECK_ERP_DSN') or os.getenv('ERP_DB_DSN', '') - VOUCHER_CHECK_ERP_USERNAME = os.getenv('VOUCHER_CHECK_ERP_USERNAME', '').strip() - VOUCHER_CHECK_ERP_PASSWORD = os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '') - VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS', '30') or '30') + VOUCHER_CHECK_ERP_USERNAME = ( + os.getenv('VOUCHER_CHECK_ERP_USERNAME') + or os.getenv('ERP_USERNAME') + or os.getenv('CONTRACT_PAYMENT_ERP_USERNAME', '') + ).strip() + VOUCHER_CHECK_ERP_PASSWORD = ( + os.getenv('VOUCHER_CHECK_ERP_PASSWORD') + or os.getenv('ERP_PASSWORD') + or os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD', '') + ) + VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int( + os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30' + ) + VOUCHER_CHECK_DMS_BASE_URL = os.getenv('VOUCHER_CHECK_DMS_BASE_URL', '').strip().rstrip('/') + VOUCHER_CHECK_DMS_USERNAME = os.getenv('VOUCHER_CHECK_DMS_USERNAME', '').strip() + VOUCHER_CHECK_DMS_PASSWORD = os.getenv('VOUCHER_CHECK_DMS_PASSWORD', '') + VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip() + VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip() # MinIO 配置 MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000') diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index db5118ee..06f5783b 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -8,6 +8,9 @@ backend/app/jobs/handlers/__init__.py from app.jobs.handlers import ( # noqa: F401 contract_payment, file_check_run, + in_transit_transfer_item, + in_transit_transfer_precheck, + in_transit_transfer_run, kb_clean, kb_dify_sync, procurement_contract_review, diff --git a/backend/app/jobs/handlers/in_transit_transfer_item.py b/backend/app/jobs/handlers/in_transit_transfer_item.py new file mode 100644 index 00000000..c2e90f3b --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_item.py @@ -0,0 +1,29 @@ +"""backend/app/jobs/handlers/in_transit_transfer_item.py + +用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。 +依赖:execution_service.execute_item、transfer deps、Job 注册表。 +逻辑:payload 携带 item_id;单项结果不影响其他项。 +""" + +from __future__ import annotations + +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.execution_service import execute_item + + +@register_handler(JobType.TRANSFER_ITEM) +def run_in_transit_transfer_item(_ctx, payload: dict) -> None: + """执行单个 Invoice(异步路径)。 + + 【AI 触发时机】:仅由 Item 入队路径调用;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + item_id = payload.get("item_id") + if item_id is None: + raise RuntimeError("missing_transfer_item_id") + execute_item( + item_id=int(item_id), + deps=transfer_deps.get_transfer_dependencies(), + ) diff --git a/backend/app/jobs/handlers/in_transit_transfer_precheck.py b/backend/app/jobs/handlers/in_transit_transfer_precheck.py new file mode 100644 index 00000000..b43dc20c --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_precheck.py @@ -0,0 +1,55 @@ +"""backend/app/jobs/handlers/in_transit_transfer_precheck.py + +用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。 +依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。 +逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写 + 状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。 +""" + +from __future__ import annotations + +from app import db +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import TransferPrecheck +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.precheck_service import run_precheck + + +@register_handler(JobType.TRANSFER_PRECHECK) +def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None: + """执行一次预检 Job 并更新预检状态。 + + 【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + precheck_no = str(payload.get("precheck_id") or "").strip() + if not precheck_no: + raise RuntimeError("missing_transfer_precheck_id") + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first() + if precheck is None: + raise RuntimeError(f"missing_transfer_precheck: {precheck_no}") + + deps = transfer_deps.get_transfer_dependencies() + source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance( + precheck.scope_json, dict + ) else [] + result = run_precheck( + source_codes=source_codes, + business_date=precheck.business_date, + deps=deps, + run_no=precheck.run.run_no if precheck.run else "RUN-PENDING", + ) + summary = result.summary + precheck.status = summary.status + precheck.counts_json = { + "file_invoice_count": summary.counts.file_invoice_count, + "not_matured_count": summary.counts.not_matured_count, + "prechecked_count": summary.counts.prechecked_count, + "executable_count": summary.counts.executable_count, + "blocked_count": summary.counts.blocked_count, + } + precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity + precheck.estimated_erp_write_count = summary.estimated_erp_write_count + precheck.precheck_hash = summary.precheck_hash + db.session.commit() diff --git a/backend/app/jobs/handlers/in_transit_transfer_run.py b/backend/app/jobs/handlers/in_transit_transfer_run.py new file mode 100644 index 00000000..161ed59f --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_run.py @@ -0,0 +1,29 @@ +"""backend/app/jobs/handlers/in_transit_transfer_run.py + +用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。 +依赖:execution_service、transfer deps、Job 注册表。 +逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。 +""" + +from __future__ import annotations + +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.execution_service import execute_precheck + + +@register_handler(JobType.TRANSFER_RUN) +def run_in_transit_transfer_run(_ctx, payload: dict) -> None: + """执行一个 Run(异步路径)。 + + 【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + precheck_id = str(payload.get("precheck_id") or "").strip() + if not precheck_id: + raise RuntimeError("missing_transfer_precheck_id") + execute_precheck( + precheck_id=precheck_id, + deps=transfer_deps.get_transfer_dependencies(), + ) diff --git a/backend/app/jobs/handlers/shipping_inventory_callback_process.py b/backend/app/jobs/handlers/shipping_inventory_callback_process.py index 484c613a..0fd3fe3a 100644 --- a/backend/app/jobs/handlers/shipping_inventory_callback_process.py +++ b/backend/app/jobs/handlers/shipping_inventory_callback_process.py @@ -35,15 +35,24 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N result = process_rpa_report_inventory_batch(dict(job.payload_json or {})) result_data = result.get('data') if isinstance(result, dict) else None + transport_status = str( + result.get('status') if isinstance(result, dict) else '' + ).strip().lower() result_status = str( (result_data or {}).get('result_status') if isinstance(result_data, dict) else '' ).strip().lower() - if result_status in {'failed', 'partial_failed'}: + if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}: failed_items = result_data.get('failed') if isinstance(result_data, dict) else [] first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None + from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback + + settle_failed_inventory_callback( + dict(job.payload_json or {}), + error=str(first_error or (result or {}).get('message') or 'inventory_callback_processing_failed'), + ) fail_job( job.id, - error=str(first_error or f'inventory_callback_business_{result_status}'), + error=str(first_error or (result or {}).get('message') or f'inventory_callback_business_{result_status or transport_status}'), result={'status': 'processed', 'callback_result': result}, retryable=False, owned_attempt=owned_attempt, diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py index 14be740a..a0c3c123 100644 --- a/backend/app/jobs/handlers/shipping_notice_parse.py +++ b/backend/app/jobs/handlers/shipping_notice_parse.py @@ -16,9 +16,9 @@ from datetime import datetime from sqlalchemy import and_, or_, update from app import db -from app.core.errors import AppError, NotFoundError +from app.core.errors import NotFoundError from app.jobs.context import JobContext -from app.jobs.queue import fail_job, finish_job +from app.jobs.queue import _is_retryable_exc, fail_job, finish_job from app.jobs.registry import register_handler from app.jobs.types import JobType from app.models import FileAsset, Job, ShippingOrderIntake @@ -120,15 +120,6 @@ def _claim_intake_for_parsing( return intake, lease -def _is_retryable_exc(exc: BaseException) -> bool: - """业务 NotFound / AppError.retryable=False 视为不可再排队。""" - if isinstance(exc, NotFoundError): - return False - if isinstance(exc, AppError): - return bool(getattr(exc, 'retryable', False)) - return True - - @register_handler(JobType.SHIPPING_NOTICE_PARSE) def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: """ @@ -264,7 +255,9 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: # 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回) if str(fail_result.get('reason') or '') == 'stale_parse_lease': return - retryable = False + # 失败收口按异常类型分级:业务失败(NotFound/AppError.retryable=False)停排, + # 瞬时基础设施异常才允许重试;不按业务域一刀切。 + retryable = _is_retryable_exc(exc) if job_id is not None: fail_job( job_id, @@ -272,3 +265,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: retryable=retryable, owned_attempt=owned_attempt, ) + # 重试类异常交由外层运行时统一收口(fail_job 已 requeue);非重试业务失败已直接 + # fail_job 为 failed,不再重抛,避免向上滚动。 + if retryable: + raise diff --git a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py index 987f87e8..00a33702 100644 --- a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py +++ b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py @@ -67,7 +67,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non gen = generate_excel({ 'task_id': task.task_no, 'wave_no': wave_no, - 'line_keys': list(frozen.get('line_keys') or []), + 'snapshot_line_ids': list(frozen.get('snapshot_line_ids') or []), 'post_ot_wave': True, '_orchestrator_internal_dispatch': True, }) diff --git a/backend/app/jobs/handlers/shipping_process_gate.py b/backend/app/jobs/handlers/shipping_process_gate.py index 233e9f2f..4ddb205f 100644 --- a/backend/app/jobs/handlers/shipping_process_gate.py +++ b/backend/app/jobs/handlers/shipping_process_gate.py @@ -84,6 +84,18 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: attempt_id = int(payload.get('attempt_id') or 0) raw_job_id = payload.get('job_id') job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + external_wait_poll_gate_id = int(payload.get('external_wait_poll_gate_id') or 0) + if external_wait_poll_gate_id and job is not None: + from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll + + result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id) + finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0)) + if str(result.get('gate_status') or '') == 'waiting_external': + gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id) + if gate is not None and gate.latest_attempt_id: + schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id)) + db.session.commit() + return if attempt_id <= 0 or job is None: raise RuntimeError('missing_attempt_id_or_job_id') diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py index 4478675b..7810d6b9 100644 --- a/backend/app/jobs/handlers/shipping_stp_auto_create.py +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -10,7 +10,8 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py 逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单; 成功 finish,附加 task_no / idempotent_replay; 失败统一走 _classify_stp_result: - - 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) + - 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) + - 临时基础设施异常 → retryable=true(保留普通重试入口) """ from __future__ import annotations @@ -51,11 +52,10 @@ def _classify_stp_job_result( 【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、 非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。 - 核心逻辑(fail-closed): - [STEP 1] build_stp_job_blocked_manual_result: - derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review; - details 合并至 blocking_reason_details。 - [STEP 2] 返回三元组(False, normalized_result_dict, next_action)。 + 核心逻辑: + [STEP 1] temporary_storage_error 走技术失败契约,允许普通重试; + [STEP 2] 其他错误走 build_stp_job_blocked_manual_result,要求人工裁决; + [STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。 Args: error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。 @@ -71,6 +71,23 @@ def _classify_stp_job_result( # 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。 if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED': message = '自动建单失败,已停止,等待用户选择下一步动作' + if category_hint == 'temporary_storage_error': + next_action = 'retry_stp_auto_create' + return True, { + 'status': 'failed', + 'retryable': True, + 'error_code': str(error_code or '').strip(), + 'message': str(message or ''), + 'next_action': next_action, + 'contract_version': 'shipping-recovery-v1-phase1', + 'decision_trace': { + 'contract_version': 'shipping-recovery-v1-phase1', + 'stage': 'stp_classify_error', + 'retryable': True, + 'matched_rule': 'temporary_storage_error', + 'category_hint': category_hint, + }, + }, next_action actions = derive_blocking_next_actions(blocking_reason=error_code) next_action = actions[0] if actions else 'open_order_review' blocked: dict[str, Any] = build_stp_job_blocked_manual_result( diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py index e4ae7eb4..f9e0fe8b 100644 --- a/backend/app/jobs/queue.py +++ b/backend/app/jobs/queue.py @@ -23,7 +23,7 @@ from sqlalchemy.exc import IntegrityError, OperationalError from sqlalchemy.orm import Session from app import db -from app.core.errors import ValidationError +from app.core.errors import AppError, NotFoundError, ValidationError from app.jobs.types import JobType from app.models import Job @@ -43,6 +43,19 @@ def _orm_session() -> Session: return db.session() +def _is_retryable_exc(exc: BaseException) -> bool: + """按异常类型分级判断任务失败是否可重试(通用裁定,不区分业务域)。 + + 业务 NotFound / AppError.retryable=False(含 ValidationError)视为不可再排队; + 仅瞬时基础设施异常(503 ServiceUnavailable 或未归类异常)才允许重试。 + """ + if isinstance(exc, NotFoundError): + return False + if isinstance(exc, AppError): + return bool(getattr(exc, 'retryable', False)) + return True + + def _ensure_outer_dbapi_transaction(session: Session) -> None: """ 确保 begin_nested() 不会成为数据库最外层事务。 @@ -582,7 +595,7 @@ def recover_stale_jobs( sibling: Job | None = None rowcount = 0 - if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts: + if snap_attempts < max_attempts: if _subject_to_parse_queued_unique(str(job.job_type or "")): try: sibling = _resolve_safe_supersede_sibling( @@ -1069,12 +1082,12 @@ def process_next_job( return True, job_type_value except Exception as exc: db.session.rollback() - # 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。 - # 其它领域维持既有技术重试策略。 + # 失败收口的可重试性由异常类型分级裁定,不按业务域一刀切; + # handler 已自行 fail_job 收敛的绝不应进入此处,此处仅兜底 handler 逃逸的异常。 fail_job( job_id, error=str(exc), - retryable=(str(domain or '').strip() != 'shipping_notice'), + retryable=_is_retryable_exc(exc), owned_attempt=owned_attempt, ) raise diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index f71c49e8..4b8f8a53 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -39,6 +39,10 @@ class JobType(StrEnum): CONTRACT_PAYMENT_SYNC = 'contract_payment_sync' CONTRACT_PAYMENT_ALERT = 'contract_payment_alert' CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly' + # 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。 + TRANSFER_PRECHECK = 'in_transit_transfer_precheck' + TRANSFER_RUN = 'in_transit_transfer_run' + TRANSFER_ITEM = 'in_transit_transfer_item' class JobStatus(StrEnum): @@ -78,6 +82,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { }), 'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}), 'schedule': frozenset({'schedule_run'}), + 'transfer': frozenset({ + 'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item', + }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index aa2badaf..9d50467b 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -79,7 +79,6 @@ from app.models.shipping_order_schema import ( ShippingOrderSchemaVersion, ShippingSchemaFamily, ) -from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch from app.models.shipping_order_snapshot import ( ShippingOrderReviewEvent, ShippingOrderSnapshot, @@ -200,8 +199,31 @@ from app.models.training import ( TrainingConfigResource, TrainingRecord, ) +from app.models.in_transit_transfer import ( + TransferArchive, + TransferAttempt, + TransferAuditEvent, + TransferInvoiceItem, + TransferPrecheck, + TransferRun, + TransferSourceJob, +) +from app.models.integration_connector import ( + IntegrationBinding, + IntegrationCall, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) +from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig -from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem +from app.models.voucher_check import ( + VoucherCheckFileResult, + VoucherCheckNotification, + VoucherCheckProfile, + VoucherCheckRun, + VoucherCheckSubject, +) from app.models.contract_payment import ( ContractPaymentAlert, ContractPaymentAlertBatch, @@ -263,7 +285,6 @@ __all__ = [ 'ShippingOrderFieldObservation', 'ShippingOrderFieldDecision', 'ShippingOrderFieldValue', - 'ShippingOrderCustomerMatch', 'ShippingOrderSnapshot', 'ShippingOrderSnapshotLine', 'ShippingOrderReviewEvent', @@ -386,8 +407,11 @@ __all__ = [ 'ShippingInventoryCandidateSource', 'ShippingInventoryCandidateLine', 'ShippingTaskInventoryRpaAttempt', - 'VoucherCheckInvoiceState', - 'VoucherCheckRunItem', + 'VoucherCheckProfile', + 'VoucherCheckRun', + 'VoucherCheckSubject', + 'VoucherCheckFileResult', + 'VoucherCheckNotification', 'ContractPaymentContract', 'ContractPaymentAttachment', 'ContractPaymentNode', @@ -396,4 +420,16 @@ __all__ = [ 'ContractPaymentAlert', 'ContractPaymentAlertBatch', 'ContractPaymentSyncState', + 'TransferRun', + 'TransferSourceJob', + 'TransferPrecheck', + 'TransferInvoiceItem', + 'TransferAttempt', + 'TransferAuditEvent', + 'TransferArchive', + 'IntegrationCredentialReference', + 'IntegrationClientInstance', + 'IntegrationInterfaceDefinition', + 'IntegrationBinding', + 'IntegrationCall', ] diff --git a/backend/app/models/content.py b/backend/app/models/content.py index d794ed4b..c88dbe4c 100644 --- a/backend/app/models/content.py +++ b/backend/app/models/content.py @@ -34,6 +34,7 @@ class QuickQuestion(Base): """ 常用问题表 用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。 + is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。 """ __tablename__ = 'quick_questions' diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py new file mode 100644 index 00000000..2b4d93a5 --- /dev/null +++ b/backend/app/models/in_transit_transfer.py @@ -0,0 +1,352 @@ +"""models/in_transit_transfer.py + +用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、 + Attempt、AuditEvent 与 Archive。 +依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。 +逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单; + Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖; + AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, + event, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.core.errors import ValidationError +from app.models.base import Base + +# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。 +TRANSFER_ITEM_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', + 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', +) +TRANSFER_RUN_STATUSES = ( + 'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'partial_failed', 'failed', 'cancelled', +) +TRANSFER_SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) +TRANSFER_PRECHECK_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'failed', 'cancelled', 'expired', +) +TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write') +TRANSFER_ATTEMPT_STATUSES = ( + 'queued', 'running', 'waiting_external', 'success', 'failed', + 'result_unknown', 'superseded', +) +TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule') + + +class TransferRun(Base): + """一次调拨执行(或只读预检)的业务真相源。""" + + __tablename__ = 'transfer_runs' + __table_args__ = ( + UniqueConstraint('run_no', name='uq_transfer_runs_run_no'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_RUN_STATUSES)})", + name='ck_transfer_runs_status', + ), + CheckConstraint( + "notification_status IN ('pending', 'success', 'failed')", + name='ck_transfer_runs_notification_status', + ), + CheckConstraint( + "trigger_type IN ('manual', 'schedule')", + name='ck_transfer_runs_trigger_type', + ), + Index('ix_transfer_runs_status_created', 'status', 'created_at'), + Index('ix_transfer_runs_business_date', 'business_date'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_no: Mapped[str] = mapped_column(String(64), nullable=False) + trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual') + business_date: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) + counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + result_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + notification_status: Mapped[str] = mapped_column( + String(16), nullable=False, default='pending', server_default='pending', + ) + notification_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + notification_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + source_jobs: Mapped[list['TransferSourceJob']] = relationship( + back_populates='run', cascade='all, delete-orphan', + ) + prechecks: Mapped[list['TransferPrecheck']] = relationship( + back_populates='run', cascade='all, delete-orphan', + ) + items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run') + + +class TransferSourceJob(Base): + """来源实例级的文件准备/预检执行单元;来源间互不阻断。""" + + __tablename__ = 'transfer_source_jobs' + __table_args__ = ( + UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_SOURCE_JOB_STATUSES)})", + name='ck_transfer_source_jobs_status', + ), + Index('ix_transfer_source_jobs_source_status', 'source_code', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + source_config_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') + file_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + lease_until: 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) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + run: Mapped[TransferRun] = relationship(back_populates='source_jobs') + + +class TransferPrecheck(Base): + """一次冻结快照的预检结果;确认/执行绑定其 Hash。""" + + __tablename__ = 'transfer_prechecks' + __table_args__ = ( + UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})", + name='ck_transfer_prechecks_status', + ), + Index('ix_transfer_prechecks_run_status', 'run_id', 'status'), + Index('ix_transfer_prechecks_business_date', 'business_date'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + precheck_no: Mapped[str] = mapped_column(String(64), nullable=False) + run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True) + business_date: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking') + scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks') + items: Mapped[list['TransferInvoiceItem']] = relationship( + back_populates='precheck', cascade='all, delete-orphan', + ) + + +class TransferInvoiceItem(Base): + """预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。""" + + __tablename__ = 'transfer_invoice_items' + __table_args__ = ( + UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})", + name='ck_transfer_invoice_items_status', + ), + Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'), + Index('ix_transfer_invoice_items_run_id', 'run_id'), + Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True) + run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + invoice_no: Mapped[str] = mapped_column(String(64), nullable=False) + material_no: Mapped[str] = mapped_column(String(64), nullable=False) + material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='') + specification: Mapped[str] = mapped_column(String(200), nullable=False, default='') + receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + # 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。 + receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False) + erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False) + result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + # 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。 + raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + manually_closed_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + precheck: Mapped[TransferPrecheck] = relationship(back_populates='items') + run: Mapped[Optional[TransferRun]] = relationship(back_populates='items') + attempts: Mapped[list['TransferAttempt']] = relationship( + back_populates='item', cascade='all, delete-orphan', + ) + + +class TransferAttempt(Base): + """一次恢复/重查/执行尝试;每次恢复创建新 Attempt,旧记录不可覆盖。""" + + __tablename__ = 'transfer_attempts' + __table_args__ = ( + UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'), + CheckConstraint( + f"kind IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_KINDS)})", + name='ck_transfer_attempts_kind', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_STATUSES)})", + name='ck_transfer_attempts_status', + ), + Index('ix_transfer_attempts_item_created', 'item_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) + kind: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + request_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts') + + +class TransferAuditEvent(Base): + """调拨领域只追加审计事件;禁止更新与删除。""" + + __tablename__ = 'transfer_audit_events' + __table_args__ = ( + CheckConstraint( + f"actor_type IN ({', '.join(repr(s) for s in TRANSFER_AUDIT_ACTOR_TYPES)})", + name='ck_transfer_audit_events_actor_type', + ), + CheckConstraint( + "result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')", + name='ck_transfer_audit_events_result', + ), + Index('ix_transfer_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'), + Index('ix_transfer_audit_events_run_created', 'run_no', 'created_at'), + Index('ix_transfer_audit_events_invoice_created', 'invoice_no', 'created_at'), + Index('ix_transfer_audit_events_operation_created', 'operation_id', 'created_at'), + Index('ix_transfer_audit_events_event_hash', 'event_hash'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + event_type: Mapped[str] = mapped_column(String(64), nullable=False) + aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False) + aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False) + run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system') + actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + actor_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + actor_display: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + result: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + before_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + after_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + before_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + after_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + event_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class TransferArchive(Base): + """大对象归档索引(MinIO);Hash 用于归档完整性校验。""" + + __tablename__ = 'transfer_archives' + __table_args__ = ( + UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'), + UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'), + CheckConstraint("file_size >= 0", name='ck_transfer_archives_file_size'), + Index('ix_transfer_archives_object', 'object_type', 'object_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + archive_no: Mapped[str] = mapped_column(String(64), nullable=False) + object_type: Mapped[str] = mapped_column(String(64), nullable=False) + object_id: Mapped[str] = mapped_column(String(128), nullable=False) + storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +@event.listens_for(TransferAuditEvent, 'before_update') +def _reject_transfer_audit_update(_mapper, _connection, _target) -> None: + """拒绝 ORM 更新,确保审计事件不可改写。""" + raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE') + + +@event.listens_for(TransferAuditEvent, 'before_delete') +def _reject_transfer_audit_delete(_mapper, _connection, _target) -> None: + """拒绝 ORM 删除,保留跨生命周期追溯事实。""" + raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE') diff --git a/backend/app/models/integration_connector.py b/backend/app/models/integration_connector.py new file mode 100644 index 00000000..9f49fefc --- /dev/null +++ b/backend/app/models/integration_connector.py @@ -0,0 +1,202 @@ +"""models/integration_connector.py + +用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型: + CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。 +依赖:models.base.Base、SQLAlchemy 2.0 ORM。 +逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding) + 维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。 + 连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + Boolean, + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + UniqueConstraint, + text, +) +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.dialects.postgresql import JSONB + +from app.models.base import Base + +# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。 +CONNECTOR_TYPES = ('rest', 'soap') +CONFIG_STATUSES = ('draft', 'published', 'retired') +CREDENTIAL_STATUSES = ('active', 'rotating', 'retired') + +# context_selector_json 需要参与唯一约束/索引:PostgreSQL 的 JSON 无默认 btree 操作符表, +# 无法建唯一索引;映射为 JSONB 即可。SQLite/测试仍用 JSON(TEXT)。 +CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql') + + +class IntegrationCredentialReference(Base): + """凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。""" + + __tablename__ = 'integration_credential_references' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_credential_references_code'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CREDENTIAL_STATUSES)})", + name='ck_integration_credential_references_status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + secret_ref: Mapped[str] = mapped_column(String(128), nullable=False) + secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env') + credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password') + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + last_verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationClientInstance(Base): + """客户端实例:一份到外部系统的连接配置(连到哪 + 凭据引用 + 超时/TLS/默认 org)。""" + + __tablename__ = 'integration_client_instances' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_client_instances_code'), + CheckConstraint( + f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})", + name='ck_integration_client_instances_connector_type', + ), + Index('ix_integration_client_instances_type_env', 'connector_type', 'environment'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + name: Mapped[str] = mapped_column(String(128), nullable=False) + connector_type: Mapped[str] = mapped_column(String(16), nullable=False) + environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod') + # 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。 + # endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。 + endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + credential_ref_code: Mapped[Optional[str]] = mapped_column( + ForeignKey('integration_credential_references.code'), nullable=True, + ) + enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true')) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationInterfaceDefinition(Base): + """接口定义:一个可调操作(请求模板 + 入参 Schema + 返回值映射 + 出参 Schema)。""" + + __tablename__ = 'integration_interface_definitions' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_interface_definitions_code'), + CheckConstraint( + f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})", + name='ck_integration_interface_definitions_connector_type', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})", + name='ck_integration_interface_definitions_status', + ), + Index('ix_integration_interface_definitions_client', 'client_instance_code'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + name: Mapped[str] = mapped_column(String(128), nullable=False) + client_instance_code: Mapped[str] = mapped_column( + ForeignKey('integration_client_instances.code'), nullable=False, + ) + connector_type: Mapped[str] = mapped_column(String(16), nullable=False) + # 关键强类型字段独立列(JSON 保留作兜底)。 + http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + output_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true')) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationBinding(Base): + """绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。""" + + __tablename__ = 'integration_bindings' + __table_args__ = ( + UniqueConstraint( + 'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})", + name='ck_integration_bindings_status', + ), + CheckConstraint( + "priority >= 0", name='ck_integration_bindings_priority', + ), + Index('ix_integration_bindings_cap_env_status', 'capability', 'environment', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + capability: Mapped[str] = mapped_column(String(128), nullable=False) + context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict) + # 最常用的 context 匹配键独立列(JSON 保留作兜底)。 + context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + client_instance_code: Mapped[str] = mapped_column( + ForeignKey('integration_client_instances.code'), nullable=False, + ) + interface_definition_code: Mapped[str] = mapped_column( + ForeignKey('integration_interface_definitions.code'), nullable=False, + ) + mapping_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod') + effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationCall(Base): + """一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。""" + + __tablename__ = 'integration_calls' + __table_args__ = ( + UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'), + Index('ix_integration_calls_capability_created', 'capability', 'created_at'), + Index('ix_integration_calls_trace_id', 'trace_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + operation_id: Mapped[str] = mapped_column(String(128), nullable=False) + capability: Mapped[str] = mapped_column(String(128), nullable=False) + binding_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + request_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + status: Mapped[str] = mapped_column(String(32), nullable=False) + elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index e11ef0e0..5fbad44b 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -5,13 +5,12 @@ backend/app/models/shipping.py 依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。 逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列; Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches); - ShippingNotice.idempotency_key 为货代上传幂等; + ShippingUploadAttempt.idempotency_key 为货代上传幂等; Intake.create_idempotency_key 承载混合/open_existing 确认请求重放; - Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离; + Intake/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离; Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源; ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性; - order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本; - current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实; + OT 的 order_data_version/current_order_extraction_id/order_snapshot_id 仅作为任务流程指针; 阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions; 建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。 """ @@ -53,18 +52,7 @@ class ShippingNotice(Base): __tablename__ = 'shipping_notices' __table_args__ = ( Index('ix_shipping_notices_conversation', 'conversation_id'), - Index('ix_shipping_notices_current_step', 'current_step'), - Index('ix_shipping_notices_upload_status', 'upload_status'), Index('ix_shipping_notices_business_no', 'business_no'), - Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'), - Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'), - Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), - Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'), - Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'), - Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), - Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'), - Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'), - Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'), # 线性版本链:同一父任务至多一个后继(NULL 不冲突) UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'), Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_task_id'), @@ -72,11 +60,6 @@ class ShippingNotice(Base): id: Mapped[int] = mapped_column(primary_key=True) task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) - customer_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_customers.id'), index=True, nullable=True, - ) - customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) - customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) # 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。 business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True) @@ -85,9 +68,6 @@ class ShippingNotice(Base): user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) source_type: Mapped[str] = mapped_column(String(32), default='manual') - source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) - source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True) source_intake_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_intakes.id'), @@ -113,10 +93,6 @@ class ShippingNotice(Base): nullable=True, index=True, ) - business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) supersedes_task_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_notices.id'), @@ -128,99 +104,6 @@ class ShippingNotice(Base): ) duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - - raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) - customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey( - 'shipping_inventory_candidate_sets.id', - name='fk_shipping_notices_active_inventory_candidate_set_id', - use_alter=True, - ), - nullable=True, - ) - # P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。 - active_process_execution_id: Mapped[Optional[int]] = mapped_column( - ForeignKey( - 'shipping_process_executions.id', - name='fk_shipping_notices_active_process_execution_id', - use_alter=True, - ), - nullable=True, - ) - inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) - # 动态订单 FieldValue 编辑的乐观锁版本。 - order_data_version: Mapped[int] = mapped_column( - Integer, - default=1, - server_default=text('1'), - nullable=False, - ) - current_order_extraction_id: Mapped[Optional[int]] = mapped_column( - ForeignKey( - 'shipping_order_extractions.id', - name='fk_shipping_notices_current_order_extraction_id', - use_alter=True, - ), - nullable=True, - index=True, - ) - # 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。 - order_snapshot_id: Mapped[Optional[int]] = mapped_column( - ForeignKey( - 'shipping_order_snapshots.id', - name='fk_shipping_notices_order_snapshot_id', - use_alter=True, - ), - nullable=True, - unique=True, - index=True, - ) - - current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True) - inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - - export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) - export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) - export_version: Mapped[int] = mapped_column(Integer, default=1) - freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - upload_attempt: Mapped[int] = mapped_column(Integer, default=0) - idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) # 任务处置与业务阶段正交:生命周期负责作废/归档。 lifecycle_status: Mapped[str] = mapped_column( @@ -241,17 +124,6 @@ class ShippingNotice(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined') - events: Mapped[List['ShippingTaskEvent']] = relationship( - 'ShippingTaskEvent', - back_populates='task', - cascade='all, delete-orphan', - ) - field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship( - 'ShippingTaskFieldConflict', - back_populates='task', - cascade='all, delete-orphan', - ) class ShippingTaskEvent(Base): @@ -260,7 +132,10 @@ class ShippingTaskEvent(Base): __tablename__ = 'shipping_task_events' id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True) + task_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_tasks.id', name='fk_shipping_task_events_task_id_order_task'), + index=True, + ) event_type: Mapped[str] = mapped_column(String(64), index=True) detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) @@ -271,7 +146,7 @@ class ShippingTaskEvent(Base): request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) - task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='events') + task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='events') class ShippingTaskPurgeAudit(Base): @@ -397,7 +272,7 @@ class ShippingTaskInventoryLink(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True) inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True) link_role: Mapped[str] = mapped_column(String(32), default='member') access_mode: Mapped[str] = mapped_column(String(32), default='readonly') @@ -418,7 +293,7 @@ class ShippingTaskInventoryLink(Base): linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) - task: Mapped['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id]) + task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id]) inventory_file: Mapped['ShippingInventoryFile'] = relationship( 'ShippingInventoryFile', back_populates='links', @@ -515,7 +390,7 @@ class ShippingOrderIntake(Base): duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) # co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。 - consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) @@ -697,7 +572,7 @@ class ShippingOrderCandidate(Base): duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) consumed_task_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_notices.id'), + ForeignKey('shipping_order_tasks.id'), nullable=True, ) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) diff --git a/backend/app/models/shipping_customer_resolution.py b/backend/app/models/shipping_customer_resolution.py index 2af97322..2795b6a6 100644 --- a/backend/app/models/shipping_customer_resolution.py +++ b/backend/app/models/shipping_customer_resolution.py @@ -1,9 +1,10 @@ """ backend/app/models/shipping_customer_resolution.py -用途:保存订单候选的客户影子识别结果与人工标签。 +用途:保存订单候选的正式客户识别结果、识别证据与人工标签。 依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。 -逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。 +逻辑:订单候选抽取后幂等刷新识别证据和候选;确认字段独立保存最终客户, + 不得以订单中的任一字段(例如 bill_to)充当客户身份真相。 """ from __future__ import annotations @@ -11,19 +12,19 @@ from __future__ import annotations from datetime import datetime from typing import List, Optional -from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint +from sqlalchemy import CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base class ShippingCustomerShadowResolution(Base): - """每个订单候选唯一一条影子识别快照,可追加管理员真值标签。""" + """每个订单候选唯一一条正式客户识别快照,可追加确认和质量标签。""" __tablename__ = 'shipping_customer_shadow_resolutions' __table_args__ = ( CheckConstraint( - "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')", + "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')", name='ck_shipping_customer_shadow_status', ), Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'), @@ -56,6 +57,12 @@ class ShippingCustomerShadowResolution(Base): resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True) + # 客户确认是识别结果的独立事实;不得覆盖 evidence_json 或原始身份指纹。 + confirmed_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + confirmation_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + confirmation_reason: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index 267371e2..d4323b31 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -32,7 +32,7 @@ class ShippingReservation(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False) reservation_id: Mapped[str] = mapped_column(String(64), nullable=False) po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False) @@ -59,7 +59,7 @@ class ShippingInventoryVerification(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) diff --git a/backend/app/models/shipping_inventory_candidates.py b/backend/app/models/shipping_inventory_candidates.py index 2e851daa..b9e8059f 100644 --- a/backend/app/models/shipping_inventory_candidates.py +++ b/backend/app/models/shipping_inventory_candidates.py @@ -5,7 +5,7 @@ models/shipping_inventory_candidates.py InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存 同一时刻的完整不可变副本,用于审计与回滚。 -依赖:Base、ShippingNotice、ShippingProcessExecution、ShippingOrderReviewCase、users、 +依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、 ShippingInventoryRoutingRule(可选外键,路由规则版本)。 逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结; input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等); @@ -81,7 +81,7 @@ class ShippingInventoryCandidateSet(Base): id: Mapped[int] = mapped_column(primary_key=True) set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') task_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=True, + ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=True, ) review_case_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True, diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py index d162f91f..5831deea 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/shipping_inventory_config.py @@ -158,16 +158,26 @@ class ShippingInventorySourceParsingBindingAudit(Base): class ShippingInventoryParsingProfile(Base): - """可跨库存源复用的库存文件结构、样本证据与订单匹配配置。""" + """可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。 + + purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义); + purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), + 供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。 + """ __tablename__ = 'shipping_inventory_parsing_profiles' __table_args__ = ( UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'), Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'), + CheckConstraint( + "purpose IN ('inventory', 'movement')", + name='ck_shipping_inventory_parsing_profiles_purpose', + ), ) id: Mapped[int] = mapped_column(primary_key=True) + purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory') profile_code: Mapped[str] = mapped_column(String(64), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) diff --git a/backend/app/models/shipping_inventory_preparation.py b/backend/app/models/shipping_inventory_preparation.py index 45e80d98..786f0574 100644 --- a/backend/app/models/shipping_inventory_preparation.py +++ b/backend/app/models/shipping_inventory_preparation.py @@ -2,7 +2,7 @@ models/shipping_inventory_preparation.py 用途:表达一次任务级库存准备轮次及逐库存源状态。 -依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 +依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。 """ @@ -31,7 +31,7 @@ class ShippingInventoryPreparationAttempt(Base): ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False) execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True) gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True) recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True) diff --git a/backend/app/models/shipping_notice_line.py b/backend/app/models/shipping_notice_line.py index fb050d58..b2d4f9d3 100644 --- a/backend/app/models/shipping_notice_line.py +++ b/backend/app/models/shipping_notice_line.py @@ -28,19 +28,27 @@ class ShippingNoticeLine(Base): __tablename__ = 'shipping_notice_lines' __table_args__ = ( UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'), + UniqueConstraint('notice_id', 'line_no', name='uq_shipping_notice_lines_line_no'), Index('ix_shipping_notice_lines_notice_id', 'notice_id'), Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'), ) id: Mapped[int] = mapped_column(primary_key=True) notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False) - snapshot_line_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True, + snapshot_line_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), nullable=False, ) position: Mapped[int] = mapped_column(Integer, nullable=False) - line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + # 发货通知项次:每个 Notice 从 1 开始连续编号,禁止使用导出序号或客户 PO 行号。 + line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True) + # 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。 + inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + inventory_file_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True, + ) + inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py index de3ef869..04fa7526 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -37,7 +37,7 @@ class ShippingNoticeLineInventoryMatch(Base): __table_args__ = ( UniqueConstraint( 'task_id', - 'line_key', + 'snapshot_line_id', 'inventory_snapshot_id', name='uq_shipping_notice_line_inv_match_task_line_snap', ), @@ -45,7 +45,7 @@ class ShippingNoticeLineInventoryMatch(Base): Index( 'uq_shipping_notice_line_inv_match_current', 'task_id', - 'line_key', + 'snapshot_line_id', unique=True, postgresql_where=text('is_current IS TRUE'), ), @@ -70,14 +70,19 @@ class ShippingNoticeLineInventoryMatch(Base): id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notices.id', ondelete='CASCADE'), + ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, ) review_case_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'), nullable=True, ) - line_key: Mapped[str] = mapped_column(String(64), nullable=False) + snapshot_line_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), + nullable=False, + index=True, + ) + line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_set_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), diff --git a/backend/app/models/shipping_order_customer_match.py b/backend/app/models/shipping_order_customer_match.py deleted file mode 100644 index 87844363..00000000 --- a/backend/app/models/shipping_order_customer_match.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -backend/app/models/shipping_order_customer_match.py - -用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。 -依赖:ShippingOrderExtraction、ShippingCustomer、users。 -逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any, Optional - -from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint -from sqlalchemy.orm import Mapped, mapped_column, relationship - -from app.models.base import Base - - -class ShippingOrderCustomerMatch(Base): - """一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。""" - - __tablename__ = 'shipping_order_customer_matches' - __table_args__ = ( - UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'), - CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'), - CheckConstraint( - "status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')", - name='ck_shipping_order_customer_matches_status', - ), - Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - extraction_id: Mapped[int] = mapped_column( - ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True, - ) - role: Mapped[str] = mapped_column(String(16), nullable=False) - raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) - source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched') - customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) - site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True) - customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) - customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) - candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) - resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column( - DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, - ) - - extraction = relationship('ShippingOrderExtraction') - customer = relationship('ShippingCustomer') - site = relationship('ShippingCustomerSite') diff --git a/backend/app/models/shipping_order_review.py b/backend/app/models/shipping_order_review.py index 5988708e..bddced4d 100644 --- a/backend/app/models/shipping_order_review.py +++ b/backend/app/models/shipping_order_review.py @@ -7,7 +7,7 @@ 逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本; Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task; 行级决定支持完整明细先行履约波次,禁止拆分数量; - wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。 + wave_lines 保证同一 (case, snapshot_line_id) 最多关联一个 task_id。 """ from __future__ import annotations @@ -109,7 +109,7 @@ class ShippingOrderReviewCase(Base): ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'), nullable=True, ) - confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) @@ -140,13 +140,13 @@ class ShippingOrderReviewCase(Base): 'ShippingOrderReviewLineDecision', back_populates='case', cascade='all, delete-orphan', - order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version', + order_by='ShippingOrderReviewLineDecision.draft_line_id, ShippingOrderReviewLineDecision.decision_version', ) wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship( 'ShippingOrderReviewWaveLine', back_populates='case', cascade='all, delete-orphan', - order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key', + order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.snapshot_line_id', ) @@ -212,7 +212,7 @@ class ShippingOrderReviewConfirmedRevision(Base): case_id: Mapped[int] = mapped_column( ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) draft_version: Mapped[int] = mapped_column(Integer, nullable=False) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) diff --git a/backend/app/models/shipping_order_review_line_decision.py b/backend/app/models/shipping_order_review_line_decision.py index ba178659..fb83a1e2 100644 --- a/backend/app/models/shipping_order_review_line_decision.py +++ b/backend/app/models/shipping_order_review_line_decision.py @@ -2,8 +2,8 @@ models/shipping_order_review_line_decision.py 用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。 -依赖:ShippingOrderReviewCase、ShippingNotice、users。 -逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一; +依赖:ShippingOrderReviewCase、ShippingOrderTask、users。 +逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, draft_line_id, version) 唯一; 活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联; decision_source 区分 system/user(历史可空)。 """ @@ -26,7 +26,7 @@ class ShippingOrderReviewLineDecision(Base): __table_args__ = ( UniqueConstraint( 'review_case_id', - 'line_key', + 'draft_line_id', 'decision_version', name='uq_shipping_review_line_decisions_case_line_ver', ), @@ -49,7 +49,7 @@ class ShippingOrderReviewLineDecision(Base): name='ck_shipping_review_line_decisions_source', ), CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'), - Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'), + Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'draft_line_id'), Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'), Index('ix_shipping_review_line_decisions_task', 'task_id'), ) @@ -59,7 +59,7 @@ class ShippingOrderReviewLineDecision(Base): ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - line_key: Mapped[str] = mapped_column(String(64), nullable=False) + draft_line_id: Mapped[str] = mapped_column(String(64), nullable=False) line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') decision_code: Mapped[str] = mapped_column(String(48), nullable=False) @@ -70,7 +70,7 @@ class ShippingOrderReviewLineDecision(Base): available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) # system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。 decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) diff --git a/backend/app/models/shipping_order_review_suggestion.py b/backend/app/models/shipping_order_review_suggestion.py index ecdf0fda..20f33ec0 100644 --- a/backend/app/models/shipping_order_review_suggestion.py +++ b/backend/app/models/shipping_order_review_suggestion.py @@ -69,7 +69,7 @@ class ShippingOrderReviewSuggestion(Base): ForeignKey('shipping_order_processing_runs.id'), nullable=True, ) field_id: Mapped[str] = mapped_column(String(64), nullable=False) - line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + draft_line_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header') evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field') status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') diff --git a/backend/app/models/shipping_order_review_wave_idempotency.py b/backend/app/models/shipping_order_review_wave_idempotency.py index 9ba9ccf3..a565ed5e 100644 --- a/backend/app/models/shipping_order_review_wave_idempotency.py +++ b/backend/app/models/shipping_order_review_wave_idempotency.py @@ -2,7 +2,7 @@ models/shipping_order_review_wave_idempotency.py 用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。 -依赖:shipping_order_review_cases、shipping_notices。 +依赖:shipping_order_review_cases、shipping_order_tasks。 逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409; progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。 """ @@ -39,15 +39,15 @@ class ShippingOrderReviewWaveIdempotency(Base): nullable=False, ) task_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notices.id', ondelete='CASCADE'), + ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, ) task_no: Mapped[str] = mapped_column(String(64), nullable=False) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) decision_source: Mapped[str] = mapped_column(String(16), nullable=False) - # 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。 - line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list) - line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False) + # 稳定排序后的冻结订单行 ID 数组指纹(冲突比对)。 + snapshot_line_ids_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list) + snapshot_line_ids_hash: Mapped[str] = mapped_column(String(64), nullable=False) # 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。 inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='') diff --git a/backend/app/models/shipping_order_review_wave_line.py b/backend/app/models/shipping_order_review_wave_line.py index 19b4427d..01e910e0 100644 --- a/backend/app/models/shipping_order_review_wave_line.py +++ b/backend/app/models/shipping_order_review_wave_line.py @@ -2,9 +2,9 @@ models/shipping_order_review_wave_line.py 用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。 -依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。 +依赖:ShippingOrderReviewCase、ShippingOrderTask、ShippingOrderReviewConfirmedRevision。 逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入; - (review_case_id, line_key) 数据库唯一约束防并发重复入波次。 + (review_case_id, snapshot_line_id) 数据库唯一约束防并发重复入波次。 """ from __future__ import annotations @@ -25,7 +25,7 @@ class ShippingOrderReviewWaveLine(Base): __table_args__ = ( UniqueConstraint( 'review_case_id', - 'line_key', + 'snapshot_line_id', name='uq_shipping_review_wave_lines_case_line', ), Index('ix_shipping_review_wave_lines_task', 'task_id'), @@ -37,8 +37,11 @@ class ShippingOrderReviewWaveLine(Base): ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - line_key: Mapped[str] = mapped_column(String(64), nullable=False) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + snapshot_line_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), + nullable=False, + ) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) wave_no: Mapped[int] = mapped_column(Integer, nullable=False) confirmed_revision_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'), diff --git a/backend/app/models/shipping_order_schema.py b/backend/app/models/shipping_order_schema.py index 4fc93c88..1adc6303 100644 --- a/backend/app/models/shipping_order_schema.py +++ b/backend/app/models/shipping_order_schema.py @@ -4,7 +4,7 @@ backend/app/models/shipping_order_schema.py 用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。 依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。 逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json; - definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum); + definition_json 含 fields / auto_creation_policy; 写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。 """ @@ -138,8 +138,7 @@ class ShippingOrderSchemaVersion(Base): definition_json 契约要点: - fields[]:字段采用与识别规则 - auto_creation_policy:自动建单策略 - - derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no) - - derivation_rules_checksum:派生规则稳定校验和 + - line_no:运行时按 Extraction 内明细顺序生成,不属于 Schema 配置或派生规则。 """ __tablename__ = 'shipping_order_schema_versions' @@ -232,7 +231,7 @@ class ShippingOrderExtraction(Base): run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True, ) - task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) @@ -264,12 +263,16 @@ class ShippingOrderLine(Base): """动态订单解析中的行身份;业务值全部位于 FieldValue。""" __tablename__ = 'shipping_order_lines' - __table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),) + __table_args__ = ( + UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'), + UniqueConstraint('extraction_id', 'line_no', name='uq_shipping_order_lines_line_no'), + ) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False) - line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + line_no: Mapped[int] = mapped_column(Integer, nullable=False) + draft_line_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines') diff --git a/backend/app/models/shipping_order_snapshot.py b/backend/app/models/shipping_order_snapshot.py index 60860e49..fb0b9107 100644 --- a/backend/app/models/shipping_order_snapshot.py +++ b/backend/app/models/shipping_order_snapshot.py @@ -2,10 +2,9 @@ backend/app/models/shipping_order_snapshot.py 用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。 -依赖:shipping_order_schema 的 Extraction、shipping_notices、shipping_customers 与 users。 +依赖:shipping_order_schema 的 Extraction、shipping_order_tasks、shipping_customers 与 users。 逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。 - Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum; - source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。 + source_manifest_json 可含 field_lineage(值来源、覆盖原因、证据引用)。 """ from __future__ import annotations @@ -31,13 +30,13 @@ class ShippingOrderSnapshot(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, index=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True) customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) order_data_version: Mapped[int] = mapped_column(Integer, nullable=False) - # 可含 derivation_rules_snapshot / derivation_rules_checksum 等规则版本投影。 + # 保存冻结时采用的业务规则版本,不保存已下线的派生规则。 rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) # 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实; # 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。 @@ -84,7 +83,8 @@ class ShippingOrderSnapshotLine(Base): id: Mapped[int] = mapped_column(primary_key=True) snapshot_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False) - line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + # 冻结订单项次:每个 Snapshot 从 1 开始连续编号,冻结后不可修改。 + line_no: Mapped[int] = mapped_column(Integer, nullable=False) part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -111,7 +111,7 @@ class ShippingOrderReviewEvent(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False) snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True) scope: Mapped[str] = mapped_column(String(16), nullable=False) diff --git a/backend/app/models/shipping_order_task.py b/backend/app/models/shipping_order_task.py index fb785999..68338d0c 100644 --- a/backend/app/models/shipping_order_task.py +++ b/backend/app/models/shipping_order_task.py @@ -2,8 +2,8 @@ backend/app/models/shipping_order_task.py 用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。 -依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_notices。 -逻辑:由 Extraction Run 的 user_task_no 双写/回填;建单成功后挂 shipping_notice_id。 +依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。 +逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。 页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。 """ @@ -19,12 +19,13 @@ from sqlalchemy import ( ForeignKey, Index, Integer, + JSON, String, Text, UniqueConstraint, text, ) -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -45,6 +46,7 @@ class ShippingOrderTask(Base): __tablename__ = 'shipping_order_tasks' __table_args__ = ( UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'), + CheckConstraint("lifecycle_status IN ('active', 'voided', 'archived')", name='ck_shipping_order_tasks_lifecycle_status'), CheckConstraint( "source_type IS NULL OR source_type IN ('eml', 'direct_pdf')", name='ck_shipping_order_tasks_source_type', @@ -53,7 +55,6 @@ class ShippingOrderTask(Base): Index('ix_shipping_order_tasks_conversation', 'conversation_id'), Index('ix_shipping_order_tasks_status', 'status'), Index('ix_shipping_order_tasks_extraction_run_id', 'extraction_run_id'), - Index('ix_shipping_order_tasks_shipping_notice_id', 'shipping_notice_id'), # 一 Candidate 一 OT;NULL candidate_id 仅遗留行,新创建路径禁止。 Index( 'uq_shipping_order_tasks_candidate_id', @@ -79,13 +80,12 @@ class ShippingOrderTask(Base): extraction_run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_processing_runs.id'), nullable=True, ) - shipping_notice_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_notices.id', name='fk_shipping_order_tasks_shipping_notice_id', use_alter=True), - nullable=True, - ) source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False, default='processing') stage: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) progress_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) @@ -94,3 +94,37 @@ class ShippingOrderTask(Base): DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, ) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + # OT 的客户确认事实由 ShippingCustomerShadowResolution 承载。 + order_data_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + current_order_extraction_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_extractions.id', name='fk_shipping_order_tasks_current_extraction', use_alter=True), nullable=True, index=True, + ) + order_snapshot_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True, + ) + active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True, + ) + step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + active_process_execution_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_executions.id', use_alter=True), nullable=True, index=True, + ) + + # OT 在正式通知创建前也必须具备独立的回收/归档生命周期,不能借用 Notice 字段。 + lifecycle_status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + deleted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + deletion_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + voided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + voided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + void_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archived_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + + events: Mapped[list['ShippingTaskEvent']] = relationship( + 'ShippingTaskEvent', back_populates='task', cascade='all, delete-orphan', + ) + field_conflicts: Mapped[list['ShippingTaskFieldConflict']] = relationship( + 'ShippingTaskFieldConflict', back_populates='task', cascade='all, delete-orphan', + ) diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py index 5ec7866a..33ef80fc 100644 --- a/backend/app/models/shipping_process_gate.py +++ b/backend/app/models/shipping_process_gate.py @@ -2,7 +2,7 @@ models/shipping_process_gate.py 用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。 -依赖:SQLAlchemy Base、ReviewCase、ShippingNotice、Job;状态枚举与 process_gate_contract 对齐。 +依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。 逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。 由领域服务独占写入;Job 仅调度。 co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。 @@ -74,7 +74,7 @@ class ShippingProcessExecution(Base): ForeignKey('shipping_order_review_cases.id'), nullable=True, ) task_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_notices.id'), nullable=True, + ForeignKey('shipping_order_tasks.id'), nullable=True, ) # 绑定候选版本,防止旧 callback/job 写入新候选链。 candidate_set_id: Mapped[Optional[int]] = mapped_column( diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/shipping_receipt_report.py index aefda816..4a2a2605 100644 --- a/backend/app/models/shipping_receipt_report.py +++ b/backend/app/models/shipping_receipt_report.py @@ -30,6 +30,10 @@ class ShippingReceiptReportConfig(Base): ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True, ) enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) + # 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True, + ) report_path_json: Mapped[dict[str, Any]] = mapped_column( JSON, default=dict, server_default=text("'{}'"), nullable=False, ) @@ -47,6 +51,7 @@ class ShippingReceiptReportConfig(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config') + parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship() class ShippingReceiptRpaUnitRun(Base): diff --git a/backend/app/models/shipping_task_line.py b/backend/app/models/shipping_task_line.py index fe1b3c3a..00f32ba4 100644 --- a/backend/app/models/shipping_task_line.py +++ b/backend/app/models/shipping_task_line.py @@ -2,7 +2,7 @@ backend/app/models/shipping_task_line.py 用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。 -依赖:models.base.Base、shipping_notices、users。 +依赖:models.base.Base、shipping_order_tasks、users。 逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。 """ @@ -60,7 +60,7 @@ class ShippingTaskFieldConflict(Base): id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notices.id', ondelete='CASCADE'), + ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, index=True, ) @@ -91,4 +91,4 @@ class ShippingTaskFieldConflict(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='field_conflicts') + task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='field_conflicts') diff --git a/backend/app/models/shipping_temporary_inventory.py b/backend/app/models/shipping_temporary_inventory.py index 5e4ca802..3ad02321 100644 --- a/backend/app/models/shipping_temporary_inventory.py +++ b/backend/app/models/shipping_temporary_inventory.py @@ -39,7 +39,7 @@ class ShippingTemporaryInventorySession(Base): analysis_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, ) - task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True) declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate') file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created') status: Mapped[str] = mapped_column(String(32), nullable=False, default='created') diff --git a/backend/app/models/voucher_check.py b/backend/app/models/voucher_check.py index 7de44eb6..01a3b757 100644 --- a/backend/app/models/voucher_check.py +++ b/backend/app/models/voucher_check.py @@ -1,9 +1,9 @@ """ backend/app/models/voucher_check.py -用途:立账凭证检核单票最新状态与批次明细 ORM。 +用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。 依赖:models.base.Base、schedule_runs。 -逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。 +逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。 """ from __future__ import annotations @@ -13,7 +13,6 @@ from typing import Optional from sqlalchemy import ( BigInteger, - Boolean, Date, DateTime, ForeignKey, @@ -28,41 +27,20 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class VoucherCheckInvoiceState(Base): - """账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。""" +class VoucherCheckProfile(Base): + """已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。""" - __tablename__ = "voucher_check_invoice_states" + __tablename__ = "voucher_check_profiles" __table_args__ = ( - UniqueConstraint( - "scope_code", - "period_month", - "invoice_no", - name="uq_voucher_check_invoice_states_scope_period_invoice", - ), - Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"), - Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"), - Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"), + UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"), + Index("ix_voucher_check_profiles_status", "status"), ) id: Mapped[int] = mapped_column(BigInteger, primary_key=True) - scope_code: Mapped[str] = mapped_column(String(32), nullable=False) - period_month: Mapped[date] = mapped_column(Date, nullable=False) - invoice_no: Mapped[str] = mapped_column(String(128), nullable=False) - invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - status: Mapped[str] = mapped_column(String(24), nullable=False) - folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) - material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - last_actual_run_id: Mapped[Optional[int]] = mapped_column( - BigInteger, - ForeignKey("schedule_runs.id", ondelete="SET NULL"), - nullable=True, - ) - last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + profile_code: Mapped[str] = mapped_column(String(32), nullable=False) + version: Mapped[str] = mapped_column(String(32), nullable=False) + definition_json: Mapped[dict] = mapped_column(JSON, nullable=False) + status: Mapped[str] = mapped_column(String(24), nullable=False, default="published") created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column( DateTime, @@ -72,43 +50,131 @@ class VoucherCheckInvoiceState(Base): ) -class VoucherCheckRunItem(Base): - """单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。""" +class VoucherCheckRun(Base): + """一次检核批次;列表统计取本表快照,不在查询时重算单文件结果。""" - __tablename__ = "voucher_check_run_items" + __tablename__ = "voucher_check_runs" __table_args__ = ( - UniqueConstraint( - "schedule_run_id", - "invoice_no", - name="uq_voucher_check_run_items_run_invoice", - ), - Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"), - Index("ix_voucher_check_run_items_period_result", "period_month", "result"), + Index("ix_voucher_check_runs_period_profile", "period_month", "profile_code"), + Index("ix_voucher_check_runs_status", "status"), + Index("ix_voucher_check_runs_finished_at", "finished_at"), ) id: Mapped[int] = mapped_column(BigInteger, primary_key=True) - schedule_run_id: Mapped[int] = mapped_column( + schedule_run_id: Mapped[Optional[int]] = mapped_column( BigInteger, - ForeignKey("schedule_runs.id", ondelete="CASCADE"), + ForeignKey("schedule_runs.id", ondelete="SET NULL"), + nullable=True, + index=True, + ) + run_no: Mapped[str] = mapped_column(String(64), nullable=False) + profile_code: Mapped[str] = mapped_column(String(32), nullable=False) + profile_version: Mapped[str] = mapped_column(String(32), nullable=False) + profile_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False) + period_month: Mapped[date] = mapped_column(Date, nullable=False) + mode: Mapped[str] = mapped_column(String(24), nullable=False, default="incremental") + status: Mapped[str] = mapped_column(String(24), nullable=False, default="running") + subject_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + archived_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + skipped_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + missing_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + missing_invoice_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + technical_error_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + staged_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0) + stats_json: Mapped[Optional[dict]] = mapped_column(JSON, 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) + + +class VoucherCheckSubject(Base): + """批次内一张销售 invoice 主体。""" + + __tablename__ = "voucher_check_subjects" + __table_args__ = ( + UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"), + Index("ix_voucher_check_subjects_invoice_no", "invoice_no"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + run_id: Mapped[int] = mapped_column( + BigInteger, + ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), nullable=False, index=True, ) - invoice_state_id: Mapped[Optional[int]] = mapped_column( - BigInteger, - ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"), - nullable=True, - ) - scope_code: Mapped[str] = mapped_column(String(32), nullable=False) - period_month: Mapped[date] = mapped_column(Date, nullable=False) invoice_no: Mapped[str] = mapped_column(String(128), nullable=False) invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - result: Mapped[str] = mapped_column(String(24), nullable=False) - folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) - material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + attributes_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class VoucherCheckFileResult(Base): + """invoice × 文件规则 的单文件结果,是缺件统计与 Excel 的真相源。""" + + __tablename__ = "voucher_check_file_results" + __table_args__ = ( + UniqueConstraint( + "run_id", + "invoice_no", + "rule_code", + name="uq_voucher_check_file_results_run_invoice_rule", + ), + Index("ix_voucher_check_file_results_status", "run_id", "status"), + Index("ix_voucher_check_file_results_invoice", "invoice_no"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + run_id: Mapped[int] = mapped_column( + BigInteger, + ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) + subject_id: Mapped[Optional[int]] = mapped_column( + BigInteger, + ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"), + nullable=True, + ) + invoice_no: Mapped[str] = mapped_column(String(128), nullable=False) + rule_code: Mapped[str] = mapped_column(String(64), nullable=False) + rule_name: Mapped[str] = mapped_column(String(128), nullable=False) + source_type: Mapped[str] = mapped_column(String(32), nullable=False) + expected_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + matched_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + source_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + archive_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + archive_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) + archive_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) + status: Mapped[str] = mapped_column(String(24), nullable=False) + missing_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class VoucherCheckNotification(Base): + """一个检核批次对应一条企微汇总通知审计。""" + + __tablename__ = "voucher_check_notifications" + __table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + run_id: Mapped[int] = mapped_column( + BigInteger, + ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), + nullable=False, + unique=True, + ) + excel_filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + recipient_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + send_status: Mapped[str] = mapped_column(String(32), nullable=False) + skip_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/services/admin/shipping_customer_lifecycle_service.py b/backend/app/services/admin/shipping_customer_lifecycle_service.py index 6d123479..0e782978 100644 --- a/backend/app/services/admin/shipping_customer_lifecycle_service.py +++ b/backend/app/services/admin/shipping_customer_lifecycle_service.py @@ -23,7 +23,7 @@ from app.models import ( ShippingCustomerImportRow, ShippingCustomerLifecycleEvent, ShippingCustomerSite, - ShippingOrderCustomerMatch, + ShippingOrderTask, ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, ShippingNotice, @@ -62,10 +62,19 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An } shadow_normalized = len(matched_resolution_ids) blockers = { - 'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(), + 'shipping_notices': ( + db.session.query(ShippingNotice.id) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id) + .filter( + ShippingCustomerShadowResolution.confirmed_customer_id == customer.id, + ) + .distinct() + .count() + ), 'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(), 'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(), - 'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(), + 'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(), 'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(), 'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(), 'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(), diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py index 2dce356e..e1e31406 100644 --- a/backend/app/services/admin/shipping_customer_service.py +++ b/backend/app/services/admin/shipping_customer_service.py @@ -25,6 +25,8 @@ from app.models import ( ShippingCustomerSiteIdentifier, ShippingIdentityEvidence, ShippingNotice, + ShippingOrderTask, + ShippingCustomerShadowResolution, ) from app.services.shipping_notice.customer_normalization import ( clean_text, @@ -144,7 +146,16 @@ def serialize_customer( 'updated_by_id': record.updated_by_id, 'created_at': record.created_at.isoformat() if record.created_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None, - 'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(), + 'notice_count': notice_count if notice_count is not None else ( + db.session.query(ShippingNotice.id) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id) + .filter( + ShippingCustomerShadowResolution.confirmed_customer_id == record.id, + ) + .distinct() + .count() + ), 'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(), 'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query( ShippingIdentityEvidence.id, @@ -174,8 +185,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: items、total、page、page_size、pages。 """ notice_counts = ( - db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count')) - .group_by(ShippingNotice.customer_id) + db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count')) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id) + .filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)) + .group_by(ShippingCustomerShadowResolution.confirmed_customer_id) .subquery() ) identifier_counts = ( diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py index 20fe6e3b..56d26fb4 100644 --- a/backend/app/services/admin/shipping_inventory_service.py +++ b/backend/app/services/admin/shipping_inventory_service.py @@ -19,6 +19,7 @@ from app.models import ( ShippingOrderField, ShippingInventoryParsingProfile, ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis, + ShippingNoticeLine, ShippingNoticeLineInventoryMatch, ShippingExcelTemplate, ShippingInventorySourceParsingBindingAudit, ShippingReceiptReportConfig, @@ -497,7 +498,11 @@ def delete_source(source_id: int) -> None: for candidates in [(rule.action_payload_json or {}).get('source_codes', [])] if isinstance(candidates, list) ) - has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0 + has_task = db.session.query(ShippingNoticeLine.id).filter( + ShippingNoticeLine.inventory_source_code == source_code, + ).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter( + ShippingNoticeLineInventoryMatch.inventory_source_code == source_code, + ).first() is not None has_export_run = any( source_code in {str(code).strip().upper() for code in source_codes} for run in ScheduleRun.query.all() diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py index 834dbc36..02341a3c 100644 --- a/backend/app/services/admin/user_service.py +++ b/backend/app/services/admin/user_service.py @@ -235,6 +235,22 @@ def create_user(data: dict[str, Any]) -> dict: def update_user(user_id: int, data: dict[str, Any]) -> dict: + """ + 更新管理端用户资料,可选同步 Casdoor 改密。 + + 核心逻辑:先写入本地字段;新密码与当前哈希相同则直接拒绝,避免 Casdoor 返回含 old password 的文案被误判成 401。 + + Args: + user_id: 目标用户主键。 + data: 管理端提交的字段,password 为空表示不改密。 + + Returns: + {'status': 'ok'}。 + + Raises: + NotFoundError: 用户不存在。 + AppError: 邮箱非法、新密码未变化或 Casdoor 同步失败。 + """ user = db.session.get(User, user_id) if not user: raise NotFoundError('User not found') @@ -259,6 +275,12 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict: if 'feature_permissions' in data or 'role' in data: permissions_payload = data.get('feature_permissions', user.feature_permissions) user.set_feature_permissions(permissions_payload) + if new_password and user.check_password(new_password): + raise AppError( + code='AUTH.PASSWORD_UNCHANGED', + message='New password must differ from the current password', + http_status=400, + ) if new_password: user.set_password(new_password) if 'agent_ids' in data: diff --git a/backend/app/services/agent_registry/catalog_bindings.py b/backend/app/services/agent_registry/catalog_bindings.py index bc2b871a..45e78647 100644 --- a/backend/app/services/agent_registry/catalog_bindings.py +++ b/backend/app/services/agent_registry/catalog_bindings.py @@ -12,4 +12,5 @@ from __future__ import annotations RUNTIME_HANDLER_BINDINGS: dict[str, str] = { 'shipping_notice': 'shipping_notice', 'file_check': 'file_check', + 'in_transit_transfer': 'in_transit_transfer', } diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index 2f085a4f..3bf2d7f9 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -129,3 +129,35 @@ agent_types: file_upload: true human_confirm: false handler_config_schema: {} + in_transit_transfer: + label: 在途仓自动调拨 + conversation_mode_default: task_chat + runtime_provider_default: hybrid + models: + - TransferRun + - TransferPrecheck + - TransferInvoiceItem + required_fields: [] + default_capabilities: + task_progress: true + human_confirm: true + forced_capabilities: + human_confirm: true + progress_contract: + enabled: true + data_source: + type: domain_state + domain: in_transit_transfer + update: + transport: sse + event: transfer_ui_state + binding: + type: conversation_context + keys: + - run_no + - precheck_id + requires_schedule_task: false + presentation: + layout: card + visualization: stepper + handler_config_schema: {} diff --git a/backend/app/services/agent_registry/handlers/bootstrap.py b/backend/app/services/agent_registry/handlers/bootstrap.py index 649d389d..db66d775 100644 --- a/backend/app/services/agent_registry/handlers/bootstrap.py +++ b/backend/app/services/agent_registry/handlers/bootstrap.py @@ -30,10 +30,12 @@ def load_handlers() -> None: import importlib import app.services.agent_registry.handlers.file_check as file_check_mod + import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod import app.services.agent_registry.handlers.shipping_notice as shipping_mod importlib.reload(file_check_mod) importlib.reload(shipping_mod) + importlib.reload(in_transit_transfer_mod) logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys())) _handlers_loaded = True diff --git a/backend/app/services/agent_registry/handlers/in_transit_transfer.py b/backend/app/services/agent_registry/handlers/in_transit_transfer.py new file mode 100644 index 00000000..e4497caa --- /dev/null +++ b/backend/app/services/agent_registry/handlers/in_transit_transfer.py @@ -0,0 +1,34 @@ +""" +用途:在途仓自动调拨 Hybrid Handler。 + +依赖:agent_registry.handlers.base/registry。 +逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute) + 输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid + 运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入 + Dify Chatflow 生命周期。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext +from app.services.agent_registry.handlers.registry import register_handler + + +@register_handler('in_transit_transfer') +class InTransitTransferHandler(AgentHandler): + """ + 在途仓自动调拨业务 Handler。 + + 核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息 + + Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。 + """ + + def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext: + """Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。""" + return ctx + + def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None: + """构造 transfer_ui_state SSE 事件(预留;进度由卡片消息 + Run API 提供)。""" + return None diff --git a/backend/app/services/agent_registry/handlers/shipping_notice.py b/backend/app/services/agent_registry/handlers/shipping_notice.py index 09fe96a9..fb65ce32 100644 --- a/backend/app/services/agent_registry/handlers/shipping_notice.py +++ b/backend/app/services/agent_registry/handlers/shipping_notice.py @@ -89,10 +89,10 @@ class ShippingNoticeHandler(AgentHandler): if str(event.get('event') or '') != 'shipping_ui_state': return None ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {} - checkpoint = ui_state.get('checkpoint') return json.dumps({ 'task_no': event.get('task_no'), - 'checkpoint': checkpoint, + 'position': ui_state.get('position'), + 'user_mode': ui_state.get('user_mode'), 'updated_at': ui_state.get('updated_at'), }, ensure_ascii=False, sort_keys=True) diff --git a/backend/app/services/auth/hxops/casdoor_user_sync.py b/backend/app/services/auth/hxops/casdoor_user_sync.py index cc4cf265..41c8f9eb 100644 --- a/backend/app/services/auth/hxops/casdoor_user_sync.py +++ b/backend/app/services/auth/hxops/casdoor_user_sync.py @@ -3,7 +3,7 @@ backend/app/services/auth/hxops/casdoor_user_sync.py 用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。 依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。 -逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。 +逻辑:管理端事务调用本模块;set-password 失败映射为稳定业务码(相同密码/原密码错误不用 401)。 """ from __future__ import annotations @@ -111,13 +111,57 @@ def raise_update_user_error(source) -> None: ) +def is_same_password_error(message: str) -> bool: + """判断 Casdoor 是否因新密码与当前密码相同而拒绝改密。""" + text = message or '' + lowered = text.lower() + if any( + token in lowered + for token in ( + 'cannot be the same', + 'must be different', + 'same as the old', + 'same as old password', + 'identical to the old', + 'identical to old', + 'password unchanged', + 'new password is the same', + ) + ): + return True + if 'new password' in lowered and 'old password' in lowered and 'same' in lowered: + return True + return '新密码' in text and '旧密码' in text and ('相同' in text or '一样' in text) + + +def raise_password_unchanged(source=None) -> None: + """新密码与当前密码相同按业务校验失败返回,禁止使用 401 以免前端清会话。""" + data = extract_error_payload(source) if source is not None else {} + msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) + raise AppError( + code='AUTH.PASSWORD_UNCHANGED', + message='New password must differ from the current password', + http_status=400, + details={'technical': msg_text[:300]} if msg_text else {}, + ) + + def raise_set_password_error(source) -> None: - """将 Casdoor set-password 失败映射为稳定业务错误码。""" + """将 Casdoor set-password 失败映射为稳定业务错误码,改密业务失败不使用会话 401。""" data = extract_error_payload(source) msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) - lowered = (msg_text or str(source or '')).lower() + raw_text = msg_text or str(source or '') + lowered = raw_text.lower() + # [STEP 1] 先识别“新密码与旧密码相同”。Casdoor 文案含 old password,若后判会被误成原密码错误 401。 + if is_same_password_error(raw_text): + raise_password_unchanged(source) + # [STEP 2] 原密码错误:业务 400。401 会被前端全局 fetch 包装当成登录失效并踢回登录页。 if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered: - raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401) + raise AppError( + code='AUTH.INCORRECT_CURRENT_PASSWORD', + message='Incorrect current password', + http_status=400, + ) if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')): raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400) if is_user_missing_error(lowered): diff --git a/backend/app/services/chat/action_registry.py b/backend/app/services/chat/action_registry.py index 21ddb00f..f55591c4 100644 --- a/backend/app/services/chat/action_registry.py +++ b/backend/app/services/chat/action_registry.py @@ -17,6 +17,7 @@ from app.services.chat.turn_context import TurnContext # action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。 ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = { "shipping.": ("shipping_notice",), + "transfer.": ("in_transit_transfer",), } @@ -79,5 +80,7 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler: def ensure_handlers_loaded() -> None: """延迟导入各领域 handler 模块以完成注册。""" from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401 + from app.services.in_transit_transfer import chat_actions as _transfer_actions # noqa: F401 _ = _shipping_extended + _ = _transfer_actions diff --git a/backend/app/services/faq_cache.py b/backend/app/services/faq_cache.py index 2ff00f7e..032a6a32 100644 --- a/backend/app/services/faq_cache.py +++ b/backend/app/services/faq_cache.py @@ -3,7 +3,7 @@ backend/app/services/faq_cache.py 用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。 依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。 -逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。 +逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。 """ import json import time @@ -66,6 +66,7 @@ class FaqCacheService: """ 尝试为指定 Agent 命中全局 FAQ 缓存条目。 核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。 + is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。 @param query - 用户提问 @param agent_id - 当前 Agent 主键 @returns 命中的 QuickQuestion;未命中返回 None @@ -80,7 +81,6 @@ class FaqCacheService: QuickQuestion.user_id.is_(None), QuickQuestion.agent_id == agent_id, QuickQuestion.cache_enabled.is_(True), - QuickQuestion.is_enabled.is_(True), QuickQuestion.answer.isnot(None), QuickQuestion.answer != "", QuickQuestion.stale_at.is_(None), diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py index 1de7c862..2e700c0d 100644 --- a/backend/app/services/file_assets/service.py +++ b/backend/app/services/file_assets/service.py @@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes( expires_at=expires_at, ) - # [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务 + # [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。 + # 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session + # 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。 try: - with db.session.begin_nested(): - db.session.add(asset) - db.session.flush() + db.session.add(asset) + db.session.flush() except IntegrityError: raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) if raced is not None: diff --git a/backend/app/services/in_transit_transfer/__init__.py b/backend/app/services/in_transit_transfer/__init__.py new file mode 100644 index 00000000..66994844 --- /dev/null +++ b/backend/app/services/in_transit_transfer/__init__.py @@ -0,0 +1,8 @@ +"""backend/app/services/in_transit_transfer/__init__.py + +用途:在途仓自动调拨 Agent 一期独立领域模块入口。 +依赖:同包 date_policy / status / quantity / strategy / contracts / audit; + Phase 1 起扩展 file_preparation / precheck_service 等。 +逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析; + 对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。 +""" diff --git a/backend/app/services/in_transit_transfer/archive.py b/backend/app/services/in_transit_transfer/archive.py new file mode 100644 index 00000000..7964f634 --- /dev/null +++ b/backend/app/services/in_transit_transfer/archive.py @@ -0,0 +1,168 @@ +"""在途调拨 MinIO 归档与 Hash 校验。 + +用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库; + 归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。 +依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。 +逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。 + 凭据只来自环境/配置,绝不写入归档内容或索引。 +""" + +from __future__ import annotations + +import hashlib +import io +import uuid +from datetime import datetime +from typing import Any, Protocol + +from app import db +from app.core.errors import AppError +from app.models import TransferArchive +from app.services.in_transit_transfer.audit import build_transfer_audit_event + +ARCHIVE_STORAGE_PROVIDER = "minio" +DEFAULT_ARCHIVE_BUCKET = "hxops-transfer" + + +class ObjectStore(Protocol): + """对象存储协议(MinIO 或测试替身)。""" + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """写入对象,返回对象键。""" + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + + +class MinioObjectStore: + """默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。""" + + def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None: + from flask import current_app + + self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket) + endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip() + access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip() + secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip() + secure = bool(current_app.config.get("MINIO_SECURE", False)) + if not endpoint: + raise AppError( + code="TRANSFER.ARCHIVE_NOT_CONFIGURED", + message="MinIO endpoint not configured", + http_status=503, + ) + from minio import Minio + + self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure) + + def _ensure_bucket(self) -> None: + """确保 bucket 存在(幂等)。""" + if not self.client.bucket_exists(self.bucket): + self.client.make_bucket(self.bucket) + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """写入对象并返回键。""" + self._ensure_bucket() + self.client.put_object( + bucket_name=bucket or self.bucket, + object_name=key, + data=io.BytesIO(data), + length=len(data), + content_type=content_type, + ) + return key + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key) + try: + return response.read() + finally: + response.close() + response.release_conn() + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key) + + +def _safe_filename(name: str) -> str: + """清洗文件名片段。""" + return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive" + + +def archive_snapshot( + *, + object_type: str, + object_id: str, + data: bytes, + original_filename: str, + content_type: str, + object_store: ObjectStore, + bucket: str = DEFAULT_ARCHIVE_BUCKET, + request_id: str | None = None, +) -> TransferArchive: + """归档一份对象并持久化索引 + 审计。 + + Args: + object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。 + object_id: 业务对象编号(precheck_no / run_no)。 + data: 待归档字节。 + original_filename: 原始文件名。 + content_type: MIME。 + object_store: 对象存储替身。 + bucket: 目标 bucket。 + Returns: + TransferArchive 索引记录。 + """ + digest = hashlib.sha256(data).hexdigest() + key = ( + f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/" + f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}" + ) + object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type) + archive = TransferArchive( + archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}", + object_type=object_type, + object_id=object_id, + storage_provider=ARCHIVE_STORAGE_PROVIDER, + storage_bucket=bucket, + storage_key=key, + original_filename=original_filename, + content_type=content_type, + file_size=len(data), + sha256=digest, + ) + db.session.add(archive) + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ARCHIVED", + aggregate_type=object_type, + aggregate_id=object_id, + actor_type="worker", + request_id=request_id, + result="success", + after={"storage_key": key, "sha256": digest, "file_size": len(data)}, + )) + db.session.commit() + return archive + + +def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool: + """复核归档 Hash(下载对象重新计算)。 + + Args: + archive: TransferArchive 索引。 + object_store: 对象存储替身。 + Returns: + True 一致;False 损坏/篡改。 + """ + data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key) + return hashlib.sha256(data).hexdigest() == archive.sha256 + + +def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes: + """恢复归档对象字节。""" + return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key) diff --git a/backend/app/services/in_transit_transfer/audit.py b/backend/app/services/in_transit_transfer/audit.py new file mode 100644 index 00000000..d0027221 --- /dev/null +++ b/backend/app/services/in_transit_transfer/audit.py @@ -0,0 +1,182 @@ +"""在途调拨审计服务。 + +用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算 + before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。 +依赖:app.models.TransferAuditEvent、标准库 hashlib/json。 +逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash; + event_hash 由事件自身稳定字段复算,不依赖对象内部状态。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Mapping + +import hashlib +import json + +from app.models import TransferAuditEvent + +# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。 +AUDIT_FORBIDDEN_KEY_FRAGMENTS = ( + "password", "secret", "token", "ciphertext", "credential", + "api_key", "apikey", "webhook", "authorization", "auth", +) + + +def is_forbidden_audit_key(key: str) -> bool: + """判断键名是否命中敏感片段(大小写不敏感)。""" + lowered = str(key or "").lower() + return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS) + + +def sanitize_snapshot(value: Any) -> Any: + """递归剔除敏感键,返回可安全持久化的快照副本。 + + Args: + value: 原始快照(dict/list/标量)。 + Returns: + 脱敏后的副本。 + """ + if isinstance(value, dict): + return { + str(key): sanitize_snapshot(item) + for key, item in value.items() + if not is_forbidden_audit_key(str(key)) + } + if isinstance(value, (list, tuple)): + return [sanitize_snapshot(item) for item in value] + return value + + +def canonical_hash(value: Any) -> str: + """对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。 + + Args: + value: 任意 JSON 可序列化值。 + Returns: + 64 位十六进制 Hash。 + """ + payload = json.dumps( + sanitize_snapshot(value), + ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str, + ) + return hashlib.sha256(payload.encode("ascii")).hexdigest() + + +def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]: + """计算前后快照顶层差异。 + + Args: + before: 变更前快照。 + after: 变更后快照。 + Returns: + {"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。 + """ + before_keys = set(before) + after_keys = set(after) + return { + "added": {key: after[key] for key in sorted(after_keys - before_keys)}, + "removed": {key: before[key] for key in sorted(before_keys - after_keys)}, + "changed": { + key: (before[key], after[key]) + for key in sorted(before_keys & after_keys) + if before[key] != after[key] + }, + } + + +def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]: + """事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。""" + created = event.created_at or datetime.utcnow() + return { + "event_type": event.event_type, + "aggregate_type": event.aggregate_type, + "aggregate_id": event.aggregate_id, + "run_no": event.run_no, + "precheck_no": event.precheck_no, + "invoice_no": event.invoice_no, + "item_id": event.item_id, + "attempt_no": event.attempt_no, + "actor_type": event.actor_type, + "actor_id": event.actor_id, + "actor_role": event.actor_role, + "actor_display": event.actor_display, + "request_id": event.request_id, + "operation_id": event.operation_id, + "source": event.source, + "result": event.result, + "error_code": event.error_code, + "before_hash": event.before_hash, + "after_hash": event.after_hash, + "created_at": created.isoformat(), + } + + +def compute_event_hash(event: TransferAuditEvent) -> str: + """由存储字段复算事件 Hash(Hash 校验作业的复算口径)。""" + return canonical_hash(_event_hash_inputs(event)) + + +def build_transfer_audit_event( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + run_no: str | None = None, + precheck_no: str | None = None, + invoice_no: str | None = None, + item_id: str | None = None, + attempt_no: str | None = None, + actor_type: str = "system", + actor_id: str | None = None, + actor_role: str | None = None, + actor_display: str | None = None, + request_id: str | None = None, + operation_id: str | None = None, + source: str | None = None, + result: str | None = None, + error_code: str | None = None, + before: Any = None, + after: Any = None, +) -> TransferAuditEvent: + """构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。 + + Args: + event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。 + run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。 + actor_*: 操作者(user/worker/schedule/admin/rpa)。 + request_id / operation_id: 关联上下文。 + before / after: 前后快照(自动脱敏并计算 Hash)。 + Returns: + TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。 + """ + before_sanitized = sanitize_snapshot(before if before is not None else {}) + after_sanitized = sanitize_snapshot(after if after is not None else {}) + created_at = datetime.utcnow() + event = TransferAuditEvent( + event_type=event_type, + aggregate_type=aggregate_type, + aggregate_id=aggregate_id, + run_no=run_no, + precheck_no=precheck_no, + invoice_no=invoice_no, + item_id=item_id, + attempt_no=attempt_no, + actor_type=actor_type, + actor_id=actor_id, + actor_role=actor_role, + actor_display=actor_display, + request_id=request_id, + operation_id=operation_id, + source=source, + result=result, + error_code=error_code, + before_json=before_sanitized, + after_json=after_sanitized, + before_hash=canonical_hash(before_sanitized), + after_hash=canonical_hash(after_sanitized), + created_at=created_at, + ) + event.event_hash = compute_event_hash(event) + return event diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py new file mode 100644 index 00000000..792d536f --- /dev/null +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -0,0 +1,71 @@ +"""在途调拨自动排程编排(09:00 自动调拨)。 + +用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知", + 供 in-transit-transfer platform job 调用。 +依赖:recovery_service、precheck_service、execution_service、notification。 +逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from app import db +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary +from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck +from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery + + +@dataclass +class AutoTransferOutcome: + """自动调拨阶段结果。""" + + run_no: str | None = None + run_status: str | None = None + recovery: RecoveryOutcome = field(default_factory=RecoveryOutcome) + notification_status: str | None = None + errors: list[str] = field(default_factory=list) + + +def run_auto_transfer(*, business_date: str, deps: TransferDeps, + source_codes: list[str] | None = None, + recover_history: bool = True, + sender: WeComSender | None = None, + recipients: list[str] | None = None) -> AutoTransferOutcome: + """执行一次自动调拨排程。 + + Args: + business_date: 业务日期。 + deps: 注入依赖。 + source_codes: 来源实例列表(缺省全部启用来源)。 + recover_history: 是否执行历史恢复。 + sender / recipients: 企微通知(None 则跳过通知)。 + Returns: + AutoTransferOutcome。 + """ + outcome = AutoTransferOutcome() + if recover_history: + try: + outcome.recovery = run_daily_recovery(business_date=business_date, deps=deps) + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"recovery_failed: {exc}") + try: + summary = create_precheck( + source_codes=source_codes or [], + business_date=business_date, + deps=deps, + ) + executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + outcome.run_no = executed.run_no + outcome.run_status = executed.status + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"auto_transfer_failed: {exc}") + if sender is not None and outcome.run_no: + try: + notice = notify_run_summary(run_no=outcome.run_no, sender=sender, recipients=recipients or []) + outcome.notification_status = notice.get("notification_status") + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"notification_failed: {exc}") + return outcome diff --git a/backend/app/services/in_transit_transfer/backlog_service.py b/backend/app/services/in_transit_transfer/backlog_service.py new file mode 100644 index 00000000..4a9371e2 --- /dev/null +++ b/backend/app/services/in_transit_transfer/backlog_service.py @@ -0,0 +1,141 @@ +"""在途调拨历史待处理池与老化分级。 + +用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项, + 按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。 +依赖:models、status。 +逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读; + manually_closed / success / duplicate_success 永久排除。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Optional + +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.status import TransferStatus + +AGING_NORMAL = "normal" +AGING_WARN_3D = "warn_3d" +AGING_ESCALATE_5D = "escalate_5d" +AGING_CRITICAL_7D = "critical_7d" +AGING_UNKNOWN = "result_unknown" +AGING_CLOSED = "closed" + +_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value + + +@dataclass(frozen=True) +class BacklogItemDTO: + """待处理池单项。""" + + item_id: int + source_code: str + invoice_no: str + material_no: str + status: str + reason: str + age_days: int + aging_level: str + last_attempt_at: Optional[str] = None + + +@dataclass +class BacklogSummaryDTO: + """待处理池汇总(含老化分级计数)。""" + + recoverable_count: int = 0 + closed_count: int = 0 + unknown_count: int = 0 + warn_3d: int = 0 + escalate_5d: int = 0 + critical_7d: int = 0 + + +def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str: + """按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。""" + if age_days >= critical: + return AGING_CRITICAL_7D + if age_days >= escalate: + return AGING_ESCALATE_5D + if age_days >= warn: + return AGING_WARN_3D + return AGING_NORMAL + + +def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]: + """返回明细最近一次 Attempt(无则 None)。""" + return TransferAttempt.query.filter_by(item_id=item.id).order_by( + TransferAttempt.created_at.desc(), + ).first() + + +def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int: + """按最近 Attempt 或明细更新时间计算积压天数。""" + latest = _latest_attempt(item) + base = latest.created_at if latest is not None else item.updated_at + return max(0, int((now - base).total_seconds() // 86400)) + + +def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]: + """列出待处理池项(可恢复 + 已关闭 + 结果未知)。 + + Args: + now: 判定时刻(默认当前时间)。 + source_code: 可选来源过滤。 + Returns: + BacklogItemDTO 列表。 + """ + current = now or datetime.utcnow() + query = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status.in_([ + _BACKLOG_RECOVERABLE, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.MANUALLY_CLOSED.value, + ]), + ) + if source_code: + query = query.filter_by(source_code=source_code) + output: list[BacklogItemDTO] = [] + for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all(): + age = _item_age_days(item, current) + latest = _latest_attempt(item) + if item.status == TransferStatus.RESULT_UNKNOWN.value: + level = AGING_UNKNOWN + elif item.status == TransferStatus.MANUALLY_CLOSED.value: + level = AGING_CLOSED + else: + level = aging_level_for(age) + output.append(BacklogItemDTO( + item_id=item.id, + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + status=item.status, + reason=item.result_message or item.result_code or "", + age_days=age, + aging_level=level, + last_attempt_at=latest.created_at.isoformat() if latest is not None else None, + )) + return output + + +def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO: + """计算待处理池汇总计数与老化分级。""" + items = list_backlog(now=now) + summary = BacklogSummaryDTO() + for item in items: + if item.status == TransferStatus.MANUALLY_CLOSED.value: + summary.closed_count += 1 + elif item.status == TransferStatus.RESULT_UNKNOWN.value: + summary.unknown_count += 1 + else: + summary.recoverable_count += 1 + if item.aging_level == AGING_WARN_3D: + summary.warn_3d += 1 + elif item.aging_level == AGING_ESCALATE_5D: + summary.escalate_5d += 1 + elif item.aging_level == AGING_CRITICAL_7D: + summary.critical_7d += 1 + return summary diff --git a/backend/app/services/in_transit_transfer/cancellation.py b/backend/app/services/in_transit_transfer/cancellation.py new file mode 100644 index 00000000..984549e3 --- /dev/null +++ b/backend/app/services/in_transit_transfer/cancellation.py @@ -0,0 +1,65 @@ +"""在途调拨请求停止(取消剩余任务)。 + +用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销; + 原因必填;取消前后状态进入审计。 +依赖:models、status、core.errors。 +逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer import status as status_machine + + +def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict: + """请求停止剩余任务。 + + Args: + run_no: Run 编号。 + reason: 取消原因(必填)。 + actor_id / request_id: 审计上下文。 + Returns: + {"run_no": ..., "cancelled_count": ...}。 + Raises: + ValidationError: 原因为空。 + NotFoundError: Run 不存在。 + ConflictError: Run 已终态不可取消。 + """ + reason_value = str(reason or "").strip() + if not reason_value: + raise ValidationError("reason is required") + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + if run.status in { + status_machine.TransferRunStatus.SUCCESS.value, + status_machine.TransferRunStatus.FAILED.value, + status_machine.TransferRunStatus.CANCELLED.value, + }: + raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE") + + cancelled = 0 + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): + if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no: + item.status = status_machine.TransferStatus.CANCELLED.value + item.result_code = "cancelled" + item.result_message = reason_value + cancelled += 1 + + active = db.session.query(TransferInvoiceItem).filter( + TransferInvoiceItem.run_id == run.id, + TransferInvoiceItem.status.in_([ + status_machine.TransferStatus.EXECUTING.value, + status_machine.TransferStatus.READY_TO_EXECUTE.value, + ]), + ).count() + if active == 0: + run.status = status_machine.TransferRunStatus.CANCELLED.value + run.completed_at = run.completed_at or datetime.utcnow() + db.session.commit() + return {"run_no": run.run_no, "cancelled_count": cancelled} diff --git a/backend/app/services/in_transit_transfer/chat_actions.py b/backend/app/services/in_transit_transfer/chat_actions.py new file mode 100644 index 00000000..f3034c2d --- /dev/null +++ b/backend/app/services/in_transit_transfer/chat_actions.py @@ -0,0 +1,100 @@ +"""在途调拨 Chat Action Handler。 + +用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件 + (message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。 +依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。 +逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。 +""" + +from __future__ import annotations + +from typing import Any, Iterator + +from app.services.chat.action_registry import register_action_handler +from app.services.chat.action_schema import TurnEvent +from app.services.chat.turn_context import TurnContext +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.execution_service import execute_precheck, get_run +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from app.services.in_transit_transfer.serializers import serialize_precheck_detail + +ACTION_TRANSFER_PRECHECK = "transfer.precheck" +ACTION_TRANSFER_EXECUTE = "transfer.execute" + + +def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEvent: + """构造结构化消息完成事件。""" + return TurnEvent(event="message.completed", data={ + "content": content, + "message_type": message_type, + "payload": payload, + }) + + +@register_action_handler +class TransferPrecheckAction: + """预检 Action:创建(或恢复)预检并输出预检卡。""" + + action_type = ACTION_TRANSFER_PRECHECK + + def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: + """执行只读预检并输出 transfer-precheck 卡片。 + + 【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发; + 只读,不写 ERP。 + """ + payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} + source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])] + business_date = str(payload.get("business_date") or business_date_now()) + deps = transfer_deps.get_transfer_dependencies() + summary = create_precheck( + source_codes=source_codes, + business_date=business_date, + deps=deps, + ) + detail = restore_precheck(summary.precheck_id) + yield _message( + content="调拨预检完成", + message_type="transfer-precheck", + payload={"kind": "precheck", **serialize_precheck_detail(detail)}, + ) + + +@register_action_handler +class TransferExecuteAction: + """执行 Action:确认选择范围并直接生成执行 Run,输出结果卡。""" + + action_type = ACTION_TRANSFER_EXECUTE + + def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: + """执行勾选范围并输出 transfer-result 卡片。 + + 【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发; + 后台确定性服务完成写前复查与 ERP 原子写入。 + """ + payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} + precheck_id = str(payload.get("precheck_id") or "").strip() + invoice_nos = payload.get("invoice_nos") + invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None + deps = transfer_deps.get_transfer_dependencies() + outcome = execute_precheck( + precheck_id=precheck_id, + deps=deps, + selected_invoice_nos=invoice_nos, + ) + run_view = get_run(outcome.run_no) + yield _message( + content=f"调拨执行完成:{outcome.run_no}", + message_type="transfer-result", + payload={ + "kind": "result", + "run_no": outcome.run_no, + "status": outcome.status, + "run": { + "run_no": outcome.run_no, + "status": outcome.status, + "result": run_view["result"], + }, + }, + ) diff --git a/backend/app/services/in_transit_transfer/concurrency.py b/backend/app/services/in_transit_transfer/concurrency.py new file mode 100644 index 00000000..3f727c77 --- /dev/null +++ b/backend/app/services/in_transit_transfer/concurrency.py @@ -0,0 +1,25 @@ +"""在途调拨并发参数与单写者约束。 + +用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值; + ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。 +依赖:无(纯常量)。 +逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。 +""" + +from __future__ import annotations + +# 一期冻结并发参数(与规格 §10 一致)。 +SOURCE_CONCURRENCY = 3 +ERP_QUERY_CONCURRENCY = 3 +ERP_WRITE_CONCURRENCY = 3 + + +def assert_single_writer(run_count: int) -> None: + """同预检最多一个执行 Run。 + + Args: + run_count: 已存在的执行 Run 数。 + Raises: + AssertionError: run_count > 1(一期硬约束)。 + """ + assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck" diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py new file mode 100644 index 00000000..2c9ad2e5 --- /dev/null +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -0,0 +1,200 @@ +"""在途调拨 DTO 与稳定错误码契约。 + +用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码, + 保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。 +依赖:标准库 dataclasses / decimal。 +逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页 + (决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Iterable + +# ---- 一期冻结错误码(TDD §7.3)------------------------------------------- +TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED" +TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED" +TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY" +TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID" +TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT" +TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH" +TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND" +TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED" +TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED" +TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED" +TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN" +TRANSFER_MANUAL_CLOSE_REASON_REQUIRED = "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED" +TRANSFER_CONFIG_PUBLISH_BLOCKED = "TRANSFER_CONFIG_PUBLISH_BLOCKED" +TRANSFER_SECRET_NOT_EXPOSED = "TRANSFER_SECRET_NOT_EXPOSED" +TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED" + +KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({ + TRANSFER_PERMISSION_DENIED, + TRANSFER_RECEIPT_NOT_MATURED, + TRANSFER_FILE_NOT_READY, + TRANSFER_FILE_SCHEMA_INVALID, + TRANSFER_INVOICE_CONFLICT, + TRANSFER_QUANTITY_MISMATCH, + TRANSFER_ERP_INVENTORY_NOT_FOUND, + TRANSFER_PRECHECK_EXPIRED, + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_DUPLICATE_NOT_VERIFIED, + TRANSFER_RESULT_UNKNOWN, + TRANSFER_MANUAL_CLOSE_REASON_REQUIRED, + TRANSFER_CONFIG_PUBLISH_BLOCKED, + TRANSFER_SECRET_NOT_EXPOSED, + TRANSFER_NOTIFICATION_FAILED, +}) + + +def require_known_error_code(code: str) -> None: + """校验错误码属于一期冻结集合。 + + Args: + code: 错误码。 + Raises: + ValueError: 未知错误码。 + """ + if str(code or "").strip() not in KNOWN_TRANSFER_ERROR_CODES: + raise ValueError(f"unknown transfer error code: {code}") + + +# ---- 预检 DTO ------------------------------------------------------------- +@dataclass(frozen=True) +class PrecheckCountsDTO: + """预检计数。""" + + file_invoice_count: int = 0 + not_matured_count: int = 0 + prechecked_count: int = 0 + executable_count: int = 0 + blocked_count: int = 0 + + +@dataclass(frozen=True) +class RawLineRefDTO: + """原始文件行追溯(Sheet/行号/文件版本)。""" + + sheet: str + row_no: int + file_version: str + + +@dataclass(frozen=True) +class PrecheckInvoiceItemDTO: + """预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。""" + + source_code: str + material_no: str + material_name: str + specification: str + invoice_no: str + from_warehouse: str + from_quantity: Decimal | None + to_warehouse: str + to_quantity: Decimal + result: str + receipt_date: str | None = None + reason: str = "" + erp_document_no: str | None = None + raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple) + + +@dataclass(frozen=True) +class PrecheckSummaryDTO: + """预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。""" + + precheck_id: str + status: str + business_date: str + eligible_receipt_date_to: str + expires_at: str + counts: PrecheckCountsDTO + estimated_transfer_quantity: str + estimated_erp_write_count: int + precheck_hash: str + + +# ---- 结果页 DTO(决策 20)-------------------------------------------------- +@dataclass(frozen=True) +class ErpDocumentLineDTO: + """ERP 单据内物料明细。""" + + material_no: str + material_name: str + specification: str + invoice_no: str + quantity: Decimal + + +@dataclass(frozen=True) +class ErpDocumentDTO: + """按 ERP 单号聚合的结果项。""" + + document_no: str + from_warehouse: str + to_warehouse: str + material_count: int + total_quantity: Decimal + posting_status: str + lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple) + + +@dataclass(frozen=True) +class TransferExceptionDTO: + """未生成 ERP 单据的异常项(单独展示)。""" + + source_code: str + invoice_no: str + material_no: str + reason: str + facts: str + + +@dataclass(frozen=True) +class RunResultDTO: + """Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。""" + + run_no: str + status: str + erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple) + exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple) + + +def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]: + """按 ERP 单号聚合成功项,产出结果页文档视图。 + + Args: + items: 预检明细项(含 erp_document_no 与 result)。 + Returns: + 按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。 + """ + grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {} + for item in items: + if item.erp_document_no and item.result in {"success", "duplicate_success"}: + grouped.setdefault(item.erp_document_no, []).append(item) + documents: list[ErpDocumentDTO] = [] + for document_no in sorted(grouped): + rows = sorted(grouped[document_no], key=lambda row: row.invoice_no) + lines = tuple( + ErpDocumentLineDTO( + material_no=row.material_no, + material_name=row.material_name, + specification=row.specification, + invoice_no=row.invoice_no, + quantity=row.to_quantity, + ) + for row in rows + ) + documents.append(ErpDocumentDTO( + document_no=document_no, + from_warehouse=rows[0].from_warehouse, + to_warehouse=rows[0].to_warehouse, + material_count=len(rows), + total_quantity=sum((row.to_quantity for row in rows), Decimal("0")), + posting_status="posted", + lines=lines, + )) + return tuple(documents) diff --git a/backend/app/services/in_transit_transfer/date_policy.py b/backend/app/services/in_transit_transfer/date_policy.py new file mode 100644 index 00000000..25c225a0 --- /dev/null +++ b/backend/app/services/in_transit_transfer/date_policy.py @@ -0,0 +1,81 @@ +"""在途调拨业务日期与成熟度策略。 + +用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured, + 昨天及更早可预检,未来日期阻断)。 +依赖:标准库 zoneinfo / datetime。 +逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用, + 避免各服务各自计算导致口径漂移。 +""" + +from __future__ import annotations + +from datetime import date, datetime, timedelta +from zoneinfo import ZoneInfo + +SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") + +# 成熟度结果 +MATURITY_ELIGIBLE = "eligible" +MATURITY_NOT_MATURED = "not_matured" +MATURITY_FUTURE = "future" + + +def parse_date(value: date | str) -> date: + """将 date 或 'YYYY-MM-DD' 字符串归一化为 date。 + + Args: + value: date 对象或 ISO 日期字符串。 + Returns: + 归一化后的 date。 + Raises: + ValueError: 字符串不是合法 ISO 日期。 + """ + if isinstance(value, date): + return value + return date.fromisoformat(str(value).strip()) + + +def business_date_now(moment: datetime | None = None) -> date: + """计算 Asia/Shanghai 业务日期。 + + Args: + moment: 可选时刻;带时区则转换到上海,naive 按 UTC 兼容处理(与 + shipping_notice.business_numbering_service 口径一致)。 + Returns: + Asia/Shanghai 口径的日期。 + """ + if moment is None: + return datetime.now(SHANGHAI_TZ).date() + if moment.tzinfo is None: + moment = moment.replace(tzinfo=ZoneInfo("UTC")) + return moment.astimezone(SHANGHAI_TZ).date() + + +def maturity_status(receipt_date: date | str, business_date: date | str) -> str: + """按 D+1 规则判定收料日期成熟度。 + + Args: + receipt_date: 收料日期。 + business_date: 当前业务日期 T。 + Returns: + 'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或 + 'future'(receipt_date > T,结构化阻断)。 + """ + receipt = parse_date(receipt_date) + business = parse_date(business_date) + if receipt == business: + return MATURITY_NOT_MATURED + if receipt > business: + return MATURITY_FUTURE + return MATURITY_ELIGIBLE + + +def eligible_receipt_date_to(business_date: date | str) -> date: + """返回可进入预检的收料截止日期(业务日期 T - 1 天)。 + + Args: + business_date: 当前业务日期。 + Returns: + T - 1 天。 + """ + return parse_date(business_date) - timedelta(days=1) diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py new file mode 100644 index 00000000..98054dba --- /dev/null +++ b/backend/app/services/in_transit_transfer/deps.py @@ -0,0 +1,118 @@ +"""在途调拨依赖装配(Dependencies)。 + +用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。 +依赖:file_preparation / erp_adapter / precheck_service / models。 +逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属 + (Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import AppError +from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository +from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter +from app.services.in_transit_transfer.precheck_service import ( + RouteMapping, + RouteNotResolvedError, + RouteResolver, + TransferDeps, +) + +RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN" + + +class ReceiptRowsNotFrozenError(AppError): + """收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。""" + + def __init__(self, message: str = "receipt file row contract not frozen"): + super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False) + + +class ShippingReceiptFileRepository: + """默认收料 ready 文件仓库(只读复用 shipping 收料归档)。 + + 行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。 + """ + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。""" + raise ReceiptRowsNotFrozenError( + "receipt file rows unfrozen: sample/sheet contract required (Q3)" + ) + + +class DefaultRouteResolver: + """默认路由解析:来源固定仓 + 外部系统仓库映射。 + + 路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。 + """ + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。""" + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + raise RouteNotResolvedError(source_code=source_code) + mapping = ShippingInventoryExternalMapping.query.filter_by( + inventory_source_id=source.id, enabled=True, + ).first() + if mapping is None or not mapping.external_organization_code: + raise RouteNotResolvedError(source_code=source_code) + return RouteMapping( + erp_org=mapping.external_organization_code, + from_warehouse=source.fixed_warehouse_id or "", + to_warehouse=mapping.external_warehouse_code, + ) + + +def _build_erp_adapter() -> CapabilityErpAdapter: + """装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。 + + P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射) + 承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。 + """ + return CapabilityErpAdapter() + + +_override: TransferDeps | None = None + + +def set_transfer_dependencies(deps: TransferDeps | None) -> None: + """测试注入点:设置/清除 TransferDeps 覆盖。""" + global _override # noqa: PLW0603 + _override = deps + + +def get_transfer_dependencies() -> TransferDeps: + """返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。""" + if _override is not None: + return _override + return TransferDeps( + file_repository=ShippingReceiptFileRepository(), + rpa_trigger=_DefaultRpaTrigger(), + route_resolver=DefaultRouteResolver(), + erp=_build_erp_adapter(), + ) + + +class _DefaultRpaTrigger: + """默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。 + + 依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或 + trigger 目录未配置时返回失败(fail-closed),不伪造等待。 + """ + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + from flask import current_app + + trigger_dir = str( + current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or "" + ).strip() + if not trigger_dir: + return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"} + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"} + return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} diff --git a/backend/app/services/in_transit_transfer/erp_adapter.py b/backend/app/services/in_transit_transfer/erp_adapter.py new file mode 100644 index 00000000..25d697e0 --- /dev/null +++ b/backend/app/services/in_transit_transfer/erp_adapter.py @@ -0,0 +1,295 @@ +"""在途调拨 ERP 访问统一边界(Adapter)。 + +用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。 + Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer / + verify_duplicate / 结果分类。 +依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。 +逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no / + erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试; + SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import Any, Protocol + +from app.core.errors import AppError + +ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN" +ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT" +ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN" + + +@dataclass(frozen=True) +class InventoryQuery: + """ERP 账面库存查询结果。""" + + found: bool + quantity: Decimal | None = None + document_no: str | None = None + + +class ErpNotFrozenError(AppError): + """ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。""" + + def __init__(self, message: str = "ERP contract not frozen"): + super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False) + + +class ErpQueryTimeoutError(AppError): + """ERP 查询超时(只读路径,允许上层重试)。""" + + def __init__(self, message: str = "ERP query timeout"): + super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True) + + +class ErpResultUnknownError(AppError): + """ERP 写结果无法确认(Phase 2 使用);禁止自动重试。""" + + def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None): + details = {"operation_id": operation_id} if operation_id else {} + super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details) + + +class ErpWriteTimeoutError(TimeoutError): + """ERP 写超时;committed 表达是否可证明已落单。""" + + def __init__( + self, + message: str, + *, + committed: bool | None, + document_no: str | None = None, + operation_id: str | None = None, + ) -> None: + super().__init__(message) + self.committed = committed + self.document_no = document_no + self.operation_id = operation_id + + +@dataclass(frozen=True) +class TransferWriteResult: + """ERP 原子建单/审核/过账结果分类。""" + + status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown + document_no: str | None = None + verified_posted: bool | None = None + error_code: str | None = None + error_message: str | None = None + + +class ErpTransport(Protocol): + """ERP 传输层协议(SOAP 或测试替身)。""" + + def query_inventory(self, **kwargs: Any) -> dict[str, Any]: + """按 Invoice 查询账面库存。""" + + def create_transfer(self, **kwargs: Any) -> dict[str, Any]: + """原子建单/审核/过账(Phase 2)。""" + + def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]: + """核实重复 Invoice 原单是否已审核过账。""" + + +class SoapErpTransport: + """真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。 + + Args: + config: 来自 Flask config 或环境变量(endpoint/username/password 等)。 + """ + + def __init__(self, config: dict[str, Any] | None = None) -> None: + self._config = config or {} + + def _require_frozen(self, operation: str) -> None: + """WSDL/endpoint 未冻结前任何调用直接拒绝。""" + if not str(self._config.get("endpoint") or "").strip(): + raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)") + + def query_inventory(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 查询账面库存(实现待 WSDL 冻结后落地)。""" + self._require_frozen("query_inventory") + raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL") + + def create_transfer(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。""" + self._require_frozen("create_transfer") + raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL") + + def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。""" + self._require_frozen("verify_duplicate") + raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL") + + +class ErpAdapter: + """ERP 唯一访问入口;组装统一请求并分类结果。""" + + def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None: + self._transport = transport + self._default_org = default_org + + def query_inventory( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> InventoryQuery: + """查询 ERP 账面库存并分类结果。 + + Args: + operation_id / run_no / attempt_no / invoice_no / erp_org / + from_warehouse / to_warehouse / quantity: 请求强制追踪字段。 + Returns: + InventoryQuery。 + Raises: + ErpQueryTimeoutError: 查询超时(可重试)。 + ErpNotFrozenError: ERP 契约未冻结。 + """ + request = { + "operation_id": operation_id, + "run_no": run_no, + "attempt_no": attempt_no, + "invoice_no": invoice_no, + "erp_org": erp_org or self._default_org, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + } + try: + response = self._transport.query_inventory(**request) + except ErpNotFrozenError: + raise + except TimeoutError as exc: + raise ErpQueryTimeoutError() from exc + response = response if isinstance(response, dict) else {} + if response.get("found"): + return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0"))) + return InventoryQuery(found=False) + + def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org, + from_warehouse, to_warehouse, quantity) -> dict[str, Any]: + """组装携带全部强制追踪字段的 ERP 请求。""" + return { + "operation_id": operation_id, + "run_no": run_no, + "attempt_no": attempt_no, + "invoice_no": invoice_no, + "erp_org": erp_org or self._default_org, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + } + + def create_transfer( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> TransferWriteResult: + """ERP 原子建单/审核/过账并按结果分类。 + + Returns: + TransferWriteResult:success / duplicate_success / duplicate_unverified / + business_failed / technical_failed / result_unknown。 + Raises: + ErpNotFrozenError: ERP 契约未冻结。 + """ + request = self._build_request( + operation_id=operation_id, run_no=run_no, attempt_no=attempt_no, + invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse, + to_warehouse=to_warehouse, quantity=quantity, + ) + try: + response = self._transport.create_transfer(**request) + except ErpNotFrozenError: + raise + except ErpWriteTimeoutError as exc: + if exc.committed is False: + # 可证明未落单 → 明确技术失败(不产生单据)。 + return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT") + return TransferWriteResult( + status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT", + document_no=exc.document_no, + ) + except TimeoutError: + # 无法区分是否落单 → result_unknown,禁止自动重试。 + return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN") + return _classify_write_response(response) + + def verify_duplicate( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> TransferWriteResult: + """核实重复 Invoice 原单是否已审核过账(幂等确认)。 + + Returns: + duplicate_success(已过账,含原单号)或 duplicate_unverified。 + """ + request = self._build_request( + operation_id=operation_id, run_no=run_no, attempt_no=attempt_no, + invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse, + to_warehouse=to_warehouse, quantity=quantity, + ) + try: + response = self._transport.verify_duplicate(**request) + except ErpNotFrozenError: + raise + except (TimeoutError, ErpWriteTimeoutError): + return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN") + response = response if isinstance(response, dict) else {} + status = str(response.get("status") or "") + document_no = response.get("document_no") + posted = bool(response.get("verified_posted")) + if status == "duplicate_success" and posted: + return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True) + return TransferWriteResult( + status="duplicate_unverified", document_no=document_no, verified_posted=posted, + error_code="TRANSFER_DUPLICATE_NOT_VERIFIED", + ) + + +def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult: + """按 ERP 写响应原文分类业务结果。""" + status = str(response.get("status") or "") + document_no = response.get("document_no") + if status == "success": + return TransferWriteResult(status="success", document_no=document_no) + if status == "duplicate_success": + posted = bool(response.get("verified_posted")) + if posted: + return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True) + return TransferWriteResult( + status="duplicate_unverified", document_no=document_no, verified_posted=False, + error_code="TRANSFER_DUPLICATE_NOT_VERIFIED", + ) + if status == "business_failed": + return TransferWriteResult( + status="business_failed", + error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"), + error_message=str(response.get("message") or ""), + ) + return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE") diff --git a/backend/app/services/in_transit_transfer/excel_export.py b/backend/app/services/in_transit_transfer/excel_export.py new file mode 100644 index 00000000..e8a95311 --- /dev/null +++ b/backend/app/services/in_transit_transfer/excel_export.py @@ -0,0 +1,125 @@ +"""在途调拨七 Sheet 异常 Excel 导出。 + +用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/ + ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。 +依赖:openpyxl、models、execution_service。 +逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本; + Secret 明文永不写入单元格(仅输出业务字段)。 +""" + +from __future__ import annotations + +import io +from typing import Any + +from openpyxl import Workbook + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.core.errors import NotFoundError + +EXCEL_SHEET_NAMES = [ + "执行汇总", + "数量不一致", + "ERP无库存", + "ERP技术失败", + "ERP结果未知", + "通知失败", + "原始文件追溯", +] + +_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + + +def build_exceptions_workbook(run_no: str) -> bytes: + """生成 Run 的七 Sheet 异常 Excel 字节。 + + Args: + run_no: Run 编号。 + Returns: + xlsx 字节。 + Raises: + NotFoundError: Run 不存在。 + """ + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).order_by( + TransferInvoiceItem.invoice_no, + ).all() + + workbook = Workbook() + workbook.remove(workbook.active) + + _sheet_summary(workbook, run, items) + _sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"}) + _sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"}) + _sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"}) + _sheet_unknown(workbook, items) + _sheet_notification(workbook, run) + _sheet_raw_trace(workbook, items) + + buffer = io.BytesIO() + workbook.save(buffer) + return buffer.getvalue() + + +def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInvoiceItem]) -> None: + """执行汇总 Sheet。""" + sheet = workbook.create_sheet("执行汇总") + sheet.append(["Run", run.run_no]) + sheet.append(["Run 状态", run.status]) + sheet.append(["通知状态", run.notification_status]) + sheet.append([]) + sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"]) + for item in items: + sheet.append([ + item.invoice_no, item.source_code, item.material_no, + item.result_code or item.status, item.erp_document_no or "", + ]) + + +def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None: + """按阻断原因归类 Sheet。""" + sheet = workbook.create_sheet(sheet_name) + sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"]) + for item in items: + if (item.result_code or "") in codes or item.status in codes: + sheet.append([ + item.invoice_no, item.source_code, item.material_no, + item.receipt_quantity, item.erp_quantity or "", + item.result_message or item.result_code or item.status, + ]) + + +def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None: + """ERP 结果未知 Sheet(只读提示,含 Operation 关联)。""" + sheet = workbook.create_sheet("ERP结果未知") + sheet.append(["Invoice", "来源", "料号", "说明"]) + sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""]) + for item in items: + if item.status == "result_unknown" or (item.result_code or "") == "result_unknown": + sheet.append([item.invoice_no, item.source_code, item.material_no, item.result_message or ""]) + + +def _sheet_notification(workbook: Workbook, run: TransferRun) -> None: + """通知失败 Sheet。""" + sheet = workbook.create_sheet("通知失败") + sheet.append(["Run", "通知状态", "错误码"]) + if run.notification_status == "failed": + sheet.append([run.run_no, run.notification_status, run.notification_error_code or ""]) + + +def _sheet_raw_trace(workbook: Workbook, items: list[TransferInvoiceItem]) -> None: + """原始文件追溯 Sheet(决策 11:Sheet/行号/文件版本)。""" + sheet = workbook.create_sheet("原始文件追溯") + sheet.append(["Invoice", "Sheet", "原始行号", "文件版本", "来源"]) + for item in items: + for line in (item.raw_lines_json or []): + sheet.append([ + item.invoice_no, + str(line.get("sheet") or ""), + int(line.get("row_no") or 0), + str(line.get("file_version") or ""), + item.source_code, + ]) diff --git a/backend/app/services/in_transit_transfer/execution_service.py b/backend/app/services/in_transit_transfer/execution_service.py new file mode 100644 index 00000000..8fd6be83 --- /dev/null +++ b/backend/app/services/in_transit_transfer/execution_service.py @@ -0,0 +1,399 @@ +"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。 + +用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run → + 逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。 +依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。 +逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0; + 每个 Invoice 独立写入,单项失败/结果未知不阻断其他项; + result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。 +""" + +from __future__ import annotations + +import uuid +from dataclasses import dataclass +from datetime import datetime +from decimal import Decimal +from typing import Any + +from app import db +from app.core.errors import AppError, NotFoundError, ValidationError +from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.contracts import ( + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_PRECHECK_EXPIRED, + ErpDocumentDTO, + PrecheckInvoiceItemDTO, + RunResultDTO, + TransferExceptionDTO, + aggregate_erp_documents, +) +from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run +from app.services.in_transit_transfer.precheck_service import ( + RESULT_EXECUTABLE, + RouteNotResolvedError, + TransferDeps, +) +from app.services.in_transit_transfer.quantity import classify_quantity_match + +PRECHECK_EXPIRED_RESULT = "precheck_expired" +ITEM_EXECUTION_ERROR_RESULT = "item_execution_error" + + +@dataclass(frozen=True) +class ExecuteOutcome: + """一次执行的结果摘要。""" + + run_no: str + status: str + result: RunResultDTO + + +def _item_result_of(item: TransferInvoiceItem) -> str: + """从持久化状态还原明细结果值(与预检快照口径一致)。""" + if item.result_code: + return item.result_code + if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value: + return RESULT_EXECUTABLE + return item.status + + +def recompute_precheck_hash(precheck: TransferPrecheck) -> str: + """由存储明细复算预检 Hash(写前快照校验口径)。""" + from app.services.in_transit_transfer.audit import canonical_hash + + counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {} + items = [ + { + "source_code": item.source_code, + "invoice_no": item.invoice_no, + "from_warehouse": item.from_warehouse, + "to_warehouse": item.to_warehouse, + "receipt_quantity": item.receipt_quantity, + "erp_quantity": item.erp_quantity, + "result": _item_result_of(item), + } + for item in sorted(precheck.items, key=lambda row: row.id) + ] + snapshot = { + "scope": sorted(precheck.scope_json.get("source_codes") or []), + "business_date": precheck.business_date, + "file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {}, + "counts": { + key: int(counts.get(key, 0)) + for key in ("file_invoice_count", "not_matured_count", "prechecked_count", + "executable_count", "blocked_count") + }, + "items": items, + } + return f"sha256:{canonical_hash(snapshot)}" + + +def _expire(precheck: TransferPrecheck) -> None: + """将预检置为过期(fail-closed 落位)。""" + precheck.status = "expired" + db.session.flush() + + +def execute_precheck( + *, + precheck_id: str, + deps: TransferDeps, + selected_invoice_nos: list[str] | None = None, + actor_id: int | None = None, + request_id: str | None = None, +) -> ExecuteOutcome: + """执行一次已确认的预检(手工或自动触发共用)。 + + Args: + precheck_id: 预检编号。 + deps: 注入依赖。 + selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。 + actor_id / request_id: 审计上下文。 + Returns: + ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。 + Raises: + NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。 + ConflictError: 重复执行。 + """ + precheck = db.session.query(TransferPrecheck).filter_by( + precheck_no=str(precheck_id).strip(), + ).first() + if precheck is None: + raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND") + if precheck.confirmed_at is not None: + from app.core.errors import ConflictError + + raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED") + if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value: + raise AppError( + code=TRANSFER_CONFIRMATION_REQUIRED, + message="precheck is not confirmed for execution", + http_status=400, + ) + if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow(): + _expire(precheck) + db.session.commit() + raise AppError( + code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired", + http_status=409, + ) + if recompute_precheck_hash(precheck) != precheck.precheck_hash: + _expire(precheck) + db.session.commit() + raise AppError( + code=TRANSFER_PRECHECK_EXPIRED, + message="precheck snapshot changed since confirmation", + http_status=409, + ) + + executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value] + if selected_invoice_nos is not None: + selected_set = {str(item).strip() for item in selected_invoice_nos} + available = {item.invoice_no for item in executable} + invalid = selected_set - available + if invalid: + raise ValidationError( + f"invoices not executable: {sorted(invalid)}", + code="TRANSFER.SELECTION_INVALID", + ) + selected = [item for item in executable if item.invoice_no in selected_set] + else: + selected = list(executable) + if not selected: + raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED) + + run = create_execution_run( + precheck, deps=deps, actor_id=actor_id, + selected_invoice_nos={item.invoice_no for item in selected}, + ) + for item in selected: + try: + _write_item(item, deps=deps, run_no=run.run_no, request_id=request_id) + except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项 + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = ITEM_EXECUTION_ERROR_RESULT + item.result_message = str(exc) + db.session.flush() + db.session.flush() + run_items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + finalize_run(run, run_items) + db.session.commit() + return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run)) + + +def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None: + """写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。""" + route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no) + if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse: + _mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck") + return + receipt_qty = Decimal(item.receipt_quantity) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + # [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。 + try: + query = deps.erp.query_inventory( + operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no, + invoice_no=item.invoice_no, erp_org=route.erp_org, + from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + except RouteNotResolvedError: + raise + if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE: + _mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck") + return + + # [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。 + attempt = TransferAttempt( + item_id=item.id, attempt_no=item.attempt_no, kind="erp_write", + status="running", operation_id=operation_id, + request_snapshot_json={ + "run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org, + "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, + "quantity": str(receipt_qty), + }, + ) + db.session.add(attempt) + db.session.flush() + result = deps.erp.create_transfer( + operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no, + invoice_no=item.invoice_no, erp_org=route.erp_org, + from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + before_status = item.status + _apply_write_result(item, attempt, result) + _audit_item_write(item, run_no, request_id, operation_id, before_status) + + +def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None: + """写前复查失败:fail-closed,不写 ERP。""" + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = result + item.result_message = message + db.session.flush() + + +def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None: + """按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。""" + attempt.response_summary_json = { + "status": result.status, + "document_no": result.document_no, + "verified_posted": result.verified_posted, + "error_code": result.error_code, + } + if result.status == "success": + item.status = status_machine.TransferStatus.SUCCESS.value + item.erp_document_no = result.document_no + item.result_code = None + attempt.status = "success" + elif result.status == "duplicate_success": + item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value + item.erp_document_no = result.document_no + item.result_code = None + attempt.status = "success" + elif result.status == "result_unknown": + # 终态:禁止自动重试,等待人工核实 SOP。 + item.status = status_machine.TransferStatus.RESULT_UNKNOWN.value + item.result_code = "result_unknown" + attempt.status = "result_unknown" + else: + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = result.status + item.result_message = result.error_message or result.error_code or "" + attempt.status = "failed" + attempt.error_code = result.error_code + attempt.completed_at = datetime.utcnow() + + +def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None: + """为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_ITEM_EXECUTED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=run_no, + invoice_no=item.invoice_no, + item_id=str(item.id), + attempt_no=item.attempt_no, + actor_type="worker", + request_id=request_id, + operation_id=operation_id, + result="success" if item.status in {"success", "duplicate_success"} else "failure", + before={"status": before_status}, + after={"status": item.status, "erp_document_no": item.erp_document_no}, + ) + db.session.add(event) + + +def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = None) -> str: + """单 Invoice 执行入口(Item Job Handler 使用)。 + + Args: + item_id: TransferInvoiceItem.id。 + deps: 注入依赖。 + Returns: + 写入后的 item 状态。 + Raises: + NotFoundError / RuntimeError: item 不存在或未关联执行 Run。 + """ + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.run_id is None: + raise RuntimeError("item not linked to execution run") + run_no = item.run.run_no if item.run else "RUN-PENDING" + _write_item(item, deps=deps, run_no=run_no, request_id=request_id) + db.session.commit() + return item.status + + +def get_run(run_no: str) -> dict[str, Any]: + """按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。""" + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + return { + "run_no": run.run_no, + "status": run.status, + "result": serialize_run_result(_build_run_result(run)), + } + + +def _build_run_result(run: TransferRun) -> RunResultDTO: + """由 Run 明细构建结果投影。""" + item_dtos: list[PrecheckInvoiceItemDTO] = [] + exceptions: list[TransferExceptionDTO] = [] + for item in sorted(run.items, key=lambda row: row.invoice_no): + result = _item_result_of(item) + item_dtos.append(PrecheckInvoiceItemDTO( + source_code=item.source_code, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + invoice_no=item.invoice_no, + receipt_date=item.receipt_date, + from_warehouse=item.from_warehouse, + from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None, + to_warehouse=item.to_warehouse, + to_quantity=Decimal(item.receipt_quantity), + result=result, + reason=item.result_message or "", + erp_document_no=item.erp_document_no, + )) + if result not in {"success", "duplicate_success"}: + exceptions.append(TransferExceptionDTO( + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + reason=result, + facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""), + )) + return RunResultDTO( + run_no=run.run_no, + status=run.status, + erp_documents=aggregate_erp_documents(item_dtos), + exceptions=tuple(exceptions), + ) + + +def serialize_run_result(result: RunResultDTO) -> dict[str, Any]: + """结果投影序列化(前端结果页 DTO)。""" + return { + "run_no": result.run_no, + "status": result.status, + "erp_documents": [ + { + "document_no": document.document_no, + "from_warehouse": document.from_warehouse, + "to_warehouse": document.to_warehouse, + "material_count": document.material_count, + "total_quantity": str(document.total_quantity), + "posting_status": document.posting_status, + "lines": [ + { + "material_no": line.material_no, + "material_name": line.material_name, + "specification": line.specification, + "invoice_no": line.invoice_no, + "quantity": str(line.quantity), + } + for line in document.lines + ], + } + for document in result.erp_documents + ], + "exceptions": [ + { + "source_code": exc.source_code, + "invoice_no": exc.invoice_no, + "material_no": exc.material_no, + "reason": exc.reason, + "facts": exc.facts, + } + for exc in result.exceptions + ], + } diff --git a/backend/app/services/in_transit_transfer/file_parser.py b/backend/app/services/in_transit_transfer/file_parser.py new file mode 100644 index 00000000..a1eb299a --- /dev/null +++ b/backend/app/services/in_transit_transfer/file_parser.py @@ -0,0 +1,179 @@ +"""在途调拨收料文件字段/结构校验。 + +用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、 + 来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。 +依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。 +逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date +from decimal import Decimal +from typing import Any, Iterable, Mapping + +from app.core.errors import AppError +from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID +from app.services.in_transit_transfer.date_policy import parse_date +from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity + +REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity") + + +@dataclass(frozen=True) +class ParsedReceiptRow: + """单行已校验收料记录。""" + + source_code: str + sheet: str + row_no: int + invoice_no: str + material_no: str + material_name: str + specification: str + receipt_date: date + receipt_quantity: Decimal + + +class ReceiptFileSchemaError(AppError): + """收料文件结构/字段校验失败(整行阻断)。""" + + def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None): + super().__init__( + code=TRANSFER_FILE_SCHEMA_INVALID, + message=message, + http_status=422, + details={"rows": rows or []}, + ) + + +def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None: + """累积式抛出首个行级错误(携带行号与原因)。""" + rows.append({"row_no": row_no, "reason": reason}) + + +def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: + """把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。 + + 字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系: + doc_no → invoice_no(幂等/汇总键) + quantity → receipt_quantity(严格数量匹配) + movement_date → receipt_date(成熟过滤) + 其余字段(material_code→material_no、material_name、warehouse_code、storage_code、 + lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。 + + Args: + source_code: 任务来源实例(行内来源身份一致性校验)。 + rows: 通用异动原始行 dict。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + return _parse_rows( + source_code=source_code, + rows=rows, + projection={ + "invoice_no": "doc_no", + "material_no": "material_code", + "receipt_quantity": "quantity", + "receipt_date": "movement_date", + }, + ) + + +def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: + """校验并解析收料文件行。 + + Args: + source_code: 任务来源实例(用于校验行内来源身份一致性)。 + rows: 原始文件行 dict。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + return _parse_rows( + source_code=source_code, + rows=rows, + projection={ + "invoice_no": "invoice_no", + "material_no": "material_no", + "receipt_quantity": "receipt_quantity", + "receipt_date": "receipt_date", + }, + ) + + +def _parse_rows( + *, + source_code: str, + rows: Iterable[Mapping[str, Any]], + projection: Mapping[str, str], +) -> list[ParsedReceiptRow]: + """按字段名投影校验并解析原始行。 + + Args: + source_code: 任务来源实例(行内来源身份一致性校验)。 + rows: 原始文件行 dict。 + projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date) + 到原始行字段名的映射(如 {invoice_no: doc_no})。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + invoice_key = str(projection.get("invoice_no") or "invoice_no") + material_key = str(projection.get("material_no") or "material_no") + quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity") + date_key = str(projection.get("receipt_date") or "receipt_date") + + errors: list[dict[str, Any]] = [] + parsed: list[ParsedReceiptRow] = [] + for raw in rows: + row = raw if isinstance(raw, Mapping) else {} + row_no = row.get("row_no") + invoice_no = str(row.get(invoice_key) or "").strip() + material_no = str(row.get(material_key) or "").strip() + sheet = str(row.get("sheet") or "").strip() + receipt_date_raw = str(row.get(date_key) or "").strip() + quantity_raw = row.get(quantity_key) + + if not sheet or not row_no: + _fail(errors, row_no=row_no, reason="missing_sheet_or_row_no") + continue + if not invoice_no: + _fail(errors, row_no=row_no, reason="missing_invoice_no") + continue + if not material_no: + _fail(errors, row_no=row_no, reason="missing_material_no") + continue + row_source = str(row.get("source_code") or "").strip() + if row_source and row_source.upper() != str(source_code).upper(): + _fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}") + continue + try: + receipt_date = parse_date(receipt_date_raw) + except ValueError: + _fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}") + continue + try: + quantity = validate_receipt_quantity(quantity_raw) + except QuantityValidationError as exc: + _fail(errors, row_no=row_no, reason=str(exc)) + continue + parsed.append(ParsedReceiptRow( + source_code=str(source_code), + sheet=sheet, + row_no=int(row_no), + invoice_no=invoice_no, + material_no=material_no, + material_name=str(row.get("material_name") or "").strip(), + specification=str(row.get("specification") or "").strip(), + receipt_date=receipt_date, + receipt_quantity=quantity, + )) + if errors: + raise ReceiptFileSchemaError(rows=errors) + return parsed diff --git a/backend/app/services/in_transit_transfer/file_preparation.py b/backend/app/services/in_transit_transfer/file_preparation.py new file mode 100644 index 00000000..ddeb0bfa --- /dev/null +++ b/backend/app/services/in_transit_transfer/file_preparation.py @@ -0,0 +1,96 @@ +"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。 + +用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件; + 存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job + 时绑定已有任务,保证并发请求只触发一次抓取。 +依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。 +逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身; + 任何触发失败 fail-closed 进入 failed,绝不误报 file_ready。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Protocol + +STAGE_FILE_READY = "file_ready" +STAGE_WAITING_RPA = "waiting_rpa_callback" +STAGE_FAILED = "failed" + + +@dataclass(frozen=True) +class ReadyReceiptFile: + """当日最新 ready 收料文件快照(含已提取行,供解析)。""" + + source_code: str + business_date: str + file_no: str + file_version: str + checksum: str + rows: tuple[dict[str, Any], ...] = () + + +@dataclass(frozen=True) +class FilePreparationResult: + """来源级文件准备结果。""" + + stage: str + file: ReadyReceiptFile | None = None + error_code: str | None = None + error_message: str | None = None + + +class ReceiptFileRepository(Protocol): + """收料 ready 文件仓库协议。""" + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回该来源当日最新 ready 文件;不存在返回 None。""" + + +class RpaTrigger(Protocol): + """收料 RPA 触发协议(DBS/Crane 共用)。""" + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + """触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。""" + + +def ensure_receipt_file_ready( + *, + source_code: str, + business_date: str, + repository: ReceiptFileRepository, + rpa_trigger: RpaTrigger, + active_source_job_key: str | None = None, +) -> FilePreparationResult: + """确保来源当日 ready 文件可用。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期(YYYY-MM-DD)。 + repository: ready 文件仓库。 + rpa_trigger: RPA 触发器。 + active_source_job_key: 活动 Source Job 键;非空时绑定已有任务不重复触发。 + Returns: + FilePreparationResult(file_ready / waiting_rpa_callback / failed)。 + """ + ready = repository.latest_ready_file(source_code=source_code, business_date=business_date) + if ready is not None: + return FilePreparationResult(stage=STAGE_FILE_READY, file=ready) + + if active_source_job_key is not None: + # 已有活动抓取任务:绑定等待,不重复触发。 + return FilePreparationResult(stage=STAGE_WAITING_RPA) + + outcome = rpa_trigger.trigger( + source_code=source_code, + business_date=business_date, + reason="precheck_missing_ready_file", + ) + outcome = outcome if isinstance(outcome, dict) else {} + if outcome.get("ok"): + return FilePreparationResult(stage=STAGE_WAITING_RPA) + return FilePreparationResult( + stage=STAGE_FAILED, + error_code=str(outcome.get("error_code") or "RPA_TRIGGER_FAILED"), + error_message=str(outcome.get("error_message") or "rpa trigger failed"), + ) diff --git a/backend/app/services/in_transit_transfer/gateway_adapter.py b/backend/app/services/in_transit_transfer/gateway_adapter.py new file mode 100644 index 00000000..5e5c5d10 --- /dev/null +++ b/backend/app/services/in_transit_transfer/gateway_adapter.py @@ -0,0 +1,80 @@ +"""services/in_transit_transfer/gateway_adapter.py + +用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用 + (query_inventory 是首个配置绑定消费者)。 +依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。 +逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer / + verify_duplicate 留待调拨执行阶段(Phase 2)接线。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from app.core.errors import AppError +from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery + +QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory" + + +class CapabilityErpAdapter: + """把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。 + + Args: + gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。 + """ + + def __init__(self, gateway: Any | None = None) -> None: + self._gateway = gateway + + def _gateway_or_default(self): + if self._gateway is not None: + return self._gateway + from app.services.integration_connector.gateway import get_capability_gateway + + return get_capability_gateway() + + def query_inventory( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> InventoryQuery: + """查询外部系统库存(经连接器框架)。 + + Args/Raises: + 与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError; + 写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={}); + 来源专属绑定待 P2/P3。 + """ + result = self._gateway_or_default().call( + capability=QUERY_INVENTORY_CAPABILITY, + context={}, + params={ + "invoice_no": invoice_no, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + }, + operation_id=operation_id, + ) + if result.status == "timeout": + raise ErpQueryTimeoutError() + if result.status != "success": + raise AppError( + code=result.error_code or "INTEGRATION.CALL_FAILED", + message=result.error_message or "query_inventory failed", + http_status=503, + retryable=False, + ) + data = result.data or {} + found = bool(data.get("found")) + qty = data.get("quantity") + return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None) diff --git a/backend/app/services/in_transit_transfer/invoice_aggregator.py b/backend/app/services/in_transit_transfer/invoice_aggregator.py new file mode 100644 index 00000000..472b9808 --- /dev/null +++ b/backend/app/services/in_transit_transfer/invoice_aggregator.py @@ -0,0 +1,91 @@ +"""在途调拨 Invoice 多行汇总与冲突阻断。 + +用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本; + 同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。 +依赖:app.core.errors.AppError、contracts.RawLineRefDTO。 +逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date +from decimal import Decimal +from typing import Iterable + +from app.core.errors import AppError +from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO +from app.services.in_transit_transfer.file_parser import ParsedReceiptRow + + +@dataclass(frozen=True) +class AggregatedInvoice: + """单 Invoice 汇总结果(含原始行追溯)。""" + + source_code: str + invoice_no: str + material_no: str + material_name: str + specification: str + receipt_date: date + receipt_quantity: Decimal + raw_lines: tuple[RawLineRefDTO, ...] + + +class InvoiceConflictError(AppError): + """同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。""" + + def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str): + super().__init__( + code=TRANSFER_INVOICE_CONFLICT, + message=message, + http_status=422, + details={"invoice_no": invoice_no, "conflict": conflict}, + ) + + +def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]: + """按 Invoice 汇总收料数量并保留原始行证据。 + + Args: + rows: 已校验的解析行。 + file_version: 当前文件版本(写入原始行追溯)。 + Returns: + 汇总后的 Invoice 列表(按 Invoice 排序)。 + Raises: + InvoiceConflictError: 同一 Invoice 多料号或多收料日期。 + """ + grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {} + for row in rows: + grouped.setdefault((row.source_code, row.invoice_no), []).append(row) + + invoices: list[AggregatedInvoice] = [] + for (source_code, invoice_no), group in sorted(grouped.items()): + material_nos = {row.material_no for row in group} + dates = {row.receipt_date for row in group} + if len(material_nos) > 1: + raise InvoiceConflictError( + invoice_no=invoice_no, + conflict=f"multiple_material_no: {sorted(material_nos)}", + ) + if len(dates) > 1: + raise InvoiceConflictError( + invoice_no=invoice_no, + conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}", + ) + first = group[0] + raw_lines = tuple( + RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version) + for row in group + ) + invoices.append(AggregatedInvoice( + source_code=source_code, + invoice_no=invoice_no, + material_no=first.material_no, + material_name=first.material_name, + specification=first.specification, + receipt_date=first.receipt_date, + receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")), + raw_lines=raw_lines, + )) + return invoices diff --git a/backend/app/services/in_transit_transfer/manual_close_service.py b/backend/app/services/in_transit_transfer/manual_close_service.py new file mode 100644 index 00000000..2f6e9dfb --- /dev/null +++ b/backend/app/services/in_transit_transfer/manual_close_service.py @@ -0,0 +1,66 @@ +"""在途调拨人工关闭服务。 + +用途:将异常项标记为 manually_closed(原因必填、永久排除、历史保留)。 +依赖:models、status、audit、contracts。 +逻辑:result_unknown / success / duplicate_success / manually_closed 禁止关闭。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED + + +def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict: + """人工关闭一个异常 Invoice。 + + Args: + item_id: TransferInvoiceItem.id。 + reason: 关闭原因(必填)。 + actor_id / request_id: 审计上下文。 + Returns: + {"item_id": ..., "status": "manually_closed"}。 + Raises: + ValidationError: 原因缺失或状态不可关闭。 + NotFoundError: item 不存在。 + """ + reason_value = str(reason or "").strip() + if not reason_value: + raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED) + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") + if item.status in { + status_machine.TransferStatus.SUCCESS.value, + status_machine.TransferStatus.DUPLICATE_SUCCESS.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + }: + raise ValidationError(f"item status {item.status} is not closeable", code="TRANSFER.MANUAL_CLOSE_NOT_ALLOWED") + + before_status = item.status + item.status = status_machine.TransferStatus.MANUALLY_CLOSED.value + item.result_code = "manually_closed" + item.result_message = reason_value + item.manually_closed_reason = reason_value + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ITEM_MANUALLY_CLOSED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=item.run.run_no if item.run else None, + invoice_no=item.invoice_no, + item_id=str(item.id), + actor_type="user", + actor_id=str(actor_id) if actor_id is not None else None, + request_id=request_id, + result="success", + before={"status": before_status}, + after={"status": item.status, "reason": reason_value}, + )) + db.session.commit() + return {"item_id": item.id, "status": item.status} diff --git a/backend/app/services/in_transit_transfer/metrics.py b/backend/app/services/in_transit_transfer/metrics.py new file mode 100644 index 00000000..453a63c1 --- /dev/null +++ b/backend/app/services/in_transit_transfer/metrics.py @@ -0,0 +1,56 @@ +"""在途调拨运营指标。 + +用途:从数据库现状投影成功率、失败类型、待处理老化与通知失败等指标, + 供运营看板与告警使用。 +依赖:models、backlog_service。 +逻辑:指标只读,不触发任何外部调用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.backlog_service import backlog_summary +from app.services.in_transit_transfer.status import TransferNotificationStatus + + +def collect_metrics(*, now: datetime | None = None) -> dict[str, Any]: + """采集调拨域指标。 + + Args: + now: 判定时刻(老化计算用)。 + Returns: + {"runs": {...}, "items": {...}, "backlog": {...}}。 + """ + runs_by_status: dict[str, int] = {} + for (status,) in db.session.query(TransferRun.status).all(): + runs_by_status[str(status)] = runs_by_status.get(str(status), 0) + 1 + notification_failed_runs = TransferRun.query.filter_by( + notification_status=TransferNotificationStatus.FAILED.value, + ).count() + + items_by_status: dict[str, int] = {} + for (status,) in db.session.query(TransferInvoiceItem.status).all(): + items_by_status[str(status)] = items_by_status.get(str(status), 0) + 1 + + backlog = backlog_summary(now=now) + return { + "runs": { + **runs_by_status, + "notification_failed_runs": notification_failed_runs, + }, + "items": items_by_status, + "backlog": { + "recoverable": backlog.recoverable_count, + "closed": backlog.closed_count, + "unknown": backlog.unknown_count, + "aging": { + "warn_3d": backlog.warn_3d, + "escalate_5d": backlog.escalate_5d, + "critical_7d": backlog.critical_7d, + }, + }, + } diff --git a/backend/app/services/in_transit_transfer/movement_contract.py b/backend/app/services/in_transit_transfer/movement_contract.py new file mode 100644 index 00000000..d4328a3b --- /dev/null +++ b/backend/app/services/in_transit_transfer/movement_contract.py @@ -0,0 +1,75 @@ +"""在途调拨通用异动/移动表领域字段契约。 + +用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。 + 未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。 +依赖:标准库 dataclasses / enum。 +逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity, + 成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum + + +class MovementFieldValueType(StrEnum): + """领域字段值类型(校验与展示共用)。""" + + TEXT = "text" + DECIMAL = "decimal" + DATE = "date" + + +@dataclass(frozen=True) +class MovementField: + """单个定死异动字段契约。 + + Args: + code: 稳定字段名(运行时契约)。 + label: 业务中文名。 + value_type: 值类型(text / decimal / date)。 + is_identity: 是否参与幂等/匹配键。 + required: 是否必填(缺省阻断)。 + """ + + code: str + label: str + value_type: MovementFieldValueType + is_identity: bool = False + required: bool = False + + +# 定死的 10 个通用异动字段(领域契约,不配置化)。 +MOVEMENT_FIELDS: tuple[MovementField, ...] = ( + MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True), + MovementField("line_no", "项次", MovementFieldValueType.TEXT), + MovementField("in_out_flag", "进出库别", MovementFieldValueType.TEXT), + MovementField("material_code", "料号", MovementFieldValueType.TEXT, is_identity=True, required=True), + MovementField("material_name", "品名", MovementFieldValueType.TEXT), + MovementField("warehouse_code", "仓库", MovementFieldValueType.TEXT), + MovementField("storage_code", "储位", MovementFieldValueType.TEXT), + MovementField("lot_no", "批号", MovementFieldValueType.TEXT), + MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True), + MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True), +) + + +def movement_match_key() -> str: + """调拨幂等/汇总键:单号 doc_no。""" + return "doc_no" + + +def movement_quantity_field() -> str: + """严格数量匹配字段:数量 quantity。""" + return "quantity" + + +def movement_identity_fields() -> set[str]: + """参与幂等/匹配判定的字段集(doc_no / material_code / movement_date)。""" + return {field.code for field in MOVEMENT_FIELDS if field.is_identity} + + +def movement_field_codes() -> set[str]: + """全部定死字段名集合。""" + return {field.code for field in MOVEMENT_FIELDS} diff --git a/backend/app/services/in_transit_transfer/movement_file_repository.py b/backend/app/services/in_transit_transfer/movement_file_repository.py new file mode 100644 index 00000000..da2f36ed --- /dev/null +++ b/backend/app/services/in_transit_transfer/movement_file_repository.py @@ -0,0 +1,125 @@ +"""在途调拨真实异动(收料/出货)文件仓库。 + +用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx), + 用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死 + 领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。 +依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、 + movement_contract、openpyxl。 +逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时 + 返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。 +""" + +from __future__ import annotations + +from io import BytesIO +from typing import Any, Mapping + +from app.services.file_assets.storage import file_asset_storage +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile + + +class ShippingReceiptFileRepository: + """真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。""" + + def __init__(self) -> None: + self._storage = file_asset_storage + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。 + Returns: + ReadyReceiptFile(rows 为领域字段名 dict)或 None。 + """ + from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile + + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + return None + config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first() + if config is None or config.parsing_profile_id is None: + return None + profile = config.parsing_profile + if profile is None or profile.status != 'published' or profile.purpose != 'movement': + return None + + report = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + if report is None: + return None + + data = self._storage.get_bytes(report.storage_key) + rows = _extract_movement_rows( + data, + field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}), + sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None, + header_row_index=(profile.definition_json or {}).get('header_row_index'), + ) + return ReadyReceiptFile( + source_code=source_code, + business_date=business_date, + file_no=report.original_filename or str(report.id), + file_version=f"sha256:{report.sha256}"[:64], + checksum=report.sha256, + rows=tuple(rows), + ) + + +def _extract_movement_rows( + data: bytes, + *, + field_mapping: Mapping[str, str], + sheet_name: str | None = None, + header_row_index: int | None = None, +) -> list[dict[str, Any]]: + """从 xlsx 字节按 movement field_mapping 提取领域行 dict。 + + field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。 + 输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。 + """ + from openpyxl import load_workbook + from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index + + wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True) + try: + if sheet_name and sheet_name in wb.sheetnames: + ws = wb[sheet_name] + else: + ws = wb.active + raw_rows: list[list[Any]] = [list(row) for row in ws.iter_rows(values_only=True)] + finally: + wb.close() + if not raw_rows: + return [] + header_idx: int | None = None + if header_row_index is not None: + idx = int(header_row_index) - 1 + if 0 <= idx < len(raw_rows): + header_idx = idx + if header_idx is None: + header_idx = find_inventory_header_row_index(raw_rows) + headers = [str(c or '').strip() for c in raw_rows[header_idx]] + data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r] + + header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()} + return [_map_header_row(headers, row, header_to_code) for row in data_rows] + + +def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]: + """把一行原始单元格按表头别名映射为定死领域字段 dict。""" + output: dict[str, Any] = {} + for index, header in enumerate(headers): + code = header_to_code.get(header) + if code and index < len(row): + output[code] = row[index] + return output diff --git a/backend/app/services/in_transit_transfer/notification.py b/backend/app/services/in_transit_transfer/notification.py new file mode 100644 index 00000000..411d879c --- /dev/null +++ b/backend/app/services/in_transit_transfer/notification.py @@ -0,0 +1,84 @@ +"""在途调拨企业微信汇总通知。 + +用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录 + notification_failed 且不改变 ERP 业务结果(run.status 保持)。 +依赖:models、audit、typing.Protocol。 +逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。 +""" + +from __future__ import annotations + +from typing import Any, Protocol + +from app import db +from app.core.errors import NotFoundError +from app.models import TransferRun +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.status import TransferNotificationStatus + + +class WeComSender(Protocol): + """企业微信汇总通知协议(测试注入 FakeWeCom)。""" + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """发送一次汇总通知。""" + + +def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None, + excel_path: str | None = None) -> dict[str, Any]: + """为 Run 发送一条汇总通知(幂等)。 + + Args: + run_no: Run 编号。 + sender: 企微发送器。 + recipients: 接收人列表(缺省空)。 + excel_path: 异常 Excel 附件路径(可空)。 + Returns: + {"run_no", "notification_status", "delivered"};空数据返回 skipped。 + Raises: + NotFoundError: Run 不存在。 + """ + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + if not run.items: + # 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。 + return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"} + if run.notification_status == TransferNotificationStatus.SUCCESS.value: + # 已成功投递:幂等跳过,保证每个 Run 恰好一条。 + return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False} + + summary = { + "run_no": run.run_no, + "status": run.status, + "business_date": run.business_date, + "counts": dict(run.counts_json or {}), + "result_summary": dict(run.result_summary_json or {}), + } + outcome = sender.send_summary( + run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path, + ) + outcome = outcome if isinstance(outcome, dict) else {} + failed = str(outcome.get("status") or "success") != "success" + run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value + if failed: + run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED") + run.notification_error_message = str(outcome.get("error_message") or "") + # 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。 + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_NOTIFICATION", + aggregate_type="transfer_run", + aggregate_id=run.run_no, + run_no=run.run_no, + actor_type="worker", + result="failure" if failed else "success", + before={"status": run.status, "notification_status": "pending"}, + after={"status": run.status, "notification_status": run.notification_status}, + )) + db.session.commit() + return { + "run_no": run.run_no, + "notification_status": run.notification_status, + "delivered": True, + } diff --git a/backend/app/services/in_transit_transfer/orchestrator.py b/backend/app/services/in_transit_transfer/orchestrator.py new file mode 100644 index 00000000..ba3918c4 --- /dev/null +++ b/backend/app/services/in_transit_transfer/orchestrator.py @@ -0,0 +1,83 @@ +"""在途调拨执行编排(Run 生命周期辅助)。 + +用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、 + 按明细终态收尾 Run(success / partial_failed)。 +依赖:models、status、precheck_service.TransferDeps。 +逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime + +from app import db +from app.core.errors import ConflictError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.precheck_service import TransferDeps + +EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED" + + +def create_execution_run( + precheck: TransferPrecheck, + *, + deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展 + actor_id: int | None = None, + selected_invoice_nos: set[str] | None = None, +) -> TransferRun: + """为已就绪预检创建执行 Run 并关联选中的可执行明细。 + + Args: + precheck: 已预检(ready_to_execute)对象。 + deps: 依赖集合(预留)。 + actor_id: 确认操作者。 + selected_invoice_nos: 选择范围(缺省关联全部可执行项)。 + Returns: + 状态为 executing 的 TransferRun。 + Raises: + ConflictError: 预检已确认(重复执行)。 + """ + if precheck.confirmed_at is not None: + raise ConflictError( + "precheck already executed", code=EXECUTION_CONFLICT_CODE, + ) + run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}" + run = TransferRun( + run_no=run_no, + trigger_type="manual", + business_date=precheck.business_date, + status=status_machine.TransferRunStatus.EXECUTING.value, + source_codes_json=list(precheck.scope_json.get("source_codes") or []), + counts_json=dict(precheck.counts_json or {}), + ) + db.session.add(run) + db.session.flush() + + precheck.run_id = run.id + precheck.status = status_machine.TransferRunStatus.EXECUTING.value + precheck.confirmed_at = datetime.utcnow() + precheck.confirmed_by = actor_id + + for item in precheck.items: + if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None: + continue + if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos: + continue + item.run_id = run.id + item.status = status_machine.TransferStatus.EXECUTING.value + item.attempt_no += 1 + db.session.flush() + return run + + +def finalize_run(run: TransferRun, items: list[TransferInvoiceItem]) -> None: + """按明细终态汇总 Run 状态(全部 success/duplicate_success → success,否则 partial_failed)。""" + statuses = {str(item.status) for item in items} + terminal_ok = {status_machine.TransferStatus.SUCCESS.value, status_machine.TransferStatus.DUPLICATE_SUCCESS.value} + if statuses and statuses <= terminal_ok: + run.status = status_machine.TransferRunStatus.SUCCESS.value + else: + run.status = status_machine.TransferRunStatus.PARTIAL_FAILED.value + run.completed_at = datetime.utcnow() diff --git a/backend/app/services/in_transit_transfer/precheck_service.py b/backend/app/services/in_transit_transfer/precheck_service.py new file mode 100644 index 00000000..b336c028 --- /dev/null +++ b/backend/app/services/in_transit_transfer/precheck_service.py @@ -0,0 +1,578 @@ +"""在途调拨预检服务。 + +用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 → + 严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。 +依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter / + date_policy / quantity / contracts / audit / models。 +逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP; + 预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。 +""" + +from __future__ import annotations + +import uuid +from dataclasses import asdict, dataclass, field +from datetime import date, datetime, timedelta +from decimal import Decimal +from typing import Any, Protocol + +from app import db +from app.core.errors import AppError, NotFoundError, ValidationError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import canonical_hash +from app.services.in_transit_transfer.contracts import ( + PrecheckCountsDTO, + PrecheckInvoiceItemDTO, + PrecheckSummaryDTO, + RawLineRefDTO, +) +from app.services.in_transit_transfer.date_policy import ( + MATURITY_ELIGIBLE, + MATURITY_FUTURE, + MATURITY_NOT_MATURED, + maturity_status, +) +from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_receipt_rows, +) +from app.services.in_transit_transfer.file_preparation import ( + ReadyReceiptFile, + ReceiptFileRepository, + RpaTrigger, + ensure_receipt_file_ready, +) +from app.services.in_transit_transfer.invoice_aggregator import ( + InvoiceConflictError, + aggregate_invoices, +) +from app.services.in_transit_transfer.quantity import classify_quantity_match +from app.services.in_transit_transfer.strategy import ( + TransferStrategyPolicy, + default_strategy, +) + +ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED" + +# 明细结果值(对应 Invoice 项状态) +RESULT_EXECUTABLE = "executable" +RESULT_NOT_MATURED = "not_matured" +RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch" +RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" +RESULT_FUTURE_DATE = "blocked_future_date" +RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout" + + +@dataclass(frozen=True) +class RouteMapping: + """来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。""" + + erp_org: str + from_warehouse: str + to_warehouse: str + + +class RouteNotResolvedError(AppError): + """来源实例缺少路由归属映射(fail-closed)。""" + + def __init__(self, *, source_code: str): + super().__init__( + code=ROUTE_NOT_RESOLVED_CODE, + message=f"route not resolved for source {source_code}", + http_status=422, + details={"source_code": source_code}, + ) + + +class RouteResolver(Protocol): + """来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。""" + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。""" + + +@dataclass(frozen=True) +class SourceProgressDTO: + """来源实例级进度(决策 18:来源隔离展示)。""" + + source_code: str + stage: str + file_no: str | None = None + file_version: str | None = None + checksum: str | None = None + error_code: str | None = None + error_message: str | None = None + + +@dataclass(frozen=True) +class PrecheckRunResult: + """一次预检运行的完整结果。""" + + summary: PrecheckSummaryDTO + items: tuple[PrecheckInvoiceItemDTO, ...] + sources: tuple[SourceProgressDTO, ...] + + +@dataclass(frozen=True) +class TransferDeps: + """预检/执行依赖集合(测试注入 Fake 替身)。""" + + file_repository: ReceiptFileRepository + rpa_trigger: RpaTrigger + route_resolver: RouteResolver + erp: Any + strategy: TransferStrategyPolicy = field(default_factory=default_strategy) + + +def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str: + """预检状态:存在未完成来源 → file_pending;否则按可执行数定。""" + if any(source.stage not in {"file_ready"} for source in sources): + return "file_pending" + if counts.executable_count > 0: + return "ready_to_execute" + return "success" + + +def run_precheck( + *, + source_codes: list[str], + business_date: str, + deps: TransferDeps, + active_source_job_key: str | None = None, + run_no: str = "RUN-PENDING", +) -> PrecheckRunResult: + """执行一次只读预检(不写 ERP)。 + + Args: + source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。 + business_date: 业务日期 T(YYYY-MM-DD)。 + deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。 + active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。 + run_no: Run 编号(创建 Run 前可为占位)。 + Returns: + PrecheckRunResult(摘要 + 明细 + 来源进度)。 + Raises: + ValidationError: source_codes 为空。 + """ + if not source_codes: + raise ValidationError("source_codes is required") + validate_strategy = deps.strategy + + sources: list[SourceProgressDTO] = [] + items: list[PrecheckInvoiceItemDTO] = [] + file_snapshot: dict[str, Any] = {} + for source_code in source_codes: + source_stage: SourceProgressDTO + try: + prepared = ensure_receipt_file_ready( + source_code=source_code, + business_date=business_date, + repository=deps.file_repository, + rpa_trigger=deps.rpa_trigger, + active_source_job_key=active_source_job_key, + ) + if prepared.stage != "file_ready" or prepared.file is None: + sources.append(SourceProgressDTO( + source_code=source_code, + stage=prepared.stage, + error_code=prepared.error_code, + error_message=prepared.error_message, + )) + continue + ready_file = prepared.file + file_snapshot[source_code] = { + "file_no": ready_file.file_no, + "file_version": ready_file.file_version, + "checksum": ready_file.checksum, + } + parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows) + invoices = aggregate_invoices(parsed, file_version=ready_file.file_version) + source_items = _precheck_invoices( + invoices=invoices, + source_code=source_code, + business_date=business_date, + ready_file=ready_file, + deps=deps, + run_no=run_no, + ) + items.extend(source_items) + sources.append(SourceProgressDTO( + source_code=source_code, + stage="file_ready", + file_no=ready_file.file_no, + file_version=ready_file.file_version, + checksum=ready_file.checksum, + )) + except (ReceiptFileSchemaError, InvoiceConflictError) as exc: + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code=exc.code, error_message=exc.message, + )) + except RouteNotResolvedError as exc: + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code=exc.code, error_message=exc.message, + )) + except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源 + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code="TRANSFER.SOURCE_PRECheck_ERROR", + error_message=str(exc), + )) + + counts = PrecheckCountsDTO( + file_invoice_count=sum( + 1 for item in items + ), + not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED), + prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED), + executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE), + blocked_count=sum(1 for item in items if item.result.startswith("blocked_")), + ) + estimated_quantity = sum( + (item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0") + ) + snapshot = { + "scope": sorted(set(source_codes)), + "business_date": business_date, + "file_snapshot": file_snapshot, + "counts": { + "file_invoice_count": counts.file_invoice_count, + "not_matured_count": counts.not_matured_count, + "prechecked_count": counts.prechecked_count, + "executable_count": counts.executable_count, + "blocked_count": counts.blocked_count, + }, + "items": [ + { + "source_code": item.source_code, + "invoice_no": item.invoice_no, + "from_warehouse": item.from_warehouse, + "to_warehouse": item.to_warehouse, + "receipt_quantity": str(item.to_quantity), + "erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None, + "result": item.result, + } + for item in items + ], + } + precheck_hash = f"sha256:{canonical_hash(snapshot)}" + sources_tuple = tuple(sources) + summary = PrecheckSummaryDTO( + precheck_id="", # 落库时回填 + status=_summary_status(sources_tuple, counts), + business_date=business_date, + eligible_receipt_date_to=str( + (date.fromisoformat(business_date) - timedelta(days=1)) + ), + expires_at="", + counts=counts, + estimated_transfer_quantity=str(estimated_quantity), + estimated_erp_write_count=counts.executable_count, + precheck_hash=precheck_hash, + ) + return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple) + + +def _precheck_invoices( + *, + invoices: list, + source_code: str, + business_date: str, + ready_file: ReadyReceiptFile, + deps: TransferDeps, + run_no: str, +) -> list[PrecheckInvoiceItemDTO]: + """对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。""" + output: list[PrecheckInvoiceItemDTO] = [] + for invoice in invoices: + maturity = maturity_status(invoice.receipt_date, business_date) + raw = tuple( + RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version) + for line in invoice.raw_lines + ) + receipt_date_iso = invoice.receipt_date.isoformat() + if maturity == MATURITY_NOT_MATURED: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse="", from_quantity=None, + to_warehouse="", to_quantity=invoice.receipt_quantity, + result=RESULT_NOT_MATURED, reason="receipt not matured until next business day", + raw_lines=raw, + )) + continue + if maturity == MATURITY_FUTURE: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse="", from_quantity=None, + to_warehouse="", to_quantity=invoice.receipt_quantity, + result=RESULT_FUTURE_DATE, reason="future receipt date", + raw_lines=raw, + )) + continue + route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + try: + query = deps.erp.query_inventory( + operation_id=operation_id, + run_no=run_no, + attempt_no=1, + invoice_no=invoice.invoice_no, + erp_org=route.erp_org, + from_warehouse=route.from_warehouse, + to_warehouse=route.to_warehouse, + quantity=invoice.receipt_quantity, + ) + except ErpQueryTimeoutError: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=None, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout", + raw_lines=raw, + )) + continue + if not query.found: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=None, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found", + raw_lines=raw, + )) + continue + match = classify_quantity_match(invoice.receipt_quantity, query.quantity) + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=query.quantity, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch", + raw_lines=raw, + )) + return output + + +def _item_status(result: str) -> str: + """明细结果 → Invoice 项状态。""" + mapping = { + RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value, + RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value, + RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + } + return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value) + + +def _generate_no(prefix: str, business_date: str) -> str: + """生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。""" + compact = str(business_date).replace("-", "") + return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}" + + +def create_precheck( + *, + source_codes: list[str], + business_date: str, + deps: TransferDeps, + active_source_job_key: str | None = None, +) -> PrecheckSummaryDTO: + """运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。 + + Args: + source_codes / business_date / deps: 同 run_precheck。 + Returns: + 预检摘要(precheck_id 已回填)。 + """ + run_no = _generate_no("RUN", business_date) + result = run_precheck( + source_codes=source_codes, + business_date=business_date, + deps=deps, + active_source_job_key=active_source_job_key, + run_no=run_no, + ) + now = datetime.utcnow() + run = TransferRun( + run_no=run_no, + trigger_type="manual", + business_date=business_date, + status="prechecking", + source_codes_json=list(source_codes), + counts_json=asdict(result.summary.counts), + ) + db.session.add(run) + db.session.flush() + + # 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。 + # 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。 + from app.services.in_transit_transfer.source_job_service import create_source_job + + _valid_job_statuses = { + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', + } + for job_source in result.sources: + create_source_job( + run_id=run.id, + source_code=job_source.source_code, + status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending', + ) + + precheck_no = _generate_no("TPC", business_date) + precheck = TransferPrecheck( + precheck_no=precheck_no, + run_id=run.id, + business_date=business_date, + status=result.summary.status, + scope_json={"source_codes": list(source_codes)}, + file_snapshot_json={ + stage.source_code: { + "file_no": stage.file_no, + "file_version": stage.file_version, + "checksum": stage.checksum, + } + for stage in result.sources + if stage.file_no + }, + mapping_version="v0", + strategy_version="v0", + counts_json=asdict(result.summary.counts), + estimated_transfer_quantity=result.summary.estimated_transfer_quantity, + estimated_erp_write_count=result.summary.estimated_erp_write_count, + precheck_hash=result.summary.precheck_hash, + expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds), + ) + db.session.add(precheck) + db.session.flush() + + for item in result.items: + db.session.add(TransferInvoiceItem( + precheck_id=precheck.id, + # 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。 + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + receipt_date=item.receipt_date, + from_warehouse=item.from_warehouse or "", + to_warehouse=item.to_warehouse or "", + receipt_quantity=str(item.to_quantity), + erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None, + status=_item_status(item.result), + result_code=item.result if item.result != RESULT_EXECUTABLE else None, + result_message=item.reason or None, + raw_lines_json=[ + {"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version} + for line in item.raw_lines + ], + )) + db.session.commit() + + summary = PrecheckSummaryDTO( + precheck_id=precheck_no, + status=precheck.status, + business_date=precheck.business_date, + eligible_receipt_date_to=result.summary.eligible_receipt_date_to, + expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "", + counts=result.summary.counts, + estimated_transfer_quantity=result.summary.estimated_transfer_quantity, + estimated_erp_write_count=result.summary.estimated_erp_write_count, + precheck_hash=result.summary.precheck_hash, + ) + return summary + + +def restore_precheck(precheck_id: str) -> dict[str, Any]: + """按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。 + + Args: + precheck_id: 预检编号(TPC-...)。 + Returns: + {"summary": {...}, "items": [...], "sources": [...]}。 + Raises: + NotFoundError: 预检不存在。 + """ + precheck = db.session.query(TransferPrecheck).filter_by( + precheck_no=str(precheck_id).strip() + ).first() + if precheck is None: + raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND") + counts = PrecheckCountsDTO(**{ + key: int(precheck.counts_json.get(key, 0)) + for key in ("file_invoice_count", "not_matured_count", "prechecked_count", + "executable_count", "blocked_count") + }) + summary = PrecheckSummaryDTO( + precheck_id=precheck.precheck_no, + status=precheck.status, + business_date=precheck.business_date, + eligible_receipt_date_to=str( + date.fromisoformat(precheck.business_date) - timedelta(days=1) + ), + expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "", + counts=counts, + estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0", + estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0), + precheck_hash=precheck.precheck_hash, + ) + items = [] + for item in sorted(precheck.items, key=lambda row: row.invoice_no): + items.append(PrecheckInvoiceItemDTO( + source_code=item.source_code, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + invoice_no=item.invoice_no, + from_warehouse=item.from_warehouse, + from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None, + to_warehouse=item.to_warehouse, + to_quantity=Decimal(item.receipt_quantity), + result=item.result_code or ( + RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status + ), + raw_lines=tuple( + RawLineRefDTO( + sheet=line.get("sheet", ""), + row_no=int(line.get("row_no", 0)), + file_version=line.get("file_version", ""), + ) + for line in (item.raw_lines_json or []) + ), + )) + sources = [ + SourceProgressDTO( + source_code=job.source_code, + stage=job.status, + file_no=job.file_no, + file_version=None, + checksum=job.file_sha256, + ) + for job in (precheck.run.source_jobs if precheck.run else []) + ] or [ + SourceProgressDTO(source_code=code, stage="file_ready") + for code in (precheck.scope_json.get("source_codes") or []) + ] + return { + "summary": summary, + "items": items, + "sources": sources, + } diff --git a/backend/app/services/in_transit_transfer/quantity.py b/backend/app/services/in_transit_transfer/quantity.py new file mode 100644 index 00000000..4abbe52b --- /dev/null +++ b/backend/app/services/in_transit_transfer/quantity.py @@ -0,0 +1,61 @@ +"""在途调拨严格数量门禁。 + +用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则, + 禁止部分调拨、数量容差与隐式截断。 +依赖:标准库 decimal。 +逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。 +""" + +from __future__ import annotations + +from decimal import Decimal, InvalidOperation +from typing import Any + +# 匹配结果 +MATCH_EXECUTABLE = "executable" +MATCH_QUANTITY_MISMATCH = "blocked_quantity_mismatch" +MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" + + +class QuantityValidationError(ValueError): + """收料数量非法(0、负数、非数字)。""" + + +def validate_receipt_quantity(value: Any) -> Decimal: + """校验并归一化收料数量。 + + Args: + value: 数字或数字字符串。 + Returns: + 归一化后的 Decimal。 + Raises: + QuantityValidationError: 非数字、0 或负数。 + """ + try: + quantity = Decimal(str(value)) + except (InvalidOperation, ValueError) as exc: + raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc + if quantity <= 0: + raise QuantityValidationError(f"receipt quantity must be positive: {value!r}") + return quantity + + +def strict_quantities_equal(left: Any, right: Any) -> bool: + """Decimal 精确相等比较(1.0 == 1.00)。""" + return Decimal(str(left)) == Decimal(str(right)) + + +def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str: + """按严格相等规则分类数量匹配结果。 + + Args: + receipt_quantity: 收料数量。 + erp_quantity: ERP 账面库存;None 表示无库存。 + Returns: + 'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。 + """ + if erp_quantity is None: + return MATCH_INVENTORY_NOT_FOUND + if strict_quantities_equal(receipt_quantity, erp_quantity): + return MATCH_EXECUTABLE + return MATCH_QUANTITY_MISMATCH diff --git a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py new file mode 100644 index 00000000..4b3e0554 --- /dev/null +++ b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py @@ -0,0 +1,57 @@ +"""在途调拨收料回调桥。 + +用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob: + success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。 +依赖:models(TransferSourceJob)、datetime。 +逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作, + 避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import TransferSourceJob + +_FILE_READY = 'file_ready' +_WAITING_RPA_CALLBACK = 'waiting_rpa_callback' +_FAILED = 'failed' + + +def advance_source_job_from_receipt_callback( + *, source_code: str, file_no: str | None = None, file_sha256: str | None = None, + callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None, +) -> TransferSourceJob | None: + """按来源推进最新等待回调的调拨来源任务。 + + Args: + source_code: 回调所属来源实例。 + file_no: 收料文件号(success 时)。 + file_sha256: 收料文件 sha256(success 时)。 + callback_ok / error_code / error_message: 回调终态。 + Returns: + 被推进的任务;无等待任务或已终态时返回 None。 + """ + job = ( + TransferSourceJob.query + .filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK) + .order_by(TransferSourceJob.id.desc()) + .first() + ) + if job is None: + return None + if callback_ok and file_no: + job.status = _FILE_READY + job.file_no = file_no + job.file_sha256 = file_sha256 + job.error_code = None + job.error_message = None + job.finished_at = datetime.utcnow() + else: + job.status = _FAILED + job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED' + job.error_message = error_message or 'receipt rpa callback failed' + job.finished_at = datetime.utcnow() + db.session.flush() + return job diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/receipt_trigger_service.py new file mode 100644 index 00000000..2440487a --- /dev/null +++ b/backend/app/services/in_transit_transfer/receipt_trigger_service.py @@ -0,0 +1,101 @@ +"""在途调拨真实收料 RPA 触发服务。 + +用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。 + 按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile, + 装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。 +依赖:write_receipt_export_batch_trigger(默认 writer)、models。 +逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待; + 写 trigger writer 可注入替身(测试)。 +""" + +from __future__ import annotations + +import uuid +from typing import Any, Callable + +from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger + +RouteTriggerWriter = Callable[..., str | None] + + +def _build_trigger_unit( + *, source_code: str, business_date: str, reason: str, +) -> dict[str, Any]: + """装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。""" + from app.models import ShippingInventorySource, ShippingReceiptReportConfig + + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + raise RuntimeError(f'source not enabled: {source_code}') + config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first() + if config is None: + raise RuntimeError(f'receipt config missing: {source_code}') + profile = source.rpa_profile + if profile is None or not profile.enabled: + raise RuntimeError(f'receipt source profile unavailable: {source_code}') + warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None] + warehouse_id = str(warehouses[0]) if warehouses else None + snapshot = { + 'config_id': config.id, 'config_version': config.config_version, + 'connector_type': source.connector_type, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id, + } + return { + 'unit_run_id': 0, + 'callback_id': f'receipt:{uuid.uuid4().hex}', + 'source_code': source.source_code, + 'connector_type': source.connector_type, + 'warehouse_id': warehouse_id, + 'rpa_profile_id': profile.id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), + 'config_snapshot': snapshot, + 'business_date': business_date, + 'reason': reason, + } + + +def trigger_receipt_rpa( + *, + source_code: str, + business_date: str, + reason: str = 'transfer_retry_receipt', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """触发一次来源收料 RPA 抓取。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger)。 + writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。 + Returns: + {"ok": True, "callback_id": ..., "trigger_path": ...} 或 + {"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。 + """ + try: + unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason) + except RuntimeError as exc: + return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)} + + run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or write_receipt_export_batch_trigger + path = writer_fn(run_no, [unit], payload={ + 'schema_version': 'shipping_receipt_rpa.v1', + 'action': 'receipt_export_batch', + 'source_code': source_code, + 'business_date': business_date, + 'reason': reason, + }) + if not path: + return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"} + return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path} diff --git a/backend/app/services/in_transit_transfer/recovery.py b/backend/app/services/in_transit_transfer/recovery.py new file mode 100644 index 00000000..2eafd737 --- /dev/null +++ b/backend/app/services/in_transit_transfer/recovery.py @@ -0,0 +1,87 @@ +"""在途调拨 Worker 崩溃/陈旧执行恢复(区别于 recovery_service 的每日历史复核)。 + +用途:回收租约过期的 executing 项(重新写前复查 + 幂等写入,不重复建单), + 并将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。 +依赖:execution_service._write_item、orchestrator.finalize_run、status。 +逻辑:恢复依赖 Invoice 幂等(重复返回原单号 duplicate_success); + result_unknown 绝不自动重试。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.execution_service import _write_item +from app.services.in_transit_transfer.orchestrator import finalize_run +from app.services.in_transit_transfer.precheck_service import TransferDeps + +STALE_EXECUTION_THRESHOLD_SECONDS = 3600 + +_TERMINAL_ITEM_STATUSES = { + status_machine.TransferStatus.SUCCESS.value, + status_machine.TransferStatus.DUPLICATE_SUCCESS.value, + status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + status_machine.TransferStatus.RESULT_UNKNOWN.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + status_machine.TransferStatus.CANCELLED.value, +} + + +def recover_stale_execution_items(*, deps: TransferDeps, now: datetime | None = None, + request_id: str | None = None) -> dict: + """回收租约过期的执行中明细。 + + Args: + deps: 注入依赖。 + now: 判定时刻。 + request_id: 审计上下文。 + Returns: + {"recovered": n, "skipped_result_unknown": n, "failed": n}。 + """ + current = now or datetime.utcnow() + threshold = current - timedelta(seconds=STALE_EXECUTION_THRESHOLD_SECONDS) + items = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status == status_machine.TransferStatus.EXECUTING.value, + TransferInvoiceItem.updated_at <= threshold, + ).all() + recovered = skipped_unknown = failed = 0 + for item in items: + if (item.result_code or "") == "result_unknown" or item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + skipped_unknown += 1 + continue + run_no = item.run.run_no if item.run else "RUN-PENDING" + try: + _write_item(item, deps=deps, run_no=run_no, request_id=request_id) + recovered += 1 + except Exception: # noqa: BLE001 —— 单项恢复失败不阻断其他项 + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = "recovery_failed" + failed += 1 + db.session.flush() + db.session.commit() + return {"recovered": recovered, "skipped_result_unknown": skipped_unknown, "failed": failed} + + +def finalize_stale_runs(*, now: datetime | None = None) -> list[int]: + """将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。 + + Args: + now: 判定时刻(保留参数)。 + Returns: + 已收尾的 Run id 列表。 + """ + finalized: list[int] = [] + runs = TransferRun.query.filter_by( + status=status_machine.TransferRunStatus.EXECUTING.value, + ).all() + for run in runs: + items = list(run.items) + if items and all(item.status in _TERMINAL_ITEM_STATUSES for item in items): + finalize_run(run, items) + finalized.append(run.id) + db.session.flush() + db.session.commit() + return finalized diff --git a/backend/app/services/in_transit_transfer/recovery_service.py b/backend/app/services/in_transit_transfer/recovery_service.py new file mode 100644 index 00000000..f810ad62 --- /dev/null +++ b/backend/app/services/in_transit_transfer/recovery_service.py @@ -0,0 +1,66 @@ +"""在途调拨每日历史恢复(自动复核待处理池)。 + +用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt; + result_unknown / manually_closed / success 不自动写入。 +依赖:models、retry_service._recheck_item、TransferDeps。 +逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.precheck_service import TransferDeps +from app.services.in_transit_transfer.retry_service import _recheck_item + + +@dataclass +class RecoveryOutcome: + """每日恢复结果汇总。""" + + recovered_count: int = 0 + still_blocked_count: int = 0 + skipped_result_unknown: int = 0 + skipped_manually_closed: int = 0 + attempts_created: int = 0 + + +def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOutcome: + """对可恢复异常执行每日自动复核。 + + Args: + business_date: 业务日期(仅用于审计上下文)。 + deps: 注入依赖。 + Returns: + RecoveryOutcome。 + """ + outcome = RecoveryOutcome() + items = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status.in_([ + status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + status_machine.TransferStatus.RESULT_UNKNOWN.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + ]), + ).all() + for item in items: + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + # 只读隔离:不查询、不写入、不创建 Attempt。 + outcome.skipped_result_unknown += 1 + continue + if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value: + # 永久排除。 + outcome.skipped_manually_closed += 1 + continue + before_attempt = item.attempt_no + new_status = _recheck_item(item, deps=deps, request_id=None) + if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value: + outcome.recovered_count += 1 + else: + outcome.still_blocked_count += 1 + if item.attempt_no > before_attempt: + outcome.attempts_created += 1 + db.session.commit() + return outcome diff --git a/backend/app/services/in_transit_transfer/retry_service.py b/backend/app/services/in_transit_transfer/retry_service.py new file mode 100644 index 00000000..2cbd7609 --- /dev/null +++ b/backend/app/services/in_transit_transfer/retry_service.py @@ -0,0 +1,120 @@ +"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。 + +用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP; + Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。 +依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。 +逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from decimal import Decimal + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps +from app.services.in_transit_transfer.quantity import classify_quantity_match + +RETRY_KIND_ERP_RECHECK = "erp_recheck" +RETRY_KIND_RPA_REFETCH = "rpa_refetch" + + +def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str: + """对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。 + + Returns: + 重检后的 item 状态。 + """ + route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + receipt_qty = Decimal(item.receipt_quantity) + query = deps.erp.query_inventory( + operation_id=operation_id, + run_no=item.run.run_no if item.run else "RUN-PENDING", + attempt_no=item.attempt_no + 1, + invoice_no=item.invoice_no, + erp_org=route.erp_org, + from_warehouse=route.from_warehouse, + to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + item.attempt_no += 1 + before_status = item.status + attempt = TransferAttempt( + item_id=item.id, attempt_no=item.attempt_no, kind="erp_query", + status="running", operation_id=operation_id, + request_snapshot_json={ + "invoice_no": item.invoice_no, "erp_org": route.erp_org, + "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, + "quantity": str(receipt_qty), + }, + ) + db.session.add(attempt) + db.session.flush() + if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE: + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch" + item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch" + attempt.status = "failed" + else: + item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value + item.result_code = None + item.result_message = None + item.erp_quantity = str(query.quantity) + attempt.status = "success" + attempt.completed_at = datetime.utcnow() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ITEM_RECHECKED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=item.run.run_no if item.run else None, + invoice_no=item.invoice_no, + item_id=str(item.id), + attempt_no=item.attempt_no, + actor_type="worker", + request_id=request_id, + operation_id=operation_id, + result="success" if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value else "failure", + before={"status": before_status}, + after={"status": item.status, "attempt_no": item.attempt_no}, + )) + db.session.flush() + return item.status + + +def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK, + actor_id: int | None = None, request_id: str | None = None) -> dict: + """人工重试异常项。 + + Args: + item_id: TransferInvoiceItem.id。 + deps: 注入依赖。 + kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。 + actor_id / request_id: 审计上下文。 + Returns: + {"item_id": ..., "status": ..., "attempt_no": ...}。 + Raises: + ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。 + NotFoundError: item 不存在。 + """ + kind_value = str(kind or "").strip() + if kind_value == RETRY_KIND_RPA_REFETCH: + raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED") + if kind_value != RETRY_KIND_ERP_RECHECK: + raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID") + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") + if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}: + raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED") + + status = _recheck_item(item, deps=deps, request_id=request_id) + db.session.commit() + return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no} diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py new file mode 100644 index 00000000..9d08e68d --- /dev/null +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -0,0 +1,77 @@ +"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。 + +用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。 +依赖:contracts、execution_service。 +逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.in_transit_transfer.execution_service import serialize_run_result + + +def serialize_summary(summary) -> dict[str, Any]: + """预检摘要序列化。""" + return { + "precheck_id": summary.precheck_id, + "status": summary.status, + "business_date": summary.business_date, + "eligible_receipt_date_to": summary.eligible_receipt_date_to, + "expires_at": summary.expires_at, + "counts": { + "file_invoice_count": summary.counts.file_invoice_count, + "not_matured_count": summary.counts.not_matured_count, + "prechecked_count": summary.counts.prechecked_count, + "executable_count": summary.counts.executable_count, + "blocked_count": summary.counts.blocked_count, + }, + "estimated_transfer_quantity": summary.estimated_transfer_quantity, + "estimated_erp_write_count": summary.estimated_erp_write_count, + "precheck_hash": summary.precheck_hash, + } + + +def serialize_item(item) -> dict[str, Any]: + """明细项序列化(决策 6 十列字段)。""" + return { + "source_code": item.source_code, + "material_no": item.material_no, + "material_name": item.material_name, + "specification": item.specification, + "invoice_no": item.invoice_no, + "receipt_date": item.receipt_date, + "from_warehouse": item.from_warehouse, + "from_quantity": str(item.from_quantity) if item.from_quantity is not None else None, + "to_warehouse": item.to_warehouse, + "to_quantity": str(item.to_quantity), + "result": item.result, + "reason": item.reason, + "raw_lines": [ + {"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version} + for line in item.raw_lines + ], + } + + +def serialize_source(source) -> dict[str, Any]: + """来源进度序列化。""" + return { + "source_code": source.source_code, + "stage": source.stage, + "file_no": source.file_no, + "file_version": source.file_version, + "checksum": source.checksum, + "error_code": source.error_code, + "error_message": source.error_message, + } + + +def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]: + """预检恢复详情(summary + items + sources)。""" + return { + "summary": serialize_summary(detail["summary"]), + "items": [serialize_item(item) for item in detail["items"]], + "sources": [serialize_source(source) for source in detail["sources"]], + } diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py new file mode 100644 index 00000000..13f68e30 --- /dev/null +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -0,0 +1,63 @@ +"""在途调拨来源收料文件状态投影服务。 + +用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile), + 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发", + 供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 +依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。 +逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching; + 最新单元为失败终态 → failed;否则 → none。 +""" + +from __future__ import annotations + +from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun + +RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing') +FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled') + + +def resolve_source_file_status(*, source_code: str) -> dict: + """返回某来源的收料文件状态投影。 + + Returns: + {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, + file_status ∈ {'ready', 'fetching', 'failed', 'none'}。 + """ + report = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + if report is not None: + return { + 'file_status': 'ready', + 'has_ready_file': True, + 'file_no': report.original_filename or str(report.id), + 'file_sha256': report.sha256, + } + + active_unit = ( + ShippingReceiptRpaUnitRun.query + .filter_by(source_code=source_code) + .filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES)) + .order_by(ShippingReceiptRpaUnitRun.id.desc()) + .first() + ) + if active_unit is not None: + return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + latest_unit = ( + ShippingReceiptRpaUnitRun.query + .filter_by(source_code=source_code) + .order_by(ShippingReceiptRpaUnitRun.id.desc()) + .first() + ) + if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES: + return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} diff --git a/backend/app/services/in_transit_transfer/source_job_service.py b/backend/app/services/in_transit_transfer/source_job_service.py new file mode 100644 index 00000000..8626bb3f --- /dev/null +++ b/backend/app/services/in_transit_transfer/source_job_service.py @@ -0,0 +1,70 @@ +"""在途调拨来源级状态服务(唯一推进入口)。 + +用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源), + 让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。 +依赖:models(TransferSourceJob)、status_machine。 +逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束; + 不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import TransferSourceJob + +SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) + + +def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob: + """为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。 + + Args: + run_id: 所属 TransferRun.id。 + source_code: 来源实例编码。 + status: 初始状态。 + Returns: + 新建(或复用已存在同 run 同来源)的 TransferSourceJob。 + """ + existing = ( + TransferSourceJob.query.filter_by(run_id=run_id, source_code=source_code).order_by(TransferSourceJob.id.desc()).first() + ) + if existing is not None: + return existing + job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status) + db.session.add(job) + db.session.flush() + return job + + +def advance_source_job(*, job: TransferSourceJob, status: str, **fields: Any) -> TransferSourceJob: + """推进单条来源 job 状态并写入来源级事实字段。 + + Args: + job: 目标 TransferSourceJob。 + status: 目标状态(须在 SOURCE_JOB_STATUSES 内,模型 CheckConstraint 兜底)。 + fields: 其余来源级字段(file_no/file_sha256/error_code/error_message/lease_until 等), + 可选 finished_at 被重置为当前时间。 + Returns: + 更新后的 job。 + """ + job.status = status + for key, value in fields.items(): + if hasattr(job, key): + setattr(job, key, value) + if status in ('success', 'partial_failed', 'failed', 'cancelled'): + job.finished_at = datetime.utcnow() + if status == 'pending': + job.started_at = datetime.utcnow() + db.session.flush() + return job + + +def source_jobs_for_run(run_id: int) -> list[TransferSourceJob]: + """读取某次 run 的全部来源级 job(供 restore/投影)。""" + return TransferSourceJob.query.filter_by(run_id=run_id).order_by(TransferSourceJob.source_code).all() diff --git a/backend/app/services/in_transit_transfer/status.py b/backend/app/services/in_transit_transfer/status.py new file mode 100644 index 00000000..193f0b71 --- /dev/null +++ b/backend/app/services/in_transit_transfer/status.py @@ -0,0 +1,217 @@ +"""在途调拨状态机与转换门禁。 + +用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期 + (TransferRunStatus)与通知状态(TransferNotificationStatus), + 并强制所有状态转换走服务端门禁。 +依赖:app.core.errors.AppError。 +逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError; + result_unknown / manually_closed / success / duplicate_success / + not_matured / cancelled 为无出边终态; + 通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。 +""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Mapping + +from app.core.errors import AppError + +INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION" + + +class TransferStatus(StrEnum): + """Invoice 项业务状态(含提示词冻结的全部 13 个状态)。""" + + FILE_PENDING = "file_pending" + FILE_READY = "file_ready" + PRECHECKING = "prechecking" + READY_TO_EXECUTE = "ready_to_execute" + EXECUTING = "executing" + SUCCESS = "success" + DUPLICATE_SUCCESS = "duplicate_success" + BLOCKED_RECOVERABLE = "blocked_recoverable" + NOT_MATURED = "not_matured" + RESULT_UNKNOWN = "result_unknown" + MANUALLY_CLOSED = "manually_closed" + CANCELLED = "cancelled" + NOTIFICATION_FAILED = "notification_failed" + + +class TransferRunStatus(StrEnum): + """Run 级生命周期;ERP 结果与通知结果分离。""" + + QUEUED = "queued" + PREPARING_FILES = "preparing_files" + PRECHECKING = "prechecking" + READY_TO_EXECUTE = "ready_to_execute" + EXECUTING = "executing" + SUCCESS = "success" + PARTIAL_FAILED = "partial_failed" + FAILED = "failed" + CANCELLED = "cancelled" + + +class TransferNotificationStatus(StrEnum): + """通知投递状态;failed 即提示词中 notification_failed 的语义。""" + + PENDING = "pending" + SUCCESS = "success" + FAILED = "failed" + + +# 无出边终态:这些状态不得再触发任何自动或手工迁移。 +TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({ + TransferStatus.SUCCESS.value, + TransferStatus.DUPLICATE_SUCCESS.value, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.MANUALLY_CLOSED.value, + TransferStatus.CANCELLED.value, + TransferStatus.NOT_MATURED.value, + TransferStatus.NOTIFICATION_FAILED.value, +}) + +# Invoice 项转换白名单:key=当前状态,value=允许的目标状态集合。 +ITEM_TRANSITIONS: dict[str, frozenset[str]] = { + TransferStatus.FILE_PENDING.value: frozenset({ + TransferStatus.FILE_READY.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + }), + TransferStatus.FILE_READY.value: frozenset({ + TransferStatus.PRECHECKING.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + }), + TransferStatus.PRECHECKING.value: frozenset({ + TransferStatus.READY_TO_EXECUTE.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.NOT_MATURED.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.READY_TO_EXECUTE.value: frozenset({ + TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检 + TransferStatus.EXECUTING.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.EXECUTING.value: frozenset({ + TransferStatus.SUCCESS.value, + TransferStatus.DUPLICATE_SUCCESS.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({ + TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt + TransferStatus.MANUALLY_CLOSED.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.NOT_MATURED.value: frozenset(), + TransferStatus.SUCCESS.value: frozenset(), + TransferStatus.DUPLICATE_SUCCESS.value: frozenset(), + TransferStatus.RESULT_UNKNOWN.value: frozenset(), + TransferStatus.MANUALLY_CLOSED.value: frozenset(), + TransferStatus.CANCELLED.value: frozenset(), + TransferStatus.NOTIFICATION_FAILED.value: frozenset(), +} + +# Run 级转换白名单。 +RUN_TRANSITIONS: dict[str, frozenset[str]] = { + TransferRunStatus.QUEUED.value: frozenset({ + TransferRunStatus.PREPARING_FILES.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.PREPARING_FILES.value: frozenset({ + TransferRunStatus.PRECHECKING.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.PRECHECKING.value: frozenset({ + TransferRunStatus.READY_TO_EXECUTE.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.READY_TO_EXECUTE.value: frozenset({ + TransferRunStatus.EXECUTING.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.EXECUTING.value: frozenset({ + TransferRunStatus.SUCCESS.value, + TransferRunStatus.PARTIAL_FAILED.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.SUCCESS.value: frozenset(), + TransferRunStatus.PARTIAL_FAILED.value: frozenset(), + TransferRunStatus.FAILED.value: frozenset(), + TransferRunStatus.CANCELLED.value: frozenset(), +} + + +class TransferStateError(AppError): + """非法状态转换领域错误。""" + + def __init__( + self, + message: str = "Invalid state transition", + *, + current: str | None = None, + target: str | None = None, + ): + details: dict[str, str] = {} + if current is not None: + details["current"] = current + if target is not None: + details["target"] = target + super().__init__( + code=INVALID_STATE_TRANSITION_CODE, + message=message, + http_status=409, + details=details, + ) + + +def assert_transition_allowed( + current: str, + target: str, + *, + transitions: Mapping[str, frozenset[str]] = ITEM_TRANSITIONS, +) -> None: + """服务端状态转换门禁。 + + Args: + current: 当前状态。 + target: 目标状态。 + transitions: 转换白名单(默认 Invoice 项表)。 + Raises: + TransferStateError: 当前状态未知或目标不在允许集合内。 + """ + current_value = str(current or "").strip() + target_value = str(target or "").strip() + allowed = transitions.get(current_value) + if allowed is None: + raise TransferStateError("unknown current status", current=current_value) + if target_value not in allowed: + raise TransferStateError( + "status transition not allowed", + current=current_value, + target=target_value, + ) + + +def apply_notification_failure(run_status: str) -> str: + """通知失败不改变 ERP 结果。 + + Args: + run_status: Run 的 ERP 业务终态。 + Returns: + 原 run_status(保持不变)。 + Raises: + TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。 + """ + status = str(run_status or "").strip() + if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}: + raise TransferStateError( + "notification failure only allowed after ERP terminal status", + current=status, + ) + return status diff --git a/backend/app/services/in_transit_transfer/strategy.py b/backend/app/services/in_transit_transfer/strategy.py new file mode 100644 index 00000000..6a3dcb43 --- /dev/null +++ b/backend/app/services/in_transit_transfer/strategy.py @@ -0,0 +1,61 @@ +"""在途调拨策略硬门禁。 + +用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试, + 强制默认 10 分钟确认有效期。 +依赖:app.core.errors.AppError、standard decimal。 +逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError, + 阻止发布/执行(fail-closed)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal + +from app.core.errors import AppError + +STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION" +DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟 + + +@dataclass(frozen=True) +class TransferStrategyPolicy: + """调拨策略冻结快照;三项禁令默认关闭。""" + + allow_partial: bool = False + quantity_tolerance: Decimal = Decimal("0") + allow_erp_auto_retry: bool = False + confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS + + +class StrategyViolationError(AppError): + """策略触碰一期禁令。""" + + def __init__(self, message: str, *, reason: str): + super().__init__( + code=STRATEGY_VIOLATION_CODE, + message=message, + http_status=409, + details={"reason": reason}, + ) + + +def validate_strategy(strategy: TransferStrategyPolicy) -> None: + """校验策略是否违反一期硬门禁。 + + Args: + strategy: 待校验策略。 + Raises: + StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。 + """ + if strategy.allow_partial: + raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial") + if strategy.quantity_tolerance != Decimal("0"): + raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance") + if strategy.allow_erp_auto_retry: + raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry") + + +def default_strategy() -> TransferStrategyPolicy: + """返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。""" + return TransferStrategyPolicy() diff --git a/backend/app/services/integration_connector/__init__.py b/backend/app/services/integration_connector/__init__.py new file mode 100644 index 00000000..7c704afc --- /dev/null +++ b/backend/app/services/integration_connector/__init__.py @@ -0,0 +1,7 @@ +"""services/integration_connector/__init__.py + +Integration Connector(外部系统连接器框架):能力契约、绑定解析、REST/SOAP 传输、 +声明式映射、凭据引用与调用引擎(CapabilityGateway)。 +""" + +from __future__ import annotations diff --git a/backend/app/services/integration_connector/binding.py b/backend/app/services/integration_connector/binding.py new file mode 100644 index 00000000..6bf2c80a --- /dev/null +++ b/backend/app/services/integration_connector/binding.py @@ -0,0 +1,124 @@ +"""services/integration_connector/binding.py + +用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到 + (客户端 + 接口 + 映射版本),并冻结调用期配置快照。 +依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。 +逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集; + 同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone + +from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.errors import BindingNotFoundError + + +@dataclass(frozen=True) +class BindingSnapshot: + """一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。""" + + capability: str + context_selector: dict + client_code: str + interface_code: str + connector_type: str + interface_version: int + mapping_version: int + credential_ref_code: str | None + config: dict + request_spec: dict + response_mapping: dict + output_schema: dict + + +def _to_naive(dt: datetime | None) -> datetime | None: + if dt is None: + return None + if dt.tzinfo is not None: + return dt.astimezone(timezone.utc).replace(tzinfo=None) + return dt + + +def _within_window(binding: IntegrationBinding, now: datetime) -> bool: + effective_from = _to_naive(binding.effective_from) + effective_to = _to_naive(binding.effective_to) + if effective_from is not None and now < effective_from: + return False + if effective_to is not None and now > effective_to: + return False + return True + + +def _is_subset(selector: dict, context: dict) -> bool: + """selector 的键值须全部存在于 context(空 selector 恒命中)。""" + return all(context.get(k) == v for k, v in selector.items()) + + +def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot: + """解析最佳绑定并冻结调用期快照。 + + Args: + capability: 能力名(如 in_transit_transfer.query_inventory)。 + context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。 + environment: 环境(prod/test/dev)。 + now: 可选时钟(测试注入);缺省用 utcnow。 + Returns: + BindingSnapshot。 + Raises: + BindingNotFoundError: 无可用绑定(fail-closed)。 + """ + base_now = now or datetime.utcnow() + rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all() + candidates: list[tuple[IntegrationBinding, dict]] = [] + for row in rows: + if not _within_window(row, base_now): + continue + selector = row.context_selector_json or {} + if not _is_subset(selector, context or {}): + continue + candidates.append((row, selector)) + if not candidates: + raise BindingNotFoundError(capability=capability) + candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True) + row, selector = candidates[0] + + client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first() + iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first() + if client is None or iface is None: + raise BindingNotFoundError(capability=capability) + + # 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。 + # 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。 + config = dict(client.config_json or {}) + if client.endpoint is not None: + config['endpoint'] = client.endpoint + if client.timeout_seconds is not None: + config['timeout_seconds'] = client.timeout_seconds + + request_spec = dict(iface.request_spec_json or {}) + if iface.http_method is not None: + request_spec['method'] = iface.http_method + if iface.request_path is not None: + request_spec['path'] = iface.request_path + + selector = dict(row.context_selector_json or {}) + if row.context_source_code is not None and 'source_code' not in selector: + selector['source_code'] = row.context_source_code + + return BindingSnapshot( + capability=row.capability, + context_selector=selector, + client_code=client.code, + interface_code=iface.code, + connector_type=client.connector_type, + interface_version=iface.version, + mapping_version=row.mapping_version, + credential_ref_code=client.credential_ref_code, + config=config, + request_spec=request_spec, + response_mapping=iface.response_mapping_json or {}, + output_schema=iface.output_schema_json or {}, + ) diff --git a/backend/app/services/integration_connector/capability.py b/backend/app/services/integration_connector/capability.py new file mode 100644 index 00000000..560ce700 --- /dev/null +++ b/backend/app/services/integration_connector/capability.py @@ -0,0 +1,125 @@ +"""services/integration_connector/capability.py + +用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。 +依赖:app.core.errors、errors.py;纯代码,不依赖 DB。 +逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app.core.errors import ValidationError +from app.services.integration_connector.errors import CapabilityNotFoundError + +# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。 +_QUERY_INPUT_SCHEMA: dict = { + "type": "object", + "required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"], + "properties": { + "invoice_no": {"type": "string"}, + "from_warehouse": {"type": "string"}, + "to_warehouse": {"type": "string"}, + "quantity": {"type": "number"}, + }, +} +_QUERY_OUTPUT_SCHEMA: dict = { + "type": "object", + "properties": { + "found": {"type": "boolean"}, + "quantity": {"type": ["number", "null"]}, + }, +} +_WRITE_OUTPUT_SCHEMA: dict = { + "type": "object", + "required": ["status"], + "properties": { + "status": { + "type": "string", + "enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"], + }, + "document_no": {"type": ["string", "null"]}, + "verified_posted": {"type": ["boolean", "null"]}, + }, +} + + +@dataclass(frozen=True) +class CapabilitySpec: + """强类型能力契约(由代码注册)。""" + + name: str + input_schema: dict + output_schema: dict + idempotency: str + write: bool + + +_CAPABILITIES: dict[str, CapabilitySpec] = {} +_LOADED = False + + +def register_capability(spec: CapabilitySpec) -> CapabilitySpec: + """注册能力;同名重复注册抛 ValidationError。""" + if spec.name in _CAPABILITIES: + raise ValidationError( + f"capability already registered: {spec.name}", + code="INTEGRATION.CAPABILITY_DUPLICATE", + details={"name": spec.name}, + ) + _CAPABILITIES[spec.name] = spec + return spec + + +def get_capability(name: str) -> CapabilitySpec: + """按名查询能力;未注册抛 CapabilityNotFoundError(fail-closed)。""" + spec = _CAPABILITIES.get(name) + if spec is None: + raise CapabilityNotFoundError(name=name) + return spec + + +def list_capabilities() -> list[CapabilitySpec]: + """返回全部已注册能力(按名排序)。""" + return sorted(_CAPABILITIES.values(), key=lambda s: s.name) + + +def ensure_capabilities_loaded() -> None: + """惰性注册内置能力(幂等);由网关/API 在解析前调用。""" + global _LOADED # noqa: PLW0603 + if _LOADED: + return + _LOADED = True + _register_transfer_capabilities() + + +def _register_transfer_capabilities() -> None: + """注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。""" + register_capability(CapabilitySpec( + name="in_transit_transfer.query_inventory", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_QUERY_OUTPUT_SCHEMA, + idempotency="none", + write=False, + )) + register_capability(CapabilitySpec( + name="in_transit_transfer.create_transfer", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_WRITE_OUTPUT_SCHEMA, + idempotency="invoice", + write=True, + )) + register_capability(CapabilitySpec( + name="in_transit_transfer.verify_duplicate", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_WRITE_OUTPUT_SCHEMA, + idempotency="invoice", + write=False, + )) + + +def reset_capability_registry_for_tests() -> None: + """单测隔离:清空注册表并重置加载标记。""" + global _LOADED # noqa: PLW0603 + _CAPABILITIES.clear() + _LOADED = False diff --git a/backend/app/services/integration_connector/engine.py b/backend/app/services/integration_connector/engine.py new file mode 100644 index 00000000..0701f370 --- /dev/null +++ b/backend/app/services/integration_connector/engine.py @@ -0,0 +1,153 @@ +"""services/integration_connector/engine.py + +用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。 +依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 +逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout; + 入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。 +""" + +from __future__ import annotations + +import time +import uuid +from dataclasses import replace + +from app import db +from app.services.integration_connector.binding import BindingSnapshot, resolve_binding +from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability +from app.services.integration_connector.errors import CallFailedError, InputInvalidError +from app.services.integration_connector.mapping import map_response, schema_errors +from app.services.integration_connector.security import sanitize +from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response +from app.models import IntegrationCall + + +def build_request(request_spec: dict, config: dict, params: dict) -> dict: + """按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。""" + request_spec = request_spec or {} + spec_path = str(request_spec.get('path') or '') + try: + path = spec_path.format(**params) + except (KeyError, IndexError, ValueError): + path = spec_path + headers = dict(config.get('headers') or {}) + spec_params = list(request_spec.get('params') or []) + selected = {k: params[k] for k in spec_params if k in params} or params + template = request_spec.get('template') + if isinstance(template, dict): + body = _fill_template(template, params) + else: + body = selected + return {'path': path, 'params': selected, 'body': body, 'headers': headers} + + +def _fill_template(template: dict, params: dict) -> dict: + """填充模板 dict 中的 {placeholder} 占位符。""" + filled: dict = {} + for key, value in template.items(): + if isinstance(value, str) and '{' in value: + try: + filled[key] = value.format(**params) + except (KeyError, IndexError, ValueError): + filled[key] = value + else: + filled[key] = value + return filled + + +def _environment() -> str: + """从 Flask 配置推导环境(dev/test/prod),缺省 prod。""" + try: + from flask import current_app, has_app_context + if has_app_context(): + value = str(current_app.config.get('ENV_NAME') or '').strip().lower() + if value in {'dev', 'test', 'prod'}: + return value + except Exception: + pass + return 'prod' + + +class CapabilityGateway: + """能力调用引擎;transports 为 {connector_type: Transport} 可注入。""" + + def __init__(self, transports: dict[str, Transport] | None = None) -> None: + self.transports = dict(transports or {}) + + def call( + self, + *, + capability: str, + context: dict, + params: dict, + operation_id: str, + idempotency_key: str | None = None, + environment: str | None = None, + transports: dict[str, Transport] | None = None, + ) -> IntegrationCallResult: + ensure_capabilities_loaded() + spec = get_capability(capability) + input_errors = schema_errors(params, spec.input_schema) + if input_errors: + raise InputInvalidError(details={'errors': input_errors}) + + env = environment or _environment() + snapshot = resolve_binding(capability, context, env) + transport = (transports or self.transports).get(snapshot.connector_type) + if transport is None: + raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'}) + + request = build_request(snapshot.request_spec, snapshot.config, params) + trace_id = f'ic-{uuid.uuid4().hex}' + start_ms = int(time.time() * 1000) + try: + raw = transport.call( + client={'config_json': snapshot.config, 'credential': {}}, + interface={'request_spec_json': snapshot.request_spec}, + request=request, + ) + except TimeoutError: + result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id) + _record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id) + return result + + result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success') + if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'): + data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema) + result = replace(result, data=data) + result = replace(result, trace_id=trace_id) + _record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id) + return result + + +def _record_call( + operation_id: str, + capability: str, + snapshot: BindingSnapshot, + params: dict, + raw: dict | None, + result: IntegrationCallResult, + start_ms: int, + trace_id: str, +) -> None: + """落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。""" + elapsed_ms = int(time.time() * 1000) - start_ms + call = IntegrationCall( + operation_id=operation_id, + capability=capability, + binding_snapshot_json={ + 'client_code': snapshot.client_code, + 'interface_code': snapshot.interface_code, + 'connector_type': snapshot.connector_type, + 'interface_version': snapshot.interface_version, + 'mapping_version': snapshot.mapping_version, + 'credential_ref_code': snapshot.credential_ref_code, + }, + request_summary_json=sanitize(params), + response_summary_json=sanitize(raw or {}), + status=result.status, + elapsed_ms=elapsed_ms, + trace_id=trace_id, + ) + db.session.add(call) + db.session.commit() diff --git a/backend/app/services/integration_connector/errors.py b/backend/app/services/integration_connector/errors.py new file mode 100644 index 00000000..d90e83f6 --- /dev/null +++ b/backend/app/services/integration_connector/errors.py @@ -0,0 +1,104 @@ +"""services/integration_connector/errors.py + +用途:Integration Connector 框架统一业务异常类(INTEGRATION.* 错误码)。 +依赖:app.core.errors.AppError。 +逻辑:fail-closed —— 缺绑定/缺凭据/映射不合法/契约未冻结均抛出,绝不猜测。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import AppError + +INTEGRATION_CAPABILITY_NOT_FOUND = "INTEGRATION.CAPABILITY_NOT_FOUND" +INTEGRATION_INPUT_INVALID = "INTEGRATION.INPUT_INVALID" +INTEGRATION_BINDING_NOT_FOUND = "INTEGRATION.BINDING_NOT_FOUND" +INTEGRATION_TRANSPORT_NOT_FROZEN = "INTEGRATION.TRANSPORT_NOT_FROZEN" +INTEGRATION_MAPPING_INVALID = "INTEGRATION.MAPPING_INVALID" +INTEGRATION_CREDENTIAL_UNRESOLVED = "INTEGRATION.CREDENTIAL_UNRESOLVED" +INTEGRATION_RESULT_UNKNOWN = "INTEGRATION.RESULT_UNKNOWN" +INTEGRATION_CALL_FAILED = "INTEGRATION.CALL_FAILED" + + +class CapabilityNotFoundError(AppError): + """能力未注册(fail-closed)。""" + + def __init__(self, message: str = "capability not registered", *, name: str | None = None): + details = {"name": name} if name else {} + super().__init__( + code=INTEGRATION_CAPABILITY_NOT_FOUND, message=message, http_status=404, details=details, + retryable=False, + ) + + +class InputInvalidError(AppError): + """入参不合能力输入 Schema。""" + + def __init__(self, message: str = "input invalid", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_INPUT_INVALID, message=message, http_status=400, details=details or {}, + retryable=False, + ) + + +class BindingNotFoundError(AppError): + """无可用绑定(fail-closed)。""" + + def __init__(self, message: str = "no binding for capability", *, capability: str | None = None): + details = {"capability": capability} if capability else {} + super().__init__( + code=INTEGRATION_BINDING_NOT_FOUND, message=message, http_status=503, details=details, + retryable=False, + ) + + +class TransportNotFrozenError(AppError): + """传输契约未冻结(缺 endpoint/wsdl)。""" + + def __init__(self, message: str = "transport not frozen"): + super().__init__( + code=INTEGRATION_TRANSPORT_NOT_FROZEN, message=message, http_status=503, retryable=False, + ) + + +class MappingInvalidError(AppError): + """映射结果不合输出 Schema(fail-closed)。""" + + def __init__(self, message: str = "mapping invalid", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_MAPPING_INVALID, message=message, http_status=503, details=details or {}, + retryable=False, + ) + + +class CredentialUnresolvedError(AppError): + """凭据无法解析(fail-closed)。""" + + def __init__(self, message: str = "credential unresolved", *, ref: str | None = None): + details = {"secret_ref": ref} if ref else {} + super().__init__( + code=INTEGRATION_CREDENTIAL_UNRESOLVED, message=message, http_status=503, details=details, + retryable=False, + ) + + +class ResultUnknownError(AppError): + """写结果无法确认;禁止自动重试。""" + + def __init__(self, message: str = "result unknown", *, operation_id: str | None = None): + details = {"operation_id": operation_id} if operation_id else {} + super().__init__( + code=INTEGRATION_RESULT_UNKNOWN, message=message, http_status=503, details=details, + retryable=False, + ) + + +class CallFailedError(AppError): + """调用技术失败(非业务失败)。""" + + def __init__(self, message: str = "call failed", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_CALL_FAILED, message=message, http_status=502, details=details or {}, + retryable=False, + ) diff --git a/backend/app/services/integration_connector/gateway.py b/backend/app/services/integration_connector/gateway.py new file mode 100644 index 00000000..3785c80d --- /dev/null +++ b/backend/app/services/integration_connector/gateway.py @@ -0,0 +1,27 @@ +"""services/integration_connector/gateway.py + +用途:模块级 CapabilityGateway 装配与测试注入点。 +依赖:engine.CapabilityGateway、transports.rest/soap。 +逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。 +""" + +from __future__ import annotations + +from app.services.integration_connector.engine import CapabilityGateway +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + +_override: CapabilityGateway | None = None + + +def set_capability_gateway(gateway: CapabilityGateway | None) -> None: + """测试注入点:设置/清除 CapabilityGateway 覆盖。""" + global _override # noqa: PLW0603 + _override = gateway + + +def get_capability_gateway() -> CapabilityGateway: + """返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。""" + if _override is not None: + return _override + return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()}) diff --git a/backend/app/services/integration_connector/mapping.py b/backend/app/services/integration_connector/mapping.py new file mode 100644 index 00000000..51973652 --- /dev/null +++ b/backend/app/services/integration_connector/mapping.py @@ -0,0 +1,210 @@ +"""services/integration_connector/mapping.py + +用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。 +依赖:decimal、errors.py;纯函数,无 IO/网络/DB。 +逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL; + 缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from app.services.integration_connector.errors import MappingInvalidError + +# 表达式安全边界:路径长度/深度上限(失败即 fail-closed)。 +MAX_PATH_LENGTH = 256 +MAX_DEPTH = 8 + +# 缺字段哨兵:与合法值 None 区分。 +MISSING = object() + + +def _tokenize(path: str) -> list[str]: + """把点路径 + 数组下标拆成 token 序列,如 a.b[0].c -> ['a','b','0','c']。""" + tokens: list[str] = [] + current = "" + i = 0 + n = len(path) + while i < n: + c = path[i] + if c == "[": + if current: + tokens.append(current) + current = "" + j = path.index("]", i) + tokens.append(path[i + 1:j]) + i = j + 1 + elif c == ".": + if current: + tokens.append(current) + current = "" + i += 1 + else: + current += c + i += 1 + if current: + tokens.append(current) + return tokens + + +def extract_path(obj: Any, path: str) -> Any: + """按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。""" + path = str(path or "") + if len(path) > MAX_PATH_LENGTH: + raise MappingInvalidError(details={"reason": "path_too_long"}) + tokens = _tokenize(path) + if len(tokens) > MAX_DEPTH: + raise MappingInvalidError(details={"reason": "path_too_deep"}) + cur = obj + for tok in tokens: + if isinstance(cur, list) and tok.isdigit(): + idx = int(tok) + if idx >= len(cur): + return MISSING + cur = cur[idx] + elif isinstance(cur, dict) and tok in cur: + cur = cur[tok] + else: + return MISSING + return cur + + +# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ---- + +def _default(value: Any, default: Any) -> Any: + return default if value is MISSING else value + + +def _fallback(value: Any, fallback: Any) -> Any: + return fallback if value is MISSING or value in (None, "") else value + + +def _decimal(value: Any) -> Any: + if value is MISSING: + return MISSING + return Decimal(str(value)) + + +def _cast(value: Any, to: str) -> Any: + if value is MISSING or value is None: + return MISSING + if to == "int": + return int(value) + if to == "float": + return float(value) + if to == "str": + return str(value) + if to == "bool": + return bool(value) + return value + + +def _enum_map(value: Any, mapping: dict[str, str]) -> Any: + if value is MISSING: + return MISSING + return mapping.get(str(value), value) + + +def _list_map(value: Any, mapping: dict[str, str]) -> list[Any]: + if value is MISSING: + return MISSING + return [mapping.get(str(item), item) for item in (value or [])] + + +def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any: + if value is MISSING: + return MISSING + return then if condition == "truthy" and bool(value) else else_ + + +TRANSFORMS: dict[str, Any] = { + "default": _default, + "fallback": _fallback, + "decimal": _decimal, + "cast": _cast, + "enum-map": _enum_map, + "list-map": _list_map, + "if-else": _if_else, +} + + +# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)---- + +def _matches_type(value: Any, type_spec: Any) -> bool: + if isinstance(type_spec, list): + return any(_matches_type(value, t) for t in type_spec) + if type_spec == "object": + return isinstance(value, dict) + if type_spec == "array": + return isinstance(value, (list, tuple)) + if type_spec == "string": + return isinstance(value, str) + if type_spec == "number": + return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool) + if type_spec == "integer": + return isinstance(value, int) and not isinstance(value, bool) + if type_spec == "boolean": + return isinstance(value, bool) + if type_spec == "null": + return value is None + return True + + +def _validate_against_schema(value: Any, schema: dict, path: str = "") -> list[tuple[str, str]]: + """返回不合规项 [(字段路径, 原因)];空列表表示合规。""" + if not isinstance(schema, dict): + return [] + errors: list[tuple[str, str]] = [] + if "enum" in schema and value not in schema["enum"]: + errors.append((path, f"not in enum: {value!r}")) + if "type" in schema and not _matches_type(value, schema["type"]): + errors.append((path, f"expected {schema['type']}, got {type(value).__name__}")) + if isinstance(value, dict): + for req in schema.get("required") or []: + if req not in value: + errors.append((f"{path}.{req}" if path else req, "required missing")) + for key, sub in (schema.get("properties") or {}).items(): + if key in value: + errors.extend(_validate_against_schema(value[key], sub, f"{path}.{key}" if path else key)) + elif isinstance(value, list) and "items" in schema: + for i, item in enumerate(value): + errors.extend(_validate_against_schema(item, schema["items"], f"{path}[{i}]")) + return errors + + +def schema_errors(value: Any, schema: dict) -> list[tuple[str, str]]: + """对 value 做最小 Schema 校验,返回不合规项 [(字段路径, 原因)];空列表表示合规。""" + return _validate_against_schema(value, schema or {}) + + +def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict: + """按 mapping 从 raw 提取并转换字段,组装 result 后经 output_schema 校验。 + + Raises: + MappingInvalidError: 未知转换函数 / 缺必需字段 / 类型或枚举不合。 + """ + mapping = mapping or {} + result: dict[str, Any] = {} + for field, spec in mapping.items(): + if not isinstance(spec, dict): + raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"}) + if "default" in spec: + value = spec["default"] + else: + expr = spec.get("expr") + value = extract_path(raw, expr) if expr is not None else MISSING + transform = spec.get("transform") + if transform: + fn = TRANSFORMS.get(transform) + if fn is None: + raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"}) + value = fn(value, **(spec.get("args") or {})) + if value is not MISSING: + result[field] = value + + errors = _validate_against_schema(result, output_schema or {}) + if errors: + raise MappingInvalidError(details={"errors": errors}) + return result diff --git a/backend/app/services/integration_connector/security.py b/backend/app/services/integration_connector/security.py new file mode 100644 index 00000000..865bc948 --- /dev/null +++ b/backend/app/services/integration_connector/security.py @@ -0,0 +1,83 @@ +"""services/integration_connector/security.py + +用途:凭据引用解析(fail-closed)与敏感字段脱敏。 +依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 +逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError; + sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import IntegrationCredentialReference +from app.services.integration_connector.errors import CredentialUnresolvedError + +DEFAULT_SENSITIVE_KEYS = frozenset({ + 'password', 'token', 'secret', 'authorization', 'cookie', 'access_key', + 'secret_key', 'credential', 'api_key', 'apikey', 'credentials', +}) + + +def resolve_credential(credential_ref_code: str) -> dict[str, Any]: + """按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。 + + Raises: + CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。 + """ + from flask import current_app + + cred = IntegrationCredentialReference.query.filter_by( + code=credential_ref_code, status='active', + ).first() + if cred is None: + raise CredentialUnresolvedError(ref=credential_ref_code) + secret_ref = cred.secret_ref + value = current_app.config.get(secret_ref) if has_app_ctx() else None + if value is None or value == '': + raise CredentialUnresolvedError(ref=secret_ref) + if isinstance(value, dict): + return dict(value) + return {'value': value} + + +def has_app_ctx() -> bool: + """当前是否处于 Flask app 上下文(无则返回 False)。""" + try: + from flask import has_app_context + return has_app_context() + except Exception: + return False + + +def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any: + """递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。 + + Args: + obj: 待脱敏对象(dict/list/标量)。 + sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。 + Returns: + 脱敏后的新对象(不修改入参)。 + """ + keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set()) + if isinstance(obj, dict): + return { + key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys)) + for key, value in obj.items() + } + if isinstance(obj, (list, tuple)): + return [sanitize(item, sensitive_keys) for item in obj] + return obj + + +def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]: + """只回凭据元数据,绝不含解析出的明文。""" + return { + 'code': cred.code, + 'secret_ref': cred.secret_ref, + 'secret_provider': cred.secret_provider, + 'credential_type': cred.credential_type, + 'version': cred.version, + 'status': cred.status, + 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, + } diff --git a/backend/app/services/integration_connector/transports/__init__.py b/backend/app/services/integration_connector/transports/__init__.py new file mode 100644 index 00000000..be8b4ce2 --- /dev/null +++ b/backend/app/services/integration_connector/transports/__init__.py @@ -0,0 +1,18 @@ +"""services/integration_connector/transports/__init__.py + +集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。 +""" + +from __future__ import annotations + +from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + +__all__ = [ + 'IntegrationCallResult', + 'Transport', + 'classify_transport_response', + 'RestTransport', + 'SoapTransport', +] diff --git a/backend/app/services/integration_connector/transports/base.py b/backend/app/services/integration_connector/transports/base.py new file mode 100644 index 00000000..17f6a680 --- /dev/null +++ b/backend/app/services/integration_connector/transports/base.py @@ -0,0 +1,73 @@ +"""services/integration_connector/transports/base.py + +用途:Transport 统一契约 + 结果分类(IntegrationCallResult)。 +依赖:typing.Protocol、dataclass;无 Flask/DB。 +逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为 + IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Protocol + +# 结果状态集(与在途调拨写入结果分类一致):success / duplicate_success / +# duplicate_unverified / business_failed / technical_failed / timeout / result_unknown +RESULT_STATUSES = ( + 'success', 'duplicate_success', 'duplicate_unverified', 'business_failed', + 'technical_failed', 'timeout', 'result_unknown', +) + + +@dataclass(frozen=True) +class IntegrationCallResult: + """一次调用归一后的结果对象。""" + + status: str + data: dict[str, Any] | None = None + error_code: str | None = None + error_message: str | None = None + document_no: str | None = None + trace_id: str | None = None + + +class Transport(Protocol): + """传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。""" + + connector_type: str + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + ... + + +def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult: + """按原始响应文本归一化结果分类(复用调拨六态分类语义)。 + + Args: + raw: 原始响应 dict,含 status/document_no/verified_posted/code/message。 + Returns: + IntegrationCallResult。 + """ + status = str(raw.get('status') or 'technical_failed') + document_no = raw.get('document_no') + if status == 'success': + return IntegrationCallResult(status='success', data=raw, document_no=document_no) + if status == 'duplicate_success': + posted = bool(raw.get('verified_posted')) + if posted: + return IntegrationCallResult(status='duplicate_success', data=raw, document_no=document_no) + return IntegrationCallResult( + status='duplicate_unverified', data=raw, document_no=document_no, + error_code='INTEGRATION_DUPLICATE_NOT_VERIFIED', + ) + if status == 'business_failed': + return IntegrationCallResult( + status='business_failed', data=raw, + error_code=str(raw.get('code') or 'ERP_BUSINESS_REJECT'), + error_message=str(raw.get('message') or ''), + ) + if status == 'timeout': + return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN') + if status == 'result_unknown': + return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no) + return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE') diff --git a/backend/app/services/integration_connector/transports/rest.py b/backend/app/services/integration_connector/transports/rest.py new file mode 100644 index 00000000..081ad309 --- /dev/null +++ b/backend/app/services/integration_connector/transports/rest.py @@ -0,0 +1,62 @@ +"""services/integration_connector/transports/rest.py + +用途:REST Transport——按 client 配置与 interface 请求规格构造 HTTP 请求并返回原始 dict。 +依赖:requests(默认注入),可注入 http_request 供测试替身。 +逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为 + business_failed dict;非 JSON 响应映射为 technical_failed。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +import requests + +from app.services.integration_connector.errors import TransportNotFrozenError + +HttpRequest = Callable[..., Any] + + +class RestTransport: + """REST 传输;http_request 可注入以便单元测试(默认 requests.request)。""" + + connector_type = 'rest' + + def __init__(self, http_request: HttpRequest | None = None) -> None: + self._http_request = http_request or requests.request + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + config = client.get('config_json') or {} + endpoint = str(config.get('endpoint') or '').strip() + if not endpoint: + raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)') + + spec = interface.get('request_spec_json') or {} + method = str(spec.get('method') or 'GET').upper() + path = str(spec.get('path') or '').strip() + url = endpoint.rstrip('/') + '/' + path.lstrip('/') + headers = {**(config.get('headers') or {}), **(request.get('headers') or {})} + timeout = int(config.get('timeout_seconds') or 60) + + response = self._http_request( + method, + url, + params=request.get('params'), + json=request.get('body'), + headers=headers, + timeout=timeout, + ) + if int(getattr(response, 'status_code', 0)) >= 400: + return { + 'status': 'business_failed', + 'code': f"HTTP_{int(response.status_code)}", + 'message': str(getattr(response, 'text', ''))[:500], + } + try: + return response.json() + except Exception: + return { + 'status': 'technical_failed', + 'code': 'NON_JSON', + 'message': str(getattr(response, 'text', ''))[:500], + } diff --git a/backend/app/services/integration_connector/transports/soap.py b/backend/app/services/integration_connector/transports/soap.py new file mode 100644 index 00000000..f945ff7f --- /dev/null +++ b/backend/app/services/integration_connector/transports/soap.py @@ -0,0 +1,29 @@ +"""services/integration_connector/transports/soap.py + +用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。 +依赖:zeep(延时导入);errors.py。 +逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.integration_connector.errors import TransportNotFrozenError + + +class SoapTransport: + """SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。""" + + connector_type = 'soap' + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + config = client.get('config_json') or {} + # SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。 + # 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。 + wsdl = str(config.get('endpoint') or '').strip() + if not wsdl: + raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)') + + # 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。 + raise NotImplementedError('SOAP implementation pending frozen WSDL') diff --git a/backend/app/services/schedule/freight_receipt_rpa_retention_job.py b/backend/app/services/schedule/freight_receipt_rpa_retention_job.py index c0a16d4f..4f0513c5 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_retention_job.py +++ b/backend/app/services/schedule/freight_receipt_rpa_retention_job.py @@ -40,7 +40,7 @@ def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int append_shipping_audit_event( event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', - unit_id=report_file.unit_run_id, result='failed', + unit_id=report_file.unit_run_id, result='failure', before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], ) diff --git a/backend/app/services/schedule/in_transit_receipt_file_job.py b/backend/app/services/schedule/in_transit_receipt_file_job.py new file mode 100644 index 00000000..48e17521 --- /dev/null +++ b/backend/app/services/schedule/in_transit_receipt_file_job.py @@ -0,0 +1,57 @@ +"""独立收料文件抓取排程(08:00)。 + +用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。 +依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。 +逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready +from app.services.schedule.job_registry import ScheduleExecuteResult + + +def _wanted_sources(task: ScheduleTask) -> list[str]: + """提取结构化 source_codes;留空代表全部启用来源。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + values = params.get("source_codes") or [] + if isinstance(values, str): + values = [values] + return [str(item).strip() for item in values if str(item).strip()] + + +def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """08:00 收料文件抓取;按来源实例独立执行。""" + deps = transfer_deps.get_transfer_dependencies() + sources = _wanted_sources(task) or [] + business_date = str(business_date_now()) + total = success = failed = empty = 0 + results: list[dict[str, Any]] = [] + warnings: list[str] = [] + errors: list[str] = [] + for source_code in sources: + total += 1 + try: + prepared = ensure_receipt_file_ready( + source_code=source_code, + business_date=business_date, + repository=deps.file_repository, + rpa_trigger=deps.rpa_trigger, + ) + results.append({"source_code": source_code, "stage": prepared.stage}) + if prepared.stage == "file_ready": + success += 1 + elif prepared.stage == "waiting_rpa_callback": + empty += 1 + else: + failed += 1 + errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}") + except Exception as exc: # noqa: BLE001 —— 来源隔离 + failed += 1 + errors.append(f"{source_code}: {exc}") + return (total, success, failed, empty, results, warnings, errors) diff --git a/backend/app/services/schedule/in_transit_transfer_job.py b/backend/app/services/schedule/in_transit_transfer_job.py new file mode 100644 index 00000000..460540c3 --- /dev/null +++ b/backend/app/services/schedule/in_transit_transfer_job.py @@ -0,0 +1,59 @@ +"""自动调拨排程(09:00)。 + +用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。 +依赖:auto_transfer、transfer deps、ScheduleExecuteResult。 +逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.auto_transfer import run_auto_transfer +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.schedule.job_registry import ScheduleExecuteResult + + +def _task_params(task: ScheduleTask) -> dict[str, Any]: + return task.job_params if isinstance(task.job_params, dict) else {} + + +def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """09:00 自动调拨:恢复 + 预检 + 执行 + 通知。""" + params = _task_params(task) + source_codes = params.get("source_codes") or [] + if isinstance(source_codes, str): + source_codes = [source_codes] + recover_history = bool(params.get("recover_history", True)) + recipients = params.get("notify_user_ids") or [] + + deps = transfer_deps.get_transfer_dependencies() + outcome = run_auto_transfer( + business_date=str(business_date_now()), + deps=deps, + source_codes=[str(item).strip() for item in source_codes], + recover_history=recover_history, + sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果) + recipients=[str(item) for item in recipients], + ) + results: list[dict[str, Any]] = [] + errors: list[str] = list(outcome.errors) + if outcome.run_no: + results.append({ + "run_no": outcome.run_no, + "status": outcome.run_status, + "notification_status": outcome.notification_status, + }) + recovery = outcome.recovery + success = 1 if outcome.run_status in {"success", "partial_failed"} else 0 + return ( + success + recovery.recovered_count, + success, + recovery.still_blocked_count, + 0, + results, + [f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"], + errors, + ) diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index a4d06fa9..93923f12 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -144,7 +144,7 @@ def _register_builtin_platform_jobs() -> None: run_contract_payment_alert_schedule, run_contract_payment_sync_schedule, ) - from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES + from app.services.voucher_check.config import DEFAULT_JOB_PARAMS from app.services.schedule.contract_payment_job import ( run_contract_payment_alert_schedule, run_contract_payment_sync_schedule, @@ -183,6 +183,8 @@ def _register_builtin_platform_jobs() -> None: description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。", category="procurement", )) + from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule + from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule register_platform_job(PlatformJobDefinition( key="shipping-order-extraction-progress-cleanup", @@ -342,7 +344,7 @@ def _register_builtin_platform_jobs() -> None: label="立账凭证检核", label_key="admin.schedule.form.platformJobAccountingVoucherCheck", handler=run_voucher_check_schedule, - description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。", + description="每周二检核上一个自然月的销售开票附件,扫描文档库类型目录并按 invoice 归档。", description_key="admin.schedule.form.accountingVoucherCheckHint", category="finance", params_schema=( @@ -356,30 +358,12 @@ def _register_builtin_platform_jobs() -> None: "options": [{"value": "HXJM", "label": "HXJM"}], }, { - "key": "directory_template", + "key": "profile_code", "type": "text", - "label": "目录模板", - "label_key": "admin.schedule.form.voucherCheckDirTemplate", + "label": "业务方 Profile", + "label_key": "admin.schedule.form.voucherCheckProfile", "required": True, - "default": "{root}/{YYYY}/{MM}/{invoice_no}", - "help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}", - "help_key": "admin.schedule.form.voucherCheckDirTemplateHelp", - }, - { - "key": "required_files", - "type": "json", - "label": "必检材料", - "label_key": "admin.schedule.form.voucherCheckRequiredFiles", - "required": True, - "default": DEFAULT_REQUIRED_FILES, - }, - { - "key": "filename_case_sensitive", - "type": "boolean", - "label": "文件名区分大小写", - "label_key": "admin.schedule.form.voucherCheckCaseSensitive", - "required": True, - "default": True, + "default": "sales", }, { "key": "notify_missing_enabled", @@ -397,16 +381,69 @@ def _register_builtin_platform_jobs() -> None: "required": False, "default": True, }, + ), + defaults=dict(DEFAULT_JOB_PARAMS), + )) + register_platform_job(PlatformJobDefinition( + key="in-transit-receipt-file", + label="在途收料文件抓取", + handler=run_in_transit_receipt_file_schedule, + description=( + "每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。" + "09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。" + ), + category="platform", + params_schema=( { - "key": "same_day_dedup_enabled", + "key": "source_codes", + "type": "multi_select", + "label": "来源实例", + "label_key": "admin.schedule.form.transferSourceCodes", + "required": False, + "default": [], + "options_source": "shipping_inventory_sources", + }, + ), + defaults={"source_codes": []}, + )) + register_platform_job(PlatformJobDefinition( + key="in-transit-transfer", + label="在途自动调拨", + handler=run_in_transit_transfer_schedule, + description=( + "每日 09:00 自动处理新增可调拨项与历史可恢复异常;" + "每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。" + ), + category="platform", + params_schema=( + { + "key": "source_codes", + "type": "multi_select", + "label": "来源实例", + "label_key": "admin.schedule.form.transferSourceCodes", + "required": False, + "default": [], + "options_source": "shipping_inventory_sources", + }, + { + "key": "recover_history", "type": "boolean", - "label": "同票同日去重", - "label_key": "admin.schedule.form.voucherCheckSameDayDedup", + "label": "历史可恢复异常复核", + "label_key": "admin.schedule.form.transferRecoverHistory", "required": False, "default": True, }, + { + "key": "notify_user_ids", + "type": "multi_select", + "label": "通知人", + "label_key": "admin.schedule.form.transferNotifyUsers", + "required": False, + "default": [], + "options_source": "users", + }, ), - defaults=dict(DEFAULT_JOB_PARAMS), + defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []}, )) diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index 43f58fe1..ac008c0e 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -4,11 +4,14 @@ backend/app/services/schedule/queue_service.py 用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。 依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。 逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。 + domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入 + business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。 """ from __future__ import annotations from datetime import datetime +from typing import Any from flask import current_app @@ -28,6 +31,86 @@ from app.services.schedule.freight_receipt_rpa_finalize import ( from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive _worker_initialized = False +_BUSINESS_REF_SLUG_MAX = 80 + + +def _schedule_job_slug(task: ScheduleTask) -> str: + """ + 从排程任务生成写入 jobs.business_ref 的业务短码。 + + 核心逻辑:优先 platform_api_path(如 accounting-voucher-check);无 path 时用 untagged。 + 冒号替换为连字符,避免破坏 `schedule_run:{id}:{slug}` 三段格式。 + + Args: + task: 排程任务。 + + Returns: + 最长 80 字符的 slug。 + """ + from app.services.schedule import normalize_platform_api_path + + slug = normalize_platform_api_path(getattr(task, "platform_api_path", None)) or "untagged" + slug = slug.replace(":", "-").replace("/", "-") + return slug[:_BUSINESS_REF_SLUG_MAX] + + +def _schedule_task_label(task: ScheduleTask) -> str: + """ + jobs.message 与 worker 日志用的任务显示名。 + + 核心逻辑:优先中文 name(如「立账凭证检核」);否则回落到 platform_api_path。 + + Args: + task: 排程任务。 + + Returns: + 非空显示名。 + """ + name = str(getattr(task, "name", None) or "").strip() + if name: + return name + slug = _schedule_job_slug(task) + return slug if slug != "untagged" else "未命名排程" + + +def schedule_job_business_ref(run_id: int, task: ScheduleTask) -> str: + """ + 生成 schedule Job 的 business_ref。 + + 格式:`schedule_run:{run_id}:{platform_api_path}`,便于在 jobs 表区分立账凭证检核等任务。 + 仍保留 run_id,取消/回收可按前缀精确匹配,避免 `schedule_run:1` 误伤 `schedule_run:13`。 + + Args: + run_id: ScheduleRun 主键。 + task: 排程任务。 + + Returns: + 长度不超过 128 的 business_ref。 + """ + return f"schedule_run:{int(run_id)}:{_schedule_job_slug(task)}" + + +def query_jobs_for_schedule_run(run_id: int): + """ + 按 ScheduleRun 主键查找对应通用 Job。 + + 核心逻辑:兼容旧格式 `schedule_run:{id}` 与新格式 `schedule_run:{id}:{path}`。 + 新格式必须带 `id` 后的冒号,避免 run_id=1 匹配到 10/11/13。 + + Args: + run_id: ScheduleRun 主键。 + + Returns: + 已过滤 domain/job_type/business_ref 的 Query;调用方可继续按 status 收窄。 + """ + run_id = int(run_id) + legacy = f"schedule_run:{run_id}" + prefix = f"schedule_run:{run_id}:" + return db.session.query(Job).filter( + Job.domain == "schedule", + Job.job_type == JobType.SCHEDULE_RUN.value, + db.or_(Job.business_ref == legacy, Job.business_ref.startswith(prefix)), + ) def _active_run(task_id: int) -> ScheduleRun | None: @@ -61,14 +144,19 @@ def _create_queued_run( *, trigger_type: str, triggered_by_user_id: int | None, + api_request_json: dict[str, Any] | None = None, ) -> tuple[ScheduleRun, int]: """ 在当前事务创建 ScheduleRun 与对应通用 Job。 + 核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run; + 业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。 + Args: task: 已由调用方锁定的排程任务。 trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。 triggered_by_user_id: 手动触发用户 ID;Cron 为 None。 + api_request_json: 可选运行参数(如立账凭证 `run_options.mode=force_all`),须在入队前写入以免 worker 抢跑。 Returns: `(ScheduleRun, job_id)`;调用方负责提交事务。 @@ -86,22 +174,29 @@ def _create_queued_run( triggered_by_user_id=triggered_by_user_id, started_at=None, status="queued", + api_request_json=api_request_json, ) db.session.add(run) db.session.flush() + task_label = _schedule_task_label(task) + platform_path = str(getattr(task, "platform_api_path", None) or "").strip() job_id = enqueue( JobType.SCHEDULE_RUN, { "schedule_task_id": task.id, "schedule_run_id": run.id, + "schedule_no": task.schedule_no, + "run_no": run.run_no, + "task_name": task_label, + "platform_api_path": platform_path, "trigger_type": normalized_trigger, "triggered_by_user_id": triggered_by_user_id, }, domain="schedule", - business_ref=f"schedule_run:{run.id}", + business_ref=schedule_job_business_ref(run.id, task), created_by_id=triggered_by_user_id, max_attempts=3, - message="排程等待后台执行", + message=f"{task_label}等待后台执行", dedupe_active=False, commit=False, ) @@ -112,6 +207,7 @@ def enqueue_manual_schedule_run( task_id: int, *, triggered_by_user_id: int | None, + api_request_json: dict[str, Any] | None = None, ) -> tuple[ScheduleRun, int, bool]: """ 手动触发排程并写入 schedule 队列。 @@ -119,6 +215,11 @@ def enqueue_manual_schedule_run( 核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回, 否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。 + Args: + task_id: 排程任务主键。 + triggered_by_user_id: 触发人;系统触发可为空。 + api_request_json: 写入新 run 的请求快照;已有活动 run 时不会覆盖。 + Returns: `(run, job_id, created)`;created=False 表示已有活动 run。 """ @@ -135,13 +236,8 @@ def enqueue_manual_schedule_run( active = _active_run(task.id) if active is not None: job = ( - db.session.query(Job) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.status.in_(("queued", "running")), - Job.business_ref == f"schedule_run:{active.id}", - ) + query_jobs_for_schedule_run(active.id) + .filter(Job.status.in_(("queued", "running"))) .order_by(Job.id.asc()) .first() ) @@ -151,6 +247,7 @@ def enqueue_manual_schedule_run( task, trigger_type="manual", triggered_by_user_id=triggered_by_user_id, + api_request_json=api_request_json, ) db.session.commit() return run, job_id, True @@ -242,13 +339,9 @@ def prepare_schedule_queue() -> int: if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run): continue active_job = ( - db.session.query(Job.id) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.business_ref == f"schedule_run:{run.id}", - Job.status.in_(("queued", "running")), - ) + query_jobs_for_schedule_run(run.id) + .filter(Job.status.in_(("queued", "running"))) + .with_entities(Job.id) .first() ) if active_job is None: @@ -308,11 +401,13 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N if task is None: finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除") return None + task_label = _schedule_task_label(task) + platform_path = str(getattr(task, "platform_api_path", None) or "").strip() or "untagged" if run.status in {"success", "failed", "partial_failed"}: finish_job( job_id, - result={"schedule_run_id": run.id, "status": run.status}, - message="排程已处于终态", + result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path}, + message=f"{task_label}已处于终态", ) return run @@ -323,6 +418,14 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N run.started_at = run.started_at or datetime.utcnow() run.error_message = None db.session.commit() + logger.info( + "[schedule-run] start name=%s path=%s run_no=%s run_id=%s job_id=%s", + task_label, + platform_path, + run.run_no, + run.id, + job_id, + ) result_run = run_task_now( task, trigger_type=run.trigger_type, @@ -331,8 +434,12 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N ) finish_job( job_id, - result={"schedule_run_id": result_run.id, "status": result_run.status}, - message="排程执行完成", + result={ + "schedule_run_id": result_run.id, + "status": result_run.status, + "platform_api_path": platform_path, + }, + message=f"{task_label}执行完成", ) return result_run except Exception as exc: @@ -355,5 +462,11 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N retryable=True, owned_attempt=owned_attempt, ) - logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id) + logger.exception( + "[schedule-run] failed name=%s path=%s run_id=%s job_id=%s", + task_label, + platform_path, + run_id, + job_id, + ) return run diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 44cfb59b..8ceab5b4 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -5,7 +5,8 @@ backend/app/services/schedule/scheduler_service.py 依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。 逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task; job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path - 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler。 + 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler; + handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。 """ from __future__ import annotations @@ -43,20 +44,16 @@ def request_cancel_run(run_id: int) -> None: 持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。 核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过 - ScheduleRun 状态/存在性复检停止可中断的长循环。 + ScheduleRun 状态/存在性复检停止可中断的长循环。business_ref 兼容 + `schedule_run:{id}` 与 `schedule_run:{id}:{platform_api_path}`。 """ - from app.jobs.types import JobType from app.models import Job + from app.services.schedule.queue_service import query_jobs_for_schedule_run now = datetime.utcnow() jobs = ( - db.session.query(Job) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.business_ref == f"schedule_run:{int(run_id)}", - Job.status.in_(("queued", "running")), - ) + query_jobs_for_schedule_run(run_id) + .filter(Job.status.in_(("queued", "running"))) .all() ) for job in jobs: @@ -493,6 +490,12 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun: + """ + 立即执行一条排程并写入 ScheduleRun 终态。 + + 核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success; + 该路径原先只写库不打日志,worker 汇总行看不到失败原因。 + """ recover_stale_awaiting_rpa_schedule_runs(task) recover_stale_receipt_rpa_schedule_runs(task) @@ -527,8 +530,16 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: executor = resolve_schedule_executor(task) total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run) except Exception as exc: - total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)] + total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 1, 0, [], [str(exc)] step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}] + if current_app: + current_app.logger.exception( + "[schedule-run] executor failed name=%s path=%s run_no=%s error=%s", + task.name, + task.platform_api_path, + run.run_no, + exc, + ) try: db.session.refresh(run) @@ -563,9 +574,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: duration_ms = int((time.time() - start_ts) * 1000) if current_app: + error_preview = "; ".join(str(item) for item in (errors or [])[:3]) current_app.logger.info( - "[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d", - run.run_no, total_count, success_count, failed_count, skipped_count, len(errors), + "[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d error=%s", + task.name, + task.platform_api_path, + run.run_no, + total_count, + success_count, + failed_count, + skipped_count, + len(errors or []), + error_preview or "-", ) if total_count == 0 and not errors: status = "success" diff --git a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py index eb24344d..37dfb9a0 100644 --- a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py +++ b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py @@ -2,7 +2,7 @@ services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py 用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。 -依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。 +依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_snapshot_line_ids。 逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op; 仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。 """ @@ -18,7 +18,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import ( ) from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( - list_eligible_post_ot_line_keys, + list_eligible_post_ot_snapshot_line_ids, ) ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] @@ -63,7 +63,7 @@ def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]: if scanned >= safe_limit: break scanned += 1 - eligible = list_eligible_post_ot_line_keys(case) + eligible = list_eligible_post_ot_snapshot_line_ids(case) if not eligible: skipped += 1 continue diff --git a/backend/app/services/schedule/voucher_check_job.py b/backend/app/services/schedule/voucher_check_job.py index 758f1be5..1b7a289a 100644 --- a/backend/app/services/schedule/voucher_check_job.py +++ b/backend/app/services/schedule/voucher_check_job.py @@ -38,7 +38,7 @@ def _ensure_headers() -> None: def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ 执行立账凭证检核排程。 - 核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。 + 核心逻辑:注册 Excel 表头后委托 runner;周批默认 incremental。 """ _ensure_headers() return run_voucher_check_batch(task, run) diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index f66dfd61..c1ff5278 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -2,9 +2,11 @@ services/shipping_notice/auto_progress_controller.py 用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。 -依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。 +依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务; + process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。 逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job - 在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 + 在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll, + 强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 """ from __future__ import annotations @@ -18,18 +20,18 @@ from flask import current_app from app import db from app.jobs.queue import enqueue from app.jobs.types import JobType -from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt +from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate from app.services.shipping_notice.tool_common import log_task_event _ACTIVE_JOB_STATUSES = ('queued', 'running') -_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'}) +_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled'}) def audit_legacy_forwarded_entrypoint( - *, task: ShippingNotice, action_code: str, actor_id: int | None = None, + *, task: ShippingOrderTask, action_code: str, actor_id: int | None = None, request_id: str | None = None, ) -> None: """记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。""" @@ -51,9 +53,9 @@ def _utc_now() -> datetime: return datetime.utcnow() -def _task_is_cancelled(task: ShippingNotice) -> bool: +def _task_is_cancelled(task: ShippingOrderTask) -> bool: """根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。""" - return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES + return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES or str(getattr(task, 'status', '') or '').strip().lower() == 'cancelled' def _recover_stale_active_job(job: Job) -> bool: @@ -90,6 +92,17 @@ def _recover_stale_active_job(job: Job) -> bool: gate.status = 'blocked_manual' gate.blocking_reason_code = 'technical_failure_present' gate.updated_at = now + # [FIX] 同一事务内重算 Execution 指针并回写 OT.stage,避免 Gate 已被判为 + # blocked_manual 而 execution.status / OT.stage 仍停在上一机械阶段(如 automating)。 + execution_id = getattr(gate, 'execution_id', None) + execution = ( + db.session.get(ShippingProcessExecution, int(execution_id)) + if execution_id is not None else None + ) + if execution is not None: + from app.services.shipping_notice.process_gate_service import _refresh_execution_pointers + + _refresh_execution_pointers(execution) db.session.flush() return True @@ -111,7 +124,7 @@ def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool: def determine_formal_start_gate( - task: ShippingNotice, + task: ShippingOrderTask, *, candidate_set: Any | None = None, ) -> str: @@ -126,7 +139,8 @@ def determine_formal_start_gate( return 'order_freeze_readiness' # 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史 # Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。 - customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower() + from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts + customer_status = str((customer_confirmation_facts(task) or {}).get('status') or '').strip().lower() if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}: return 'customer_resolution' # 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。 @@ -139,7 +153,7 @@ def determine_formal_start_gate( def _create_formal_execution_for_task( - task: ShippingNotice, + task: ShippingOrderTask, *, candidate_set_id: int | None, ) -> ShippingProcessExecution: @@ -178,7 +192,7 @@ def _supersede_duplicate_execution( ) -def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: +def _active_execution_for_task(task: ShippingOrderTask, *, candidate_set_id: int | None) -> ShippingProcessExecution: """ 锁定并取得当前唯一活动 Execution。 @@ -235,7 +249,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id) -def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None: +def supersede_auto_progress_for_candidate_refreeze(task: ShippingOrderTask) -> None: """ 在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。 @@ -309,9 +323,37 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi return None, None +def _auto_retry_blocked( + trigger: str | None, + has_failed_worker_attempt: bool, + resume_gate_code: str | None = None, +) -> bool: + """[禁止自动重试] 裁决:已存在失败 Worker Attempt 时是否拒绝再入队。 + + 核心逻辑:防止自动/后台 trigger 在外部依赖持续故障时无人值守空转重试; + 但用户显式重试(user_retry / user_manual)或带 resume_gate_code 的显式定向推进 + (如匹配工具调 run_task_auto_progress,其 trigger 为 tool_api_match_inventory_line + 而非 user_retry)应放行,否则点"重新匹配库存"会因 has_failed_worker_attempt + 被误拦、报"自动推进已无待处理 Gate"。 + + Args: + trigger: 触发类型(auto / user_retry / user_manual / worker_takeover / ...)。 + has_failed_worker_attempt: 当前 Gate 是否已有带 job_id 的失败 Attempt。 + resume_gate_code: 显式定向推进的目标 Gate;有值即视为用户/工具主动恢复,不拦。 + + Returns: + True 表示应禁止自动再入队;False 表示放行。 + """ + user_initiated = str(trigger or '').strip() in {'user_retry', 'user_manual'} + explicit_resume = bool(str(resume_gate_code or '').strip()) + return bool(has_failed_worker_attempt) and not user_initiated and not explicit_resume + + def submit_auto_progress( - *, task: ShippingNotice, trigger: str, operator_id: int | None = None, + *, task: ShippingOrderTask, trigger: str, operator_id: int | None = None, resume_gate_code: str | None = None, commit: bool = True, + inventory_mode: str = 'auto', + line_scope_key: str | None = None, recovery_plan_id: int | None = None, recovery_attempt_id: int | None = None, resume_after_gate: str | None = None, @@ -319,14 +361,12 @@ def submit_auto_progress( """ 接收任何自动/用户触发并安全入队当前 Gate。 - 普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。 + 入口只接受 ShippingOrderTask;Execution 与 Gate 始终按 OT 任务身份推进。 """ - # ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN; - # PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。 locked_task = ( - ShippingNotice.query + ShippingOrderTask.query .filter_by(id=int(task.id)) - .with_for_update(of=ShippingNotice) + .with_for_update(of=ShippingOrderTask) .first() ) if locked_task is None: @@ -373,14 +413,23 @@ def submit_auto_progress( from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job from app.services.shipping_notice.process_gate_service import queue_gate_attempt - sync_fulfillment_gates_from_task( - execution=execution, - actor_type='system', - actor_id=operator_id, + explicit_inventory_retry = ( + str(inventory_mode or '').strip() == 'retry_rpa' + and str(resume_gate_code or '').strip() == 'inventory_preparation' ) - db.session.flush() + if not explicit_inventory_retry: + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=operator_id, + ) + db.session.flush() execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one() - current_gate = str(execution.current_gate_code or '').strip() or None + current_gate = ( + 'inventory_preparation' + if explicit_inventory_retry + else str(execution.current_gate_code or '').strip() or None + ) gate = ( ShippingProcessGate.query .filter_by(execution_id=int(execution.id), gate_code=current_gate) @@ -388,6 +437,53 @@ def submit_auto_progress( .first() if current_gate else None ) + if explicit_inventory_retry and gate is not None: + # [ROOT CAUSE] 显式 retry_rpa(含行级改源后重抓)必须覆盖残留的 + # poll_inventory_preparation / waiting_external。否则只会再入队只读 poll: + # poll 遇到失败 Preparation 会直接收口,既不建新 RPA Attempt 也不写 trigger。 + # passed / waiting_external / failed_terminal 一律放开为 blocked_retryable。 + from app.services.shipping_notice.process_gate_job_service import ( + cancel_inventory_external_wait_polls, + ) + + cancel_inventory_external_wait_polls( + gate_id=int(gate.id), + reason='显式库存重抓:终止外部等待轮询', + ) + # 活动 Attempt 不得被复用;否则 queue_gate_attempt 会因 BUSY 失败, + # 或 active_attempt 早退把「强制重抓」吞成「继续轮询」。 + for stale in ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .all() + ): + stale.status = 'failed' + stale.error_code = 'superseded_by_explicit_retry' + stale.error_summary = '被显式库存重抓取代' + stale.finished_at = _utc_now() + if stale.job_id: + stale_job = db.session.get(Job, int(stale.job_id)) + if stale_job is not None and str(stale_job.status or '') in _ACTIVE_JOB_STATUSES: + stale_job.status = 'cancelled' + stale_job.finished_at = _utc_now() + stale_job.message = '显式库存重抓:取消残留活动 Job' + gate.status = 'blocked_retryable' + gate.passed_at = None + gate.blocking_reason_code = 'inventory_rpa_retry_requested' + gate.next_action_code = 'retry_inventory_preparation' + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = _utc_now() + execution.current_gate_code = 'inventory_preparation' + # 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate + # 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。 + execution.responsible_party = 'worker' + execution.primary_next_action_code = 'retry_inventory_preparation' + execution.updated_at = _utc_now() + db.session.flush() active_attempt = ( ShippingProcessGateAttempt.query .filter( @@ -398,7 +494,7 @@ def submit_auto_progress( .first() if gate is not None else None ) - if active_attempt is not None and active_attempt.job_id: + if active_attempt is not None and active_attempt.job_id and not explicit_inventory_retry: if commit: db.session.commit() return { @@ -410,6 +506,22 @@ def submit_auto_progress( 'reused': True, } action_code = str(getattr(gate, 'next_action_code', '') or '').strip() + # [禁止自动重试] 门禁一旦存在“Worker 真实执行失败”的 Attempt(failed 且 job_id 非空), + # 本次自动投递即属重试:任何 trigger(回调/聊天/批处理)都不得再入队,重试必须由 + # 用户在当前 Gate 显式发起;否则外部依赖持续故障时,回调/轮询会形成无人值守的 + # “失败→重试→再失败”空转环。仅存量内联投影 Attempt(job_id 为空)或无 Attempt + # 的首次投递不受影响,编排初始触发保持不变。 + has_failed_worker_attempt = ( + gate is not None + and db.session.query(ShippingProcessGateAttempt.id) + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status == 'failed', + ShippingProcessGateAttempt.job_id.isnot(None), + ) + .first() + is not None + ) # 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的 # system/worker Gate 才可自动创建 Attempt 并入队。 # 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。 @@ -418,6 +530,7 @@ def submit_auto_progress( if ( gate is not None and action_code + and not _auto_retry_blocked(trigger, has_failed_worker_attempt, resume_gate_code) and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code) and not is_navigation_action(action_code) and is_technical_gate_party(execution.responsible_party) @@ -439,6 +552,8 @@ def submit_auto_progress( 'candidate_set_id': candidate_set_id, 'fencing_token': uuid.uuid4().hex, 'trigger': trigger, + 'inventory_mode': inventory_mode, + 'line_scope_key': line_scope_key, 'recovery_plan_id': recovery_plan_id, 'recovery_attempt_id': recovery_attempt_id, 'resume_after_gate': resume_after_gate, diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py index e5c25563..c2ca49e0 100644 --- a/backend/app/services/shipping_notice/batch_create_idempotency.py +++ b/backend/app/services/shipping_notice/batch_create_idempotency.py @@ -3,7 +3,7 @@ services/shipping_notice/batch_create_idempotency.py 用途:发货通知跨请求文件内容重复校验。 依赖:models.ShippingNotice。 -逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 +逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingUploadAttempt.idempotency_key(货代上传幂等)语义分离。 """ from __future__ import annotations @@ -83,10 +83,17 @@ def assert_no_exact_duplicate_notices( return for content_hash, _filename in hashes: - query = ShippingNotice.query.filter( - ShippingNotice.user_id == user_id, - ShippingNotice.source_content_hash == content_hash, - ShippingNotice.lifecycle_status == 'active', + from app.models import ShippingOrderTask, ShippingOrderIntake, FileAsset + query = ( + ShippingNotice.query + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id) + .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) + .filter( + ShippingOrderTask.user_id == user_id, + FileAsset.content_hash == content_hash, + ShippingOrderTask.lifecycle_status == 'active', + ) ) if skipped_ids: query = query.filter(ShippingNotice.id.notin_(list(skipped_ids))) diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index 0bba968a..ae577d7a 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -14,7 +14,9 @@ from typing import Any from flask import current_app from app import db +from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import PH_RPA_PENDING +from app.services.shipping_notice.process_gate_projection import task_blocking_reason from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job from app.services.shipping_notice.query_service import get_task_by_ref from app.services.shipping_notice.tool_common import ( @@ -55,22 +57,25 @@ def _unmark_running(bucket: set[str], key: str) -> None: def _should_orchestrate_task(task: Any) -> bool: from app.services.shipping_notice.task_disposition_service import task_is_active + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task if not task_is_active(task): return False - pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() - if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}: + pending_reason = str(task_blocking_reason(task) or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt + if has_verified_upload_success(task): return False if getattr(task, "review_status", None): return False if ( - not getattr(task, "inventory_lines_json", None) + not has_ready_inventory_file_for_task(task) and pending_reason in {"", PH_RPA_PENDING} ): return True - if getattr(task, "pending_human_reason", None): + if task_blocking_reason(task): return False - if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}: + latest_attempt = latest_upload_attempt(task) if hasattr(task, 'id') else None + if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {"pending", "running", "failed", "unknown", "timed_out"}: return False return True @@ -95,6 +100,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: return {"status": "skipped", "message": "task already running"} try: + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + task = get_task_by_ref(normalized_task_no) if not task: return {"status": "missing", "message": "task not found"} @@ -102,30 +109,38 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: return { "status": "skipped", "message": ( - f"skip stage={getattr(task, 'current_step', '') or ''}" - f" pending_human_reason={task.pending_human_reason or ''}" - f" review_status={task.review_status or ''}" + f"skip stage={getattr(task, 'stage', '') or ''}" + f" pending_human_reason={task_blocking_reason(task) or ''}" + f" review_status={getattr(task, 'review_status', '') or ''}" ), } log_task_event( task, "backend_orchestrator_task_started", - {"current_step": task.current_step, "lifecycle_status": task.lifecycle_status}, + {"stage": task.stage, "lifecycle_status": task.lifecycle_status}, ) db.session.commit() payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id} - pending_reason = str(task.pending_human_reason or "").strip().lower() + pending_reason = str(task_blocking_reason(task) or '').strip().lower() if ( - not getattr(task, "inventory_lines_json", None) + not has_ready_inventory_file_for_task(task) and pending_reason == PH_RPA_PENDING ): - # Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询 - # PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。 - from app.services.shipping_notice.progress_workflow import run_task_auto_progress + # [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落 + # rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。 + from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait - result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') + recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator') + if recheck is not None: + result = recheck + else: + # Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询 + # PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') if current_app: current_app.logger.info( "[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s", @@ -134,7 +149,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: str(result.get("message") or "")[:300], ) elif ( - not getattr(task, "inventory_lines_json", None) + not has_ready_inventory_file_for_task(task) and pending_reason == "" ): payload["mode"] = "auto" @@ -166,7 +181,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: "[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s", task.task_no, result.get("status"), - task.current_step, + task.stage, str(result.get("message") or "")[:300], ) @@ -178,7 +193,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: { "result_status": str(result.get("status") or ""), "lifecycle_status": refreshed.lifecycle_status, - "current_step": refreshed.current_step, + "stage": refreshed.stage, }, ) db.session.commit() @@ -190,7 +205,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: db.session.rollback() task = get_task_by_ref(normalized_task_no) if task: - task.error_message = str(exc) + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + if hasattr(owner, 'error_message'): + owner.error_message = str(exc) log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]}) db.session.commit() return {"status": "failed", "message": str(exc)[:500] or "background task failed"} diff --git a/backend/app/services/shipping_notice/business_numbering_service.py b/backend/app/services/shipping_notice/business_numbering_service.py index 847b2636..0b0a0fb7 100644 --- a/backend/app/services/shipping_notice/business_numbering_service.py +++ b/backend/app/services/shipping_notice/business_numbering_service.py @@ -15,7 +15,7 @@ from sqlalchemy import update from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice +from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE BUSINESS_TYPE = "shipping_notice" @@ -121,13 +121,19 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int: return int(value) -def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str: +def assign_notice_business_number( + notice: ShippingNotice, + *, + moment: datetime | None = None, + customer_id_override: int | None = None, +) -> str: """ 为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。 Args: notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。 moment: 可选时刻,测试时用于固定上海业务日期。 + customer_id_override: 纠错替代单使用的新客户;仅用于编号,不修改原 OT 的历史匹配事实。 Returns: 分配或已存在的 business_no。 @@ -137,12 +143,18 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | """ if notice.business_no: return str(notice.business_no) - if notice.customer_id is None: + owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + resolution = customer_resolution_facts(owner) if owner is not None else {'customer_id': None} + customer_id = int(customer_id_override) if customer_id_override is not None else ( + int(resolution['customer_id']) if resolution['customer_id'] is not None else None + ) + if customer_id is None: raise ConflictError( 'Shipping notice customer must be confirmed before numbering', code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED', ) - customer = db.session.get(ShippingCustomer, int(notice.customer_id)) + customer = db.session.get(ShippingCustomer, customer_id) if customer is None or customer.status != 'active': raise ConflictError( 'Active customer is required before numbering', @@ -160,7 +172,5 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | notice.business_date = business_date notice.business_sequence_value = sequence_value notice.business_numbering_rule_version = NUMBERING_RULE_VERSION - notice.customer_name_snapshot = customer.standard_name - notice.customer_short_code_snapshot = short_code db.session.flush() return str(notice.business_no) diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index aa8b8e0b..47adf96e 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -27,7 +27,6 @@ from app.models import ( ShippingOrderCandidate, ShippingOrderCandidateQualification, ShippingOrderExtraction, - ShippingOrderCustomerMatch, ) from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_EVALUATOR_VERSION, @@ -71,7 +70,6 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85' # 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。 # 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。 _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) -_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'}) _EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) @@ -79,9 +77,8 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> """按冻结字段配置判断证据缺失是否只是可选字段诊断。 核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有 - ``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法 - 追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知 - 字段继续 fail-closed。 + ``required`` 或 ``auto_create_key_field`` 才能阻断。无法追溯 Schema + 时继续 fail-closed;系统项次由写路径生成,不构成证据缺失例外。 """ reason = str(item.get('reason') or item.get('code') or '').strip() if reason not in _EVIDENCE_GAP_REASONS: @@ -111,7 +108,7 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> config = None if config is not None: return not bool(config.get('required')) and not bool(config.get('auto_create_key_field')) - return field_code in _OPTIONAL_INTERNAL_FIELD_CODES + return False def blocking_candidate_conflicts(candidate: Any) -> list[Any]: @@ -173,8 +170,7 @@ def resolve_candidate_customer_resolved( """ 判定 Candidate/Extraction 的 Bill-to 客户是否已确认。 - 核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed; - 其次读 Candidate.structured_result_json.customer.resolution_status。 + 核心逻辑:只读 Candidate 的正式客户识别结果;不读取 bill_to 或解析摘要兜底。 Args: candidate: 可选 Candidate。 @@ -183,56 +179,35 @@ def resolve_candidate_customer_resolved( Returns: True 表示客户已确认,可用于建单资格评估。 """ - ext_id = extraction_id - if ext_id is None and candidate is not None: - raw = getattr(candidate, 'order_extraction_id', None) - if raw is not None: - try: - ext_id = int(raw) - except (TypeError, ValueError): - ext_id = None - if ext_id is not None: - row = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(ext_id), - role='bill_to', - status='confirmed', - ).first() - if row is not None and row.customer_id is not None: - return True + from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task - if candidate is None: - return False - ok, _reason = _customer_ok(candidate, customer_resolved=None) - return bool(ok) + resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id) + if resolution is not None: + return bool(resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None) + # review_case 人工确认新建的 Candidate 只在 structured_result_json['customer'] 写入确认事实 + # (review_case 权威确认,见 order_review_confirmation_service._create_review_candidate),并不落 resolution 表; + # 在建单资格判断时兜底认可,避免"已确认客户却无法建单"。 + structured = getattr(candidate, 'structured_result_json', None) if candidate is not None else None + if isinstance(structured, dict): + customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {} + return str(customer.get('resolution_status') or '').strip().lower() == 'confirmed' + return False -def resolve_confirmed_bill_to_customer_id( +def resolve_confirmed_customer_id( *, candidate: Any | None = None, extraction_id: int | None = None, ) -> int | None: """ - 返回已确认 Bill-to 标准客户主键;未确认时为 None。 - - 核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。 + 返回正式识别结果中已确认的标准客户主键;未确认时为 None。 """ - ext_id = extraction_id - if ext_id is None and candidate is not None: - raw = getattr(candidate, 'order_extraction_id', None) - if raw is not None: - try: - ext_id = int(raw) - except (TypeError, ValueError): - ext_id = None - if ext_id is not None: - row = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(ext_id), - role='bill_to', - status='confirmed', - ).first() - if row is not None and row.customer_id is not None: - return int(row.customer_id) - return None + from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task + + resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id) + return int(resolution.confirmed_customer_id) if ( + resolution is not None and resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None + ) else None def assert_customer_confirmed_before_task_create( diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 44368a67..b456a676 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -2,11 +2,17 @@ services/shipping_notice/chat_actions.py 用途:发货通知聊天只读状态适配。 -依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。 +依赖:state_machine(位置/用户模式与内部状态迁移)、ui_state。 逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。 """ -from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry +from app.services.shipping_notice.state_machine import ( + TaskTransition, + apply_task_transition, + position_for_task, + resolve_task_ui_state, + validate_registry, +) from app.services.shipping_notice.ui_state import build_task_ui_state @@ -14,19 +20,20 @@ def build_chat_actions_payload(task) -> dict: """ 构建聊天气泡侧动作按钮兼容 payload。 - 核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate; + 核心逻辑:复用统一 UI State 读模型,抽取聊天侧 position/user_mode/summary/process_gate; 业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。 Args: task: ShippingNotice 模型实例。 Returns: - 包含 task_no、checkpoint、process_gate、actions 与摘要的字典。 + 包含 task_no、position、user_mode、process_gate、actions 与摘要的字典。 """ state = build_task_ui_state(task) return { "task_no": state.get("task_no"), - "checkpoint": state.get("checkpoint"), + "position": state.get("position"), + "user_mode": state.get("user_mode"), "stage": state.get("stage"), "todo": state.get("todo"), "actions": state.get("actions"), @@ -41,7 +48,7 @@ __all__ = [ "TaskTransition", "apply_task_transition", "build_chat_actions_payload", - "checkpoint_for_task", + "position_for_task", "resolve_task_ui_state", "validate_registry", ] diff --git a/backend/app/services/shipping_notice/chat_tool_capability.py b/backend/app/services/shipping_notice/chat_tool_capability.py index 7174b069..a1913a62 100644 --- a/backend/app/services/shipping_notice/chat_tool_capability.py +++ b/backend/app/services/shipping_notice/chat_tool_capability.py @@ -13,7 +13,7 @@ from typing import Any from flask import current_app from app.core.errors import ForbiddenError -from app.models import ChatSession, ShippingNotice +from app.models import ChatSession, ShippingOrderTask READ_SCOPES = frozenset({'get_shipping_status'}) @@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non if session is None: raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED') if task_no: - task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() + task = ShippingOrderTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() if task is None or str(body.get('task') or '').upper() != task.task_no: raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') return body diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index 23b84e52..e3d2bfaa 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -1,10 +1,10 @@ """ services/shipping_notice/constants.py -用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量; +用途:发货通知 API 字段名、位置标签 POSITION_* / review_status / pending_human_reason 的规范常量; 并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。 -依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。 -逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移; +依赖:error_explainability_contract(分层原因码冻结集);state_machine / ui_state 引用 POSITION_*/PH_*/RS_*。 +逻辑:tools.py、tool_response、workspace API 统一读本模块,避免位置标签漂移; 细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。 """ @@ -36,28 +36,27 @@ from app.services.shipping_notice.error_explainability_contract import ( # Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑 AUTO_CHAIN_FALLBACK = "auto_chain_fallback" -# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py) -CP_UPLOAD_REQ = "upload_req" -CP_PARSE_OK = "parse_ok" -CP_PARSE_REVIEW = "parse_review" -CP_CUSTOMER_REVIEW = "customer_review" -CP_TASK_EXISTS = "task_exists" -CP_RSV_REQ = "rsv_req" -CP_UPLOAD_FAILED = "upload_failed" -CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" -CP_WAITING_UPLOAD = "waiting_upload" -CP_REJECTED = "rejected" -# Derived UI checkpoints (no separate pending_human_reason; from domain facts) -CP_INVENTORY_PENDING = "inventory_pending" -CP_READY_MATCH = "ready_to_match" -CP_READY_EXPORT = "ready_to_export" -CP_EXPORT_READY = "export_ready" -CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" -CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review" -CP_ORDER_FREEZE = "order_freeze" -CP_EXPORT_GENERATED = "export_generated" -CP_UPLOADED = "uploaded" -CP_COMPLETED = "completed" +# 位置标签(原 CheckPoint 字面量;非状态机。derive_position / 文案表共用) +POSITION_UPLOAD_REQ = "upload_req" +POSITION_PARSE_OK = "parse_ok" # 转瞬态;新逻辑勿依赖 +POSITION_PARSE_REVIEW = "parse_review" +POSITION_CUSTOMER_REVIEW = "customer_review" +POSITION_TASK_EXISTS = "task_exists" # 信息态;新逻辑勿依赖 +POSITION_RSV_REQ = "rsv_req" +POSITION_UPLOAD_FAILED = "upload_failed" +POSITION_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" +POSITION_WAITING_UPLOAD = "waiting_upload" +POSITION_REJECTED = "rejected" +POSITION_INVENTORY_PENDING = "inventory_pending" +POSITION_READY_MATCH = "ready_to_match" +POSITION_READY_EXPORT = "ready_to_export" +POSITION_EXPORT_READY = "export_ready" +POSITION_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" +POSITION_INVENTORY_SOURCE_REVIEW = "inventory_source_review" +POSITION_ORDER_FREEZE = "order_freeze" +POSITION_EXPORT_GENERATED = "export_generated" +POSITION_UPLOADED = "uploaded" +POSITION_COMPLETED = "completed" # review_status RS_PARSE_REVIEW = "parse_review" @@ -68,13 +67,13 @@ RS_CONFIRMED = "confirmed" # pending_human_reason (internal; shortened) PH_LOW_CONF = "low_confidence" -PH_RSV_REQ = CP_RSV_REQ +PH_RSV_REQ = POSITION_RSV_REQ PH_SHORTAGE = "shortage" PH_RPA_EXHAUSTED = "rpa_exhausted" PH_RPA_PENDING = "rpa_pending" PH_INV_UNAVAIL = "inv_unavail" PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved" -PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED +PH_NOTICE_TEXT_EXTRACTION_FAILED = POSITION_NOTICE_TEXT_EXTRACTION_FAILED PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" @@ -82,26 +81,26 @@ PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" # 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档) __all__ = ( 'AUTO_CHAIN_FALLBACK', - 'CP_UPLOAD_REQ', - 'CP_PARSE_OK', - 'CP_PARSE_REVIEW', - 'CP_CUSTOMER_REVIEW', - 'CP_TASK_EXISTS', - 'CP_RSV_REQ', - 'CP_UPLOAD_FAILED', - 'CP_UPLOAD_RESULT_UNKNOWN', - 'CP_WAITING_UPLOAD', - 'CP_REJECTED', - 'CP_INVENTORY_PENDING', - 'CP_READY_MATCH', - 'CP_READY_EXPORT', - 'CP_EXPORT_READY', - 'CP_NOTICE_TEXT_EXTRACTION_FAILED', - 'CP_INVENTORY_SOURCE_REVIEW', - 'CP_ORDER_FREEZE', - 'CP_EXPORT_GENERATED', - 'CP_UPLOADED', - 'CP_COMPLETED', + 'POSITION_UPLOAD_REQ', + 'POSITION_PARSE_OK', + 'POSITION_PARSE_REVIEW', + 'POSITION_CUSTOMER_REVIEW', + 'POSITION_TASK_EXISTS', + 'POSITION_RSV_REQ', + 'POSITION_UPLOAD_FAILED', + 'POSITION_UPLOAD_RESULT_UNKNOWN', + 'POSITION_WAITING_UPLOAD', + 'POSITION_REJECTED', + 'POSITION_INVENTORY_PENDING', + 'POSITION_READY_MATCH', + 'POSITION_READY_EXPORT', + 'POSITION_EXPORT_READY', + 'POSITION_NOTICE_TEXT_EXTRACTION_FAILED', + 'POSITION_INVENTORY_SOURCE_REVIEW', + 'POSITION_ORDER_FREEZE', + 'POSITION_EXPORT_GENERATED', + 'POSITION_UPLOADED', + 'POSITION_COMPLETED', 'RS_PARSE_REVIEW', 'RS_SHORTAGE_REVIEW', 'RS_RSV_REQ', diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index b3fdbf7e..3232cb29 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -1,19 +1,16 @@ """ services/shipping_notice/customer_auto_resolution.py -用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。 -依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。 -逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。 +用途:基于管理员审核的强证据受控自动确认 OT 客户。 +依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。 +逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。 """ from __future__ import annotations -import hashlib -from datetime import datetime from typing import Any from app import db -from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingCustomer, ShippingCustomerShadowResolution, @@ -24,24 +21,25 @@ from app.models import ( ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchemaVersion, - ShippingNotice, + ShippingOrderTask, ShippingTaskEvent, ) -from app.services.shipping_notice.customer_identity_gate import confirm_task_customer +from app.services.shipping_notice.customer_identity_gate import ( + confirm_task_customer, + customer_confirmation_facts, +) from app.services.shipping_notice.customer_normalization import ( is_public_email_domain, normalize_customer_name, normalize_domain, normalize_email, ) -from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no -from app.services.shipping_notice.business_numbering_service import assign_notice_business_number +from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id AUTO_RESOLUTION_VERSION = "customer-auto-v2" CUSTOMER_AUDIT_EVENT_TYPES = ( "customer_auto_resolution_evaluated", "customer_auto_confirmed", - "customer_correction_applied", ) @@ -92,6 +90,52 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]: } +def _ruleset_definitions_semantically_compatible( + snapshot: dict[str, Any], schema_version: ShippingOrderSchemaVersion, +) -> bool: + """ + 校验规则集冻结定义在解析所用 Schema 版本中语义契约仍成立(允许 Schema 常规重发布造成的版本错位)。 + + 语义键集合:field_code / scope('header') / value_type / normalizer_key / available_for_customer_identity。 + 允许 display_name、aliases、extraction_instruction、evidence_policy 等非语义字段变化; + 任一语义键不一致或字段被停用则 fail-closed,防止按过期配置标准化产生误绑客户。 + + Args: + snapshot: 影子 rule_set 快照(含 definitions)。 + schema_version: 解析实际使用的 Schema 版本。 + + Returns: + True 表示所有带 field_code 的定义在新 Schema 中语义兼容。 + """ + fields = ((schema_version.definition_json or {}).get('fields') or []) if schema_version else [] + fields_by_code = { + str(item.get('field_code') or ''): item + for item in fields if isinstance(item, dict) and str(item.get('field_code') or '') + } + definitions = snapshot.get('definitions') if isinstance(snapshot, dict) else [] + for raw in definitions if isinstance(definitions, list) else []: + if not isinstance(raw, dict): + continue + config = raw.get('field_config') if isinstance(raw.get('field_config'), dict) else {} + field_code = str(config.get('field_code') or '').strip() + if not field_code: + # 旧快照未保存 field_code:无法做语义校验,交由 UUID 直配路径(继续,不判定失败)。 + continue + actual = fields_by_code.get(field_code) + if actual is None or not actual.get('enabled', True): + return False + if str(actual.get('scope') or '') != 'header' or str(config.get('scope') or '') != 'header': + return False + if str(actual.get('value_type') or '') != str(config.get('value_type') or ''): + return False + if not actual.get('available_for_customer_identity'): + return False + frozen_normalizer = str(config.get('normalizer_key') or '').strip() + if frozen_normalizer and frozen_normalizer != str(actual.get('normalizer_key') or '').strip(): + return False + return True + + def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None: """校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。""" context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {} @@ -118,16 +162,12 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | or snapshot.get('order_schema') != frozen_definition.get('order_schema') ): return None - schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None - if not schema or schema.get('id') != shadow.order_schema_version_id: - return None + # Schema 锚点放宽:规则集冻结的版本 id 可与解析实际使用的版本错位(Schema 常规重发布), + # 但解析所用 Schema 版本必须真实存在(published/retired),且规则集定义在新 Schema 中语义兼容。 schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) - if ( - schema_version is None - or schema_version.status not in {'published', 'retired'} - or schema_version.version != schema.get('version') - or schema_version.checksum != schema.get('checksum') - ): + if schema_version is None or schema_version.status not in {'published', 'retired'}: + return None + if not _ruleset_definitions_semantically_compatible(snapshot, schema_version): return None extraction_id = context.get('order_extraction_id') extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None @@ -286,7 +326,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow return result -def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: +def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: """ 使用任务来源 Candidate 的影子证据执行受控自动裁决。 @@ -307,13 +347,14 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: 'is_eligible': False, }, } - if task.source_candidate_id is None: + candidate_id = getattr(task, 'candidate_id', None) + if candidate_id is None: return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( - candidate_id=int(task.source_candidate_id), + candidate_id=int(candidate_id), ).first() if shadow is None: - candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) + candidate = db.session.get(ShippingOrderCandidate, int(candidate_id)) if candidate is not None: from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution @@ -333,20 +374,23 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: return {**decision, 'quality_gate': quality_gate} -def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: +def try_auto_confirm_task_customer(task: ShippingOrderTask) -> dict[str, Any]: """ - 尝试自动确认并生成业务编号;未达门槛时保持 customer_review。 + 尝试自动确认 OT 客户;未达门槛时保持 customer_review。 - 核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 + 核心逻辑:先写自动裁决审计,再复用人工确认事务;成功后将确认方法改为 auto_rule。 """ - if task.customer_resolution_status == "confirmed": - return {"status": "already_confirmed", "customer_id": task.customer_id} + facts = customer_confirmation_facts(task) + if facts['status'] == 'confirmed': + return {"status": "already_confirmed", "customer_id": facts['customer_id']} decision = resolve_auto_customer_from_shadow(task) - db.session.add(ShippingTaskEvent( - task_id=task.id, - event_type="customer_auto_resolution_evaluated", - detail_json=decision, - )) + event_task_id = task_event_task_id(task) + if event_task_id is not None: + db.session.add(ShippingTaskEvent( + task_id=event_task_id, + event_type="customer_auto_resolution_evaluated", + detail_json=decision, + )) if decision.get("customer_id") is None: db.session.flush() return decision @@ -358,165 +402,32 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: resolution_method="auto_rule", commit=False, ) - db.session.add(ShippingTaskEvent( - task_id=updated.id, - event_type="customer_auto_confirmed", - detail_json={ - **decision, - "business_no": updated.business_no, - }, - )) + updated_event_task_id = task_event_task_id(updated) + if updated_event_task_id is not None: + db.session.add(ShippingTaskEvent( + task_id=updated_event_task_id, + event_type="customer_auto_confirmed", + detail_json={ + **decision, + "business_no": getattr(updated, 'business_no', None), + }, + )) db.session.flush() - return {**decision, "status": "auto_confirmed", "business_no": updated.business_no} - - -def correct_numbered_task_customer( - task: ShippingNotice, - *, - customer_id: int, - reason: str, - actor_id: int | None, -) -> dict[str, Any]: - """ - 更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。 - - 核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice → - 清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 - - Args: - task: 原业务号或技术号定位到的当前任务版本。 - customer_id: 管理员确认的正确启用客户 ID。 - reason: 必填纠错原因,写入审计事件。 - actor_id: 管理员审计 ID。 - Returns: - 原号、新号、替代业务单和受影响任务信息。 - Raises: - ValidationError: 缺少原因、客户无效或客户未变化。 - ConflictError: 业务单未编号、已上传或已被替代。 - """ - correction_reason = str(reason or "").strip() - if not correction_reason: - raise ValidationError( - "Customer correction reason is required", - code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED", - ) - original = ( - db.session.query(ShippingNotice) - .filter(ShippingNotice.id == int(task.id)) - .with_for_update() - .one_or_none() - ) - if original is None or not original.business_no: - raise ConflictError( - "Numbered shipping notice is required for customer correction", - code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", - ) - existing_replacement = db.session.query(ShippingNotice.id).filter_by( - supersedes_task_id=original.id, - ).first() - if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided': - raise ConflictError( - "Shipping notice has already been replaced", - code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED", - ) - - customer = db.session.get(ShippingCustomer, int(customer_id)) - if customer is None: - raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND") - if customer.status == "merged": - raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED") - if customer.status != "active": - raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") - if original.customer_id == customer.id: - raise ValidationError( - "Corrected customer must differ from the current customer", - code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED", - ) - - if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: - raise ConflictError( - "Uploaded shipping notices require an external cancellation workflow before correction", - code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED", - ) - - old_business_no = str(original.business_no) - now = datetime.utcnow() - customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() - replacement = ShippingNotice( - task_no=generate_task_no(), - user_id=original.user_id, - conversation_id=original.conversation_id, - source_type=original.source_type, - source_file_name=original.source_file_name, - source_file_type=original.source_file_type, - source_content_hash=original.source_content_hash, - source_asset_id=original.source_asset_id, - source_intake_id=original.source_intake_id, - source_candidate_id=original.source_candidate_id, - order_task_id=original.order_task_id, - business_fingerprint=original.business_fingerprint, - fingerprint_version=original.fingerprint_version, - content_fingerprint=original.content_fingerprint, - content_fingerprint_version=original.content_fingerprint_version, - document_version=int(original.document_version or 1) + 1, - supersedes_task_id=original.id, - raw_content=original.raw_content, - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - customer_resolution_status="confirmed", - customer_resolution_method="admin_correction", - customer_identity_fingerprint=customer_fingerprint, - customer_confirmed_by=actor_id, - customer_confirmed_at=now, - ) - db.session.add(replacement) - db.session.flush() - new_business_no = assign_notice_business_number(replacement) - original.lifecycle_status = 'voided' - original.voided_at = now - original.voided_by_id = actor_id - original.void_reason = f'customer_correction:{correction_reason}' - correction_detail = { - "old_notice_id": original.id, - "new_notice_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "old_customer_id": original.customer_id, - "new_customer_id": customer.id, - "reason": correction_reason, - "actor_id": actor_id, - } - db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail)) - db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail)) - - # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 - db.session.commit() - return { - "task_no": replacement.task_no, - "old_notice_id": original.id, - "new_notice_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "customer_id": customer.id, - "affected_task_count": 1, - } + # OT 阶段只确认客户;业务编号属于正式 Notice 的 Excel 生成事务。 + return {**decision, "status": "auto_confirmed", "business_no": None} def get_auto_resolution_metrics() -> dict[str, Any]: - """汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。""" + """汇总自动裁决事件,供管理员监控、查询与降级判断。""" evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by( event_type="customer_auto_resolution_evaluated", ).distinct().count() confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by( event_type="customer_auto_confirmed", ).distinct().count() - corrected = db.session.query(ShippingTaskEvent.task_id).filter_by( - event_type="customer_correction_applied", - ).distinct().count() recent_events = ( - db.session.query(ShippingTaskEvent, ShippingNotice.task_no) - .join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id) + db.session.query(ShippingTaskEvent, ShippingOrderTask.task_no) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingTaskEvent.task_id) .filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES)) .order_by(ShippingTaskEvent.id.desc()) .limit(100) @@ -528,7 +439,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]: 'quality_gate': _auto_confirmation_quality_gate(), "evaluated_count": evaluated, "auto_confirmed_count": confirmed, - "corrected_task_count": corrected, "auto_confirmation_rate": (confirmed / evaluated) if evaluated else None, "recent_events": [ { diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index ea193393..da66174a 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -8,7 +8,6 @@ backend/app/services/shipping_notice/customer_identity_gate.py from __future__ import annotations -import hashlib from datetime import datetime from typing import Any @@ -16,18 +15,44 @@ from sqlalchemy import or_ from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError -from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ( + ShippingCustomer, + ShippingNotice, + ShippingOrderTask, +) from app.services.shipping_notice.customer_normalization import clean_text +from app.services.shipping_notice.customer_resolution_service import ( + confirm_customer_resolution, + customer_resolution_facts, +) CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' -def customer_identity_is_confirmed(task: ShippingNotice) -> bool: - """判断 Notice 自身是否已通过标准客户确认。""" - if task.customer_id is None: +def customer_confirmation_facts(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: + """读取唯一客户识别结果;bill_to 等订单字段仅可出现在识别证据中。""" + facts = customer_resolution_facts(task) + resolution = facts['resolution'] + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None + return { + 'customer_id': facts['customer_id'], + 'status': facts['status'], + 'resolution_method': getattr(resolution, 'confirmation_method', None), + 'identity_fingerprint': getattr(resolution, 'identity_rule_set_checksum', None), + 'confirmed_by_id': getattr(resolution, 'confirmed_by_id', None), + 'confirmed_at': getattr(resolution, 'confirmed_at', None), + 'customer_name_snapshot': getattr(customer, 'standard_name', None), + 'customer_short_code_snapshot': getattr(customer, 'short_code', None), + } + + +def customer_identity_is_confirmed(task: ShippingNotice | ShippingOrderTask) -> bool: + """判断 OT 或正式 Notice 是否已通过标准客户确认。""" + facts = customer_confirmation_facts(task) + if facts['customer_id'] is None or facts['status'] != 'confirmed': return False - customer = db.session.get(ShippingCustomer, int(task.customer_id)) - return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) + return bool(customer and customer.status == 'active') def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None: @@ -42,6 +67,9 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con """ if customer_identity_is_confirmed(task): return + facts = customer_confirmation_facts(task) + customer_id = facts['customer_id'] + status = facts['status'] or 'pending' raise AppError( code=CUSTOMER_GATE_ERROR_CODE, message='标准客户尚未确认,无法继续后续流程', @@ -49,8 +77,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con details={ 'operation': operation, 'task_no': task.task_no, - 'customer_resolution_status': task.customer_resolution_status or 'pending', - 'customer_id': task.customer_id, + 'customer_resolution_status': status, + 'customer_id': customer_id, }, ) @@ -71,15 +99,15 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str def confirm_task_customer( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, customer_id: int, actor_id: int | None, resolution_method: str = 'manual', commit: bool = True, -) -> ShippingNotice: +) -> ShippingNotice | ShippingOrderTask: """ - 人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。 + 人工确认 OT/Notice 所属标准客户;业务编号仅由正式 Notice 的 Excel 阶段分配。 核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。 客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。 @@ -91,12 +119,11 @@ def confirm_task_customer( resolution_method: manual/auto_rule 等审计方法。 commit: 是否提交事务;批次编排传 False 由外层统一提交。 """ + model = ShippingOrderTask if isinstance(task, ShippingOrderTask) else ShippingNotice task = ( - db.session.query(ShippingNotice) - .filter(ShippingNotice.id == int(task.id)) - # ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN; - # PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。 - .with_for_update(of=ShippingNotice) + db.session.query(model) + .filter(model.id == int(task.id)) + .with_for_update(of=model) .one() ) customer = db.session.get(ShippingCustomer, int(customer_id)) @@ -106,38 +133,28 @@ def confirm_task_customer( raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') if customer.status != 'active': raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') - if task.business_no and task.customer_id not in {None, customer.id}: + facts = customer_confirmation_facts(task) + if getattr(task, 'business_no', None) and facts['customer_id'] not in {None, customer.id}: raise ConflictError( 'Numbered shipping notice customer cannot be changed silently', code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED', ) - now = datetime.utcnow() - previous_customer_id = task.customer_id - task.customer_id = customer.id - task.customer_name_snapshot = customer.standard_name - task.customer_short_code_snapshot = customer.short_code - fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() - task.customer_resolution_status = 'confirmed' - task.customer_resolution_method = resolution_method - task.customer_identity_fingerprint = fingerprint - task.customer_confirmed_by = actor_id - task.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=task.id, - event_type='customer_confirmed', - detail_json={ - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'previous_customer_id': previous_customer_id, - 'method': resolution_method, - 'business_no': task.business_no, - }, - )) + owner = task + if not isinstance(task, ShippingOrderTask): + order_task_id = getattr(task, 'order_task_id', None) + owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None + if owner is None: + raise ConflictError('Shipping notice is not linked to an order task', code='SHIPPING.ORDER_TASK_REQUIRED') + confirm_customer_resolution( + owner, + customer_id=int(customer.id), + actor_id=actor_id, + method=resolution_method, + ) if commit: db.session.commit() - return db.session.get(ShippingNotice, int(task.id)) + return db.session.get(model, int(task.id)) db.session.flush() return task @@ -154,7 +171,7 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict task=task, message='标准客户尚未确认,请先选择正式客户后再继续。', data=serialize_task_for_tool(task), - checkpoint='customer_review', + position='customer_review', stop_agent_turn=True, forbidden_next_tools=[ 'ensure_inventory', 'parse_inventory', 'match_inventory', @@ -187,7 +204,7 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]: task=task, message='请选择标准客户。', data=serialize_task_for_tool(task), - checkpoint='customer_review', + position='customer_review', stop_agent_turn=True, ) updated = confirm_task_customer( diff --git a/backend/app/services/shipping_notice/customer_resolution_service.py b/backend/app/services/shipping_notice/customer_resolution_service.py new file mode 100644 index 00000000..93ab18fa --- /dev/null +++ b/backend/app/services/shipping_notice/customer_resolution_service.py @@ -0,0 +1,76 @@ +""" +services/shipping_notice/customer_resolution_service.py + +用途:提供订单任务的唯一客户识别结果读取与确认入口。 +依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。 +逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据, + 不能承担客户角色或流程门禁真相。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask + + +def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None: + """按 OT、Notice 或 Candidate 读取正式客户识别结果,不回读 bill_to 或解析摘要。""" + candidate_id = getattr(task, 'id', None) if isinstance(task, ShippingOrderCandidate) else getattr(task, 'candidate_id', None) + if candidate_id is None: + order_task_id = getattr(task, 'order_task_id', None) + order_task = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None + candidate_id = getattr(order_task, 'candidate_id', None) + if candidate_id is None: + return None + return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(candidate_id)).one_or_none() + + +def resolution_for_extraction(extraction_id: int | None) -> ShippingCustomerShadowResolution | None: + """按当前 Extraction 找到关联 Candidate 的唯一客户识别结果。""" + if extraction_id is None: + return None + candidate = ShippingOrderCandidate.query.filter_by(order_extraction_id=int(extraction_id)).one_or_none() + return resolution_for_task(candidate) if candidate is not None else None + + +def customer_resolution_facts(task: Any) -> dict[str, Any]: + """返回流程 Gate 所需的最小客户确认事实,缺失时 fail-closed。""" + resolution = resolution_for_task(task) + if resolution is None: + return {'customer_id': None, 'status': None, 'resolution': None} + return { + 'customer_id': resolution.confirmed_customer_id, + 'status': resolution.status, + 'resolution': resolution, + } + + +def confirm_customer_resolution( + task: Any, + *, + customer_id: int, + actor_id: int | None, + method: str, + reason: str | None = None, +) -> ShippingCustomerShadowResolution: + """确认当前识别结果的客户;人工或自动确认均保留原始证据、规则和候选快照。""" + resolution = resolution_for_task(task) + if resolution is None: + raise ConflictError('Customer resolution is required before confirmation', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED') + customer = db.session.get(ShippingCustomer, int(customer_id)) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if customer.status != 'active': + raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') + resolution.confirmed_customer_id = int(customer.id) + resolution.confirmation_method = str(method) + resolution.confirmation_reason = str(reason or '').strip() or None + resolution.confirmed_by_id = actor_id + resolution.confirmed_at = datetime.utcnow() + resolution.status = 'confirmed' + db.session.flush() + return resolution diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py deleted file mode 100644 index dd070fd8..00000000 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ /dev/null @@ -1,517 +0,0 @@ -""" -services/shipping_notice/decision_workflow.py - -用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。 -依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、 - tool_common(操作人/生命周期快照)、fulfillment_audit。 -逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照, - reject/close/confirm 同步写入 ShippingAuditEvent。 -""" - -from __future__ import annotations - -from typing import Any - -from app import db -from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink -from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, - CP_PARSE_OK, - PH_INVENTORY_SOURCE_UNRESOLVED, - PH_LOW_CONF, - PH_RPA_PENDING, - PH_SHORTAGE, - RS_PARSE_REVIEW, - RS_SHORTAGE_REVIEW, -) -from app.services.shipping_notice.fulfillment_workflow import match_completed -from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction -from app.services.shipping_notice.inventory_source_gate import ( - is_inventory_source_stable, - adjudicate_and_apply_inventory_source, - ensure_inventory_source_review_state, -) -from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state -from app.services.shipping_notice.tool_common import ( - log_task_action_event, - log_task_event, - merge_tool_payload, - payload_wants_auto_chain_fallback, - resolve_workspace_actor_id, - task_lifecycle_audit_snapshot, - prepend_tool_message, -) -from app.services.shipping_notice.tool_response import tool_response - - -def start_task_orchestrator(task_no: str | None) -> bool: - """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" - from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start - - return _start(task_no) - - -def _reset_inventory_state_for_forced_rpa(task) -> None: - """ - 清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。 - 【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。 - """ - task.inventory_lines_json = None - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - - -def _request_formal_gate_action(**kwargs): - """决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。 - - 核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留 - (review_status / pending_human_reason / error_message / upload 错误), - 避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。 - """ - task = kwargs.get('task') - if task is not None: - task.upload_error_message = None - task.upload_receipt_json = None - task.review_status = None - task.pending_human_reason = None - task.error_message = None - - from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request - - return _request(**kwargs) - - -def _prepare_task_for_inventory_reupload(task) -> None: - """ - 解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。 - - 【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。 - 历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。 - """ - if task.id is not None: - for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all(): - link.is_active = False - _reset_inventory_state_for_forced_rpa(task) - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - - -def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: - """ - 提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。 - 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。 - -核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate - Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。 - Args: - payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。 - - Returns: - dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。 - """ - task = resolve_task_from_payload(payload) - if not task: - return tool_response( - status="failed", - message=t("workflow.decision.task_not_found", lang="zh"), - ) - - decision = str(payload.get("decision") or "").strip().lower() - comment = str(payload.get("comment") or "").strip() - lang = resolve_lang(payload) - event_source = str(payload.get("event_source") or "").strip() or "decision_workflow" - actor_id = resolve_workspace_actor_id(payload) - before_snapshot = task_lifecycle_audit_snapshot(task) - - # Published parsing profiles are the only production mapping contract. - # Reject legacy task-level mapping decisions instead of reopening a manual - # mapping path that could override the source's configured profile. - if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}: - return tool_response( - status="failed", - task_id=task.task_no, - message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。", - data=serialize_task_for_tool(task), - ) - - if decision == "reparse_inventory": - _prepare_task_for_inventory_reupload(task) - log_task_action_event( - task, - "inventory_reupload_requested", - action="reparse_inventory", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。", - data=serialize_task_for_tool(task), - checkpoint="upload_req", - stop_agent_turn=True, - ) - - # [STEP 1] 先处理终止型决策。 - # reject / close 会直接结束当前任务,不再继续进入库存或出货链路。 - if decision == "reject": - apply_task_transition(task, TaskTransition.REJECTED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_rejected", - action="reject", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='reject', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot or {'status': 'active'}, - after=after_snapshot or {'status': 'rejected'}, - metadata={'decision': 'reject'}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.rejected", lang=lang), - data=serialize_task_for_tool(task), - ) - - if decision in {"close", "closed"}: - apply_task_transition(task, TaskTransition.CLOSED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_closed", - action="close", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='close', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot or {'status': 'active'}, - after=after_snapshot or {'status': 'closed'}, - metadata={'decision': 'close'}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.closed", lang=lang), - data=serialize_task_for_tool(task), - ) - - # [STEP 2] 处理“确认继续”类决策。 - # confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。 - if decision in {"confirm", "confirmed", "confirm_parse"}: - if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.shortage_confirm_blocked", lang=lang), - data=serialize_task_for_tool(task), - ) - - if ( - decision == "confirm_parse" - or task.review_status == RS_PARSE_REVIEW - or task.pending_human_reason == PH_LOW_CONF - or not match_completed(task) - ): - parse_validation = ( - (task.step_payload_json or {}).get("parse_validation") - if isinstance(task.step_payload_json, dict) - else None - ) - blocking_issues = [ - item - for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or [] - if isinstance(item, dict) and item.get("severity") == "blocking" - ] - if blocking_issues: - return tool_response( - status="needs_human", - task=task, - message="解析结果仍包含不合法的关键字段,请修正后再确认。", - data={**serialize_task_for_tool(task), "parse_validation": parse_validation}, - checkpoint=task.review_status or "parse_review", - stop_agent_turn=True, - forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], - ) - is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF - # 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。 - if ( - not is_low_confidence_parse_confirm - and ( - task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED - or not is_inventory_source_stable(task) - ) - ): - ui = resolve_task_ui_state(task) - return tool_response( - status="needs_human", - task=task, - message="库存源尚未确定,请先完成库存源确认。", - data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, - stop_agent_turn=True, - ) - apply_task_transition(task, TaskTransition.CONFIRM_PARSE) - task.match_status = None - task.shortage_json = None - task.line_results_json = None - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "parse_confirmed", - action="confirm", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='confirm_parse', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot, - after=after_snapshot, - metadata={'decision': decision}, - source=event_source, - ) - db.session.commit() - if not is_inventory_source_stable(task): - adjudication = ensure_inventory_source_review_state(task) - db.session.commit() - return tool_response( - status="ok", - task=task, - message="解析内容已确认,请继续选择正式库存源。", - data={ - **serialize_task_for_tool(task), - "inventory_source_candidates": adjudication.candidates, - "inventory_source_status": adjudication.status, - "inventory_source_reason": adjudication.reason, - "destination_candidates": adjudication.destination_candidates, - }, - checkpoint=CP_INVENTORY_SOURCE_REVIEW, - stop_agent_turn=True, - ) - if not task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.parse_confirmed_running", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_OK, - next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang), - forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], - ) - return tool_response( - status="ok", - task=task, - message=t("workflow.decision.parse_confirmed_next", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_OK, - next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang), - forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], - ) - - if match_completed(task): - apply_task_transition(task, TaskTransition.CONFIRM_MATCHED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_confirmed", - action="confirm", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='confirm_matched', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot, - after=after_snapshot, - metadata={'decision': decision}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.matched_confirmed", lang=lang), - data=serialize_task_for_tool(task), - ) - - if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.inventory_preparing", lang=lang), - data=serialize_task_for_tool(task), - ) - - if task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.fulfillment_running", lang=lang), - data=serialize_task_for_tool(task), - ) - - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.confirm_invalid_state", lang=lang), - data=serialize_task_for_tool(task), - ) - - # [STEP 3] 处理重算型决策。 - # retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路, - # 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。 - if decision == "retry_rpa": - _reset_inventory_state_for_forced_rpa(task) - log_task_event( - task, - "decision_retry_rpa", - {"comment": comment, "force_refresh": True}, - actor_id=actor_id, - source=event_source, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.flush() - return _request_formal_gate_action( - task=task, - action_code='retry_inventory_preparation', - user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), - idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'), - trigger=event_source, - ) - - if decision == "rematch": - apply_task_transition(task, TaskTransition.REMATCH_REQUESTED) - task.match_status = None - task.shortage_json = None - task.line_results_json = None - log_task_action_event( - task, - "decision_rematch", - action="rematch", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - # flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。 - db.session.flush() - return _request_formal_gate_action( - task=task, - action_code='retry_inventory_from_matching', - user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), - idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'), - trigger=event_source, - ) - - # [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。 - if decision == "reparse": - candidate = ( - db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) - if task.source_candidate_id else None - ) - source_run_id = candidate.order_extraction_run_id if candidate is not None else None - if source_run_id: - from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run - - run = db.session.get(ShippingOrderProcessingRun, source_run_id) - if run is not None: - replacement, reused = reparse_order_extraction_run( - user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None, - ) - log_task_action_event( - task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment, - extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused}, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.commit() - return tool_response( - status="needs_human", task=task, - message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。", - data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no}, - checkpoint=task.review_status or "parse_review", stop_agent_turn=True, - forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], - ) - return tool_response( - status="needs_human", - task=task, - message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。", - data=serialize_task_for_tool(task), - checkpoint=task.review_status or "parse_review", - stop_agent_turn=True, - forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], - ) - - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.unknown", lang=lang).format(decision=decision), - ) diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 62a3abda..3bfe2ba1 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -13,18 +13,18 @@ from __future__ import annotations from datetime import datetime from typing import Any -from app.models import ShippingNotice, ShippingTemporaryInventorySession +from app.models import ShippingOrderTask, ShippingTemporaryInventorySession from app.services.agent_runtime_context.builder import serialize_for_dify from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.shipping_notice.runtime_context import build_shipping_runtime_context -def _task_by_task_no(task_id: str) -> ShippingNotice | None: +def _task_by_task_no(task_id: str) -> ShippingOrderTask | None: """按显式 task_id 获取任务;禁止按会话号猜测当前任务。""" normalized = str(task_id or "").strip().upper() if not normalized: return None - return ShippingNotice.query.filter_by(task_no=normalized).first() + return ShippingOrderTask.query.filter_by(task_no=normalized).first() def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None: @@ -56,7 +56,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N return str(item.session_no or '').strip().upper() or None if item else None -def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None: +def _focus_task_row(focus_task: str, explicit_task_row: ShippingOrderTask | None) -> ShippingOrderTask | None: """ 解析当前显式焦点任务行。 @@ -74,7 +74,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) - return None if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized: return explicit_task_row - return ShippingNotice.query.filter_by(task_no=normalized).first() + return ShippingOrderTask.query.filter_by(task_no=normalized).first() def build_dify_chat_inputs( 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 e6fc1a96..271e6ba1 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 @@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy( dynamic_rows = reconstruct_coordinate_profile_rows( characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, table_region=table_region, termination_rules=termination_rules, + # dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。 exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code, include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns', schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, @@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows( _absolute_relative_region(bbox, item) for item in (exclusion_regions or []) if isinstance(item, dict) ] + marker_authorization_exclusions = exclusions # 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其 # “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions, # 从而保留管理员配置的普通排除区。 @@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows( continue band_indices = {glyph_index for glyph_index, _glyph in band} marker_indices.update(band_indices) - if exclusions and any( + if marker_authorization_exclusions and any( _inside_region(glyph.bbox, region) for _glyph_index, glyph in band - for region in exclusions + for region in marker_authorization_exclusions ): authorized_marker_indices.update(band_indices) # [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。 @@ -604,7 +606,8 @@ def reconstruct_coordinate_profile_rows( # This mode is opt-in per table region. It supports documents whose stable # columns stay put while optional descriptions move values across visual rows. if row_reconstruction_mode == 'dynamic_x_columns': - return _reconstruct_dynamic_x_columns_profile_rows( + return _resolve_shifted_part_number_candidates( + rows=_reconstruct_dynamic_x_columns_profile_rows( glyphs=glyphs, table_bbox=bbox, ordered_layouts=ordered_layouts, @@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, schema_fields=schema_fields, + ), + glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, ) if row_reconstruction_mode == 'adaptive_record_columns': - return _reconstruct_adaptive_record_columns_profile_rows( + return _resolve_shifted_part_number_candidates( + rows=_reconstruct_adaptive_record_columns_profile_rows( glyphs=glyphs, table_bbox=bbox, ordered_layouts=ordered_layouts, @@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, schema_fields=schema_fields, + ), + glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, ) relative_y_rows = _reconstruct_relative_y_profile_rows( @@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows( schema_fields=schema_fields, ) if relative_y_rows is not None: - return relative_y_rows + return _resolve_shifted_part_number_candidates( + rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, + ) def values_for( band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any], @@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows( current_issues.extend(continuation_issues) next_offset += 1 flush() - return results if include_deleted else [row for row in results if row.role != 'deleted'] + rows = results if include_deleted else [row for row in results if row.role != 'deleted'] + return _resolve_shifted_part_number_candidates( + rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, + ) def _project_coordinate_profile_regions( @@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows( delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center values: dict[str, str] = {} issues: list[str] = [] + deleted = any( + _DELETED_PATTERN.fullmatch(re.sub( + r'\s+', '', ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ), + )) + for _row_index, band in record + ) for field in fields: code = str(field['field_code']) saved = _absolute_relative_region(table_bbox, field['region']) + # [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分, + # 保持 LayoutBBox 的非负原点和正面积契约。 + shifted_y0 = max(0.0, saved.y0 + delta_y) region = LayoutBBox( - x0=saved.x0, y0=saved.y0 + delta_y, - x1=saved.x1, y1=saved.y1 + delta_y, + x0=saved.x0, y0=shifted_y0, + x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y), ) selected_bands = [ band for _row_index, band in record @@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows( results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _band in record], - role='data', issues=issues, + role='deleted' if deleted else 'data', issues=issues, )) return results if include_deleted else [row for row in results if row.role != 'deleted'] @@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows( start_region = _absolute_relative_region(table_bbox, start_field['region']) expected_anchor_center = (start_region.y0 + start_region.y1) / 2 results: list[CoordinateProfileLogicalRow] = [] + sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)] + expected_indices = _calibrate_field_band_indices( + fields=fields, sample_record=sample_record, table_bbox=table_bbox, + ) + multiline_fields = { + id(field) for field in fields + if sum( + _regions_overlap_vertically( + _absolute_relative_region(table_bbox, field['region']), _band_bbox(band), + ) + for _row_index, band in sample_record + ) > 1 + } for anchor_index, start in enumerate(anchors): end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands) record = usable_bands[start:end] @@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows( x0=saved.x0, y0=saved.y0 + delta_y, x1=saved.x1, y1=saved.y1 + delta_y, ) - # A visual field box may intentionally span multiple PDF text lines - # (for example a wrapped customer part number). The previous - # one-band assignment treated that as an ambiguity and dropped the - # field, which caused two vertically stacked part-number fields to - # become empty or reuse the same prefix. When the configured field - # region intersects multiple bands, read all of its own glyphs; - # single-band fields retain the calibrated matching behavior. - intersecting = [ - band for _row_index, band in record - if _regions_overlap_vertically(region, _band_bbox(band)) - ] - if not intersecting: - continue - raw = _text_in_multiline_region( - intersecting, region, - compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, - ) + if id(field) not in multiline_fields: + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else '' + if code == 'part_number': + expected_index = expected_indices.get(id(field), 0) + candidates: list[tuple[float, int, str]] = [] + for candidate_index in range(expected_index, len(record)): + candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region) + if _is_structured_part_identifier(candidate_raw): + compact_candidate = re.sub(r'\s+', '', candidate_raw) + candidates.append(( + _profile_field_band_score( + raw=candidate_raw, field_code=code, + extractor_key=str(field.get('extractor_key') or 'direct'), + ), + candidate_index, candidate_raw, + )) + if re.search(r'\d', compact_candidate): + candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:]) + candidates.sort(key=lambda item: (-item[0], item[1])) + if len(candidates) == 1: + raw = candidates[0][2] + elif len(candidates) > 1: + best = candidates[0] + if best[0] > candidates[1][0] + .25: + raw = best[2] + else: + issues.append(f'coordinate_profile_field_band_ambiguous:{code}') + raw = '' + else: + # A visual field box may intentionally span multiple PDF text lines + # (for example a wrapped customer part number). The previous + # one-band assignment treated that as an ambiguity and dropped the + # field, which caused two vertically stacked part-number fields to + # become empty or reuse the same prefix. When the configured field + # region intersects multiple bands, read all of its own glyphs; + # single-band fields retain the calibrated matching behavior. + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + if not intersecting: + continue + raw = _text_in_multiline_region( + intersecting, region, + compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, + ) if not raw: continue extracted = extract_profile_field_value( @@ -1890,6 +1964,137 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str) return score +def _is_structured_part_identifier(raw: str) -> bool: + """ + 判断文本是否可作为内部料号纠偏证据。 + + 核心逻辑:去首尾空白后仍须是无空格的紧凑标识(字母数字 + ._:/-),且含数字或 + 连接符;含空格的贸易条款/描述串一律拒绝,避免去空格后误匹配。 + + Args: + raw: 候选原文。 + + Returns: + True 表示可作为 structured 料号证据。 + """ + value = str(raw or '').strip() + if not value or re.search(r'\s', value): + return False + return bool( + not re.match(r'^(?:revision|rev):', value, re.IGNORECASE) + and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', value) + and re.search(r'\d|[._:/-]', value) + ) + + +def _resolve_shifted_part_number_candidates( + *, rows: list[CoordinateProfileLogicalRow], + glyphs: list[tuple[int, PositionedCharacter]], + ordered_layouts: list[dict[str, Any]], + table_bbox: LayoutBBox, + line_start_field_code: str, +) -> list[CoordinateProfileLogicalRow]: + """ + 在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。 + + 核心逻辑:仅当当前位置读到的值不是 structured 料号(多为描述折行)时,才扫描 + 后续视觉行;唯一高置信候选可替换,多候选则 Review。当前位置已是 structured + 时保持原值,禁止被后续条款行无条件覆盖。 + + Args: + rows: 三种重建模式产出的逻辑明细。 + glyphs: 表区内带索引的字符。 + ordered_layouts: 按 row_offset 排序的子行布局。 + table_bbox: 重建坐标系下的表/页框。 + line_start_field_code: 起行锚点字段编码。 + + Returns: + 纠偏后的逻辑明细列表(原地更新 fields/issues)。 + """ + part_fields = [ + field for layout in ordered_layouts + for field in (layout.get('field_regions') or []) + if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number' + and isinstance(field.get('region'), dict) + ] + if not part_fields: + return rows + part_start_offset = min( + offset for offset, layout in enumerate(ordered_layouts) + if any(field in (layout.get('field_regions') or []) for field in part_fields) + ) + # 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段, + # 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。 + if part_start_offset == 0: + return rows + bands = _group_visual_rows(glyphs) + main_fields = ordered_layouts[0].get('field_regions') or [] + start_field = next( + ( + field for field in main_fields + if isinstance(field, dict) + and str(field.get('field_code') or '') == line_start_field_code + and isinstance(field.get('region'), dict) + ), + None, + ) + start_region = ( + _absolute_relative_region(table_bbox, start_field['region']) + if start_field is not None else None + ) + + for row_position, row in enumerate(rows): + current = str(row.fields.get('part_number') or '').strip() + if not current or not row.source_row_indices: + continue + # 当前位置已是结构化料号:纠偏只服务描述折行,不得再扫后续条款行覆盖。 + if _is_structured_part_identifier(current): + continue + record_start = min(row.source_row_indices) + record_end = ( + min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:]) + if row_position + 1 < len(rows) else len(bands) + ) + candidates: list[tuple[float, int, str]] = [] + # 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述, + # 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步, + # 因为自适应重建可能已把后续候选 band 一并吸收到当前行。 + expected_index = record_start + part_start_offset + scan_start = expected_index + for index in range(scan_start, record_end): + # 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因 + # 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。 + if index > record_start and start_region is not None: + start_raw = _text_in_horizontal_region(bands[index], start_region) + if is_valid_line_start_value(start_raw): + break + for field in part_fields: + region = _absolute_relative_region(table_bbox, field['region']) + raw = _text_in_horizontal_region(bands[index], region) + if raw.strip() == current: + continue + if not _is_structured_part_identifier(raw): + continue + score = _profile_field_band_score( + raw=raw, field_code='part_number', + extractor_key=str(field.get('extractor_key') or 'direct'), + ) + score -= abs(index - expected_index) * .5 + if re.search(r'\d', re.sub(r'\s+', '', raw)): + score += .5 + candidates.append((score, index, raw)) + candidates.sort(key=lambda item: (-item[0], item[1])) + if len(candidates) == 1: + row.fields['part_number'] = candidates[0][2] + elif len(candidates) > 1: + if candidates[0][0] > candidates[1][0] + .25: + row.fields['part_number'] = candidates[0][2] + else: + row.fields.pop('part_number', None) + row.issues.append('coordinate_profile_field_band_ambiguous:part_number') + return rows + + def _text_in_region( band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, ) -> str: diff --git a/backend/app/services/shipping_notice/document_layout/field_split_core.py b/backend/app/services/shipping_notice/document_layout/field_split_core.py index 71d27929..6a06b316 100644 --- a/backend/app/services/shipping_notice/document_layout/field_split_core.py +++ b/backend/app/services/shipping_notice/document_layout/field_split_core.py @@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any]) segment.pop('handling', None) segment.pop('target_field_id', None) segment.pop('target_field_code', None) + # segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。 + segment.pop('segment_id', None) return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')) diff --git a/backend/app/services/shipping_notice/document_layout/html_table.py b/backend/app/services/shipping_notice/document_layout/html_table.py index cfd86fb3..8f54df54 100644 --- a/backend/app/services/shipping_notice/document_layout/html_table.py +++ b/backend/app/services/shipping_notice/document_layout/html_table.py @@ -464,10 +464,13 @@ def _map_data_row( if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract): return HtmlMappedRow(row_index=row_index, role='repeated_header') joined = ' '.join(normalized) - if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined: + # 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。 + marker_joined = joined.lower() + if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined: return HtmlMappedRow(row_index=row_index, role='deleted') first = next((item for item in normalized if item), '') - if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first): + # 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。 + if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()): return HtmlMappedRow(row_index=row_index, role='summary') if _has_explicit_zero_quantity(row, columns=columns): return HtmlMappedRow(row_index=row_index, role='deleted') @@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool: if not texts: return False markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'} - return all(text in markers for text in texts) + # 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。 + return all(text.lower() in markers for text in texts) def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]: diff --git a/backend/app/services/shipping_notice/document_layout/order_profile.py b/backend/app/services/shipping_notice/document_layout/order_profile.py index 6b416d38..683492c5 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -5,7 +5,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py 依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。 逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费 DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成 - matching_signature 供运行时硬门禁与维度比对。 + matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。 """ from __future__ import annotations @@ -329,10 +329,10 @@ SCORING_DIMENSION_KEYS = ( 'optional_static_text', 'trusted_business_context', ) +# table_geometry 保留为软分;MinerU 脏高度不得作为自动决胜硬门禁。 CRITICAL_STRUCTURE_DIMENSION_KEYS = ( 'header_semantic_position', 'column_topology', - 'table_geometry', ) # 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。 _LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = { diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py b/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py index 784bdaf9..9d913ae2 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py @@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str if field_code == 'reservation_id': value = validated_reservation_id(text) return {field_code: value} if value else {} + if field_code == 'uom': + # 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。 + stripped = re.sub(r'\d+', '', text).strip() + return {field_code: stripped} if stripped else {} return {field_code: text} if extractor_key == 'temp_internal_parts': resolved = resolve_composite_part_numbers(text) 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 11d12dc3..c00706d5 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 @@ -4,7 +4,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py 用途:以冻结版面签名与坐标证据唯一匹配订单坐标模板,按统一七维权重做确定性综合评分。 依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。 逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜; - 页存在≠page_structure 命中;line_layout 存在≠结构匹配;缺失锚点/客户提示不得满分。 + table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column; + 主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表; + 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。 """ from __future__ import annotations @@ -34,6 +36,7 @@ from app.services.shipping_notice.document_layout.order_profile import ( ) from app.services.shipping_notice.document_layout.order_profile_signature import ( MATCHER_POLICY_ID, + clip_table_bbox_to_business_rows, signature_checksum, ) @@ -167,6 +170,8 @@ def match_frozen_coordinate_profiles( observed = _observe_layout_features( layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables, page_glyphs=page_glyphs, signature=observed_signature, + termination_rules=_profile_termination_rules(profile), + exclusion_regions=_profile_exclusion_regions(profile), ) if signature_body is None: reason_codes.append('profile_signature_missing') @@ -882,11 +887,20 @@ def _compute_dimension_results( results: dict[str, MatchDimensionResult] = {} # [STEP 1] header_semantic_position:表头语义和位置必须独立于锚点硬门禁。 + # 有 required_anchors 时不做表头原子硬互斥——唯一身份由锚点承担,避免噪声表头误杀。 + enforce_header_atoms = _should_enforce_header_atom_discriminator(required_hits) header_result = _score_header_semantic_position( signature=signature, observed=observed, required_hits=required_hits, + enforce_atom_discriminator=enforce_header_atoms, ) results['header_semantic_position'] = header_result if ( + enforce_header_atoms + and header_result.state == 'mismatched' + and _header_discriminator_atoms_conflict(signature=signature, observed=observed) + ): + hard_conflicts.append('profile_header_discriminator_conflict') + elif ( header_result.state == 'mismatched' and signature and signature.get('table_patterns') @@ -926,13 +940,27 @@ def _compute_dimension_results( return results, hard_conflicts +def _should_enforce_header_atom_discriminator(required_hits: list[bool]) -> bool: + """ + 判断是否启用表头原子硬互斥。 + + 核心逻辑:模板若已配置必选锚点,身份由锚点门禁承担,不再用表头原子硬杀; + 仅「无必选锚点」的近亲模板才启用原子互斥。 + """ + return not required_hits + + def _score_header_semantic_position( *, signature: dict[str, Any] | None, observed: dict[str, Any], required_hits: list[bool], + enforce_atom_discriminator: bool = True, ) -> MatchDimensionResult: - """比对真实表头 token、横向顺序和位置;锚点命中不替代表头结构证据。""" + """比对真实表头 token、横向顺序和位置。 + + 核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。 + """ if signature is None: return MatchDimensionResult(state='unavailable', score=0.0) expected_tokens: list[str] = [] @@ -951,6 +979,11 @@ def _score_header_semantic_position( ) if not observed_tokens: return MatchDimensionResult(state='unavailable', score=0.0) + if ( + enforce_atom_discriminator + and _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens) + ): + return MatchDimensionResult(state='mismatched', score=0.0) matched = sum(1 for token in expected_tokens if token in observed_tokens) token_ratio = matched / len(expected_tokens) expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []] @@ -971,6 +1004,43 @@ def _score_header_semantic_position( ) +_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'}) +_HEADER_ATOM_MIN_LEN = 3 + + +def _header_token_atoms(tokens: list[str]) -> frozenset[str]: + """ + 将表头 token 拆成稳定原子,供无锚点近亲模板互斥。 + + 核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。 + """ + atoms: set[str] = set() + for token in tokens: + normalized = re.sub(r"['’]", '', str(token).casefold()) + for part in re.split(r'[^a-z0-9]+', normalized): + if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS: + atoms.add(part) + return frozenset(atoms) + + +def _header_discriminator_atoms_conflict( + *, + signature: dict[str, Any] | None, + observed: dict[str, Any], +) -> bool: + """签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。""" + if signature is None or not signature.get('table_patterns'): + return False + expected_tokens: list[str] = [] + for table in signature.get('table_patterns') or []: + if isinstance(table, dict): + expected_tokens.extend(str(item) for item in table.get('header_tokens') or []) + observed_tokens = [str(item) for item in observed.get('header_tokens') or []] + if not expected_tokens or not observed_tokens: + return False + return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens) + + def _score_column_topology( *, signature: dict[str, Any] | None, @@ -1025,7 +1095,8 @@ def _score_table_geometry( observed: dict[str, Any], profile: OrderCoordinateProfile, ) -> MatchDimensionResult: - """比对表区 bbox 中位数与容差。""" + """比对主表身份几何:顶边与左右宽度;忽略底边高度(MinerU 粘连备注会拉高 y1)。""" + _ = profile if signature is None: return MatchDimensionResult(state='unavailable', score=0.0) patterns = [item for item in signature.get('table_patterns') or [] if isinstance(item, dict)] @@ -1045,11 +1116,30 @@ def _score_table_geometry( if isinstance(tolerance, list) and len(tolerance) == 4 else [float(tolerance[0]) if isinstance(tolerance, list) and tolerance else 0.05] * 4 ) - best = max(best, _bbox_similarity(median, reference_bbox, tolerances=tolerances)) + best = max( + best, + _identity_table_geometry_similarity( + median, reference_bbox, tolerances=tolerances, + ), + ) score = round(best, 6) return MatchDimensionResult(state='matched' if score >= 0.65 else 'mismatched', score=score) +def _identity_table_geometry_similarity( + expected: list[float], observed: list[float], *, tolerances: list[float], +) -> float: + """只比较 x0/y0/x1(顶边+宽度);y1 不参与身份分,避免脏表高绑架模板匹配。""" + # indices: 0=x0, 1=y0, 2=x1, 3=y1(忽略) + identity_indices = (0, 1, 2) + hits = 0 + for index in identity_indices: + tolerance = float(tolerances[index]) if index < len(tolerances) else 0.05 + if abs(float(expected[index]) - float(observed[index])) <= tolerance: + hits += 1 + return round(hits / len(identity_indices), 6) + + def _score_page_structure( *, signature: dict[str, Any] | None, @@ -1140,15 +1230,6 @@ def _score_trusted_business_context( ) -def _bbox_similarity(expected: list[float], observed: list[float], *, tolerances: list[float]) -> float: - """分别使用 x0/y0/x1/y1 容差评估表区几何。""" - deltas = [abs(float(a) - float(b)) for a, b in zip(expected, observed)] - if not deltas: - return 0.0 - within = sum(1 for delta, tolerance in zip(deltas, tolerances) if delta <= tolerance) - return round(within / len(deltas), 6) - - def _observe_layout_features( *, layout: dict[str, Any], @@ -1157,6 +1238,8 @@ def _observe_layout_features( glyph_tables: dict[str, Any], page_glyphs: dict[str, Any], signature: dict[str, Any] | None, + termination_rules: list[dict[str, Any]] | None = None, + exclusion_regions: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: """从冻结 layout 聚合非敏感结构特征供维度比对。""" persisted = layout.get('matching_features') @@ -1183,6 +1266,16 @@ def _observe_layout_features( primary_bbox = _select_signature_primary_table_bbox( tables=tables, pages=pages, signature=signature, ) + # [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。 + primary_bbox = _clip_observed_primary_table_bbox( + primary_bbox, + tables=tables, + pages=pages, + page_glyphs=page_glyphs, + signature=signature, + termination_rules=termination_rules, + exclusion_regions=exclusion_regions, + ) header_tokens, column_centers, column_width_ratios = _observe_primary_table_header( glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, @@ -1371,6 +1464,96 @@ def _select_signature_primary_table_bbox( return best_bbox +def _clip_observed_primary_table_bbox( + primary_bbox: list[float] | None, + *, + tables: list[dict[str, Any]], + pages: dict[str, Any], + page_glyphs: dict[str, Any], + signature: dict[str, Any] | None, + termination_rules: list[dict[str, Any]] | None = None, + exclusion_regions: list[dict[str, Any]] | None = None, +) -> list[float] | None: + """对运行时主表框做业务行裁剪;无模板终止声明或定位失败时 fail-open。""" + if not isinstance(primary_bbox, list) or len(primary_bbox) != 4: + return primary_bbox + page_no, page = _page_for_primary_table_bbox( + primary_bbox, tables=tables, pages=pages, + ) + if not isinstance(page, dict): + return primary_bbox + glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) or [] + header_y1 = None + for pattern in (signature or {}).get('table_patterns') or []: + if not isinstance(pattern, dict): + continue + header_bbox = pattern.get('header_bbox') + if isinstance(header_bbox, list) and len(header_bbox) == 4: + try: + header_y1 = float(header_bbox[3]) + except (TypeError, ValueError): + header_y1 = None + break + clipped = clip_table_bbox_to_business_rows( + primary_bbox, + page=page, + glyphs=glyphs if isinstance(glyphs, list) else None, + header_y1=header_y1, + termination_rules=termination_rules, + exclusion_regions=exclusion_regions, + ) + return clipped if isinstance(clipped, list) else primary_bbox + + +def _profile_termination_rules(profile: OrderCoordinateProfile) -> list[dict[str, Any]]: + """汇总模板全部表区的终止规则,供主表几何裁剪复用抽取侧契约。""" + return [ + rule.model_dump() + for table in profile.table_regions + for rule in table.termination_rules + ] + + +def _profile_exclusion_regions(profile: OrderCoordinateProfile) -> list[dict[str, Any]]: + """汇总模板全部表区的排除框。""" + return [ + region.model_dump() + for table in profile.table_regions + for region in table.exclusion_regions + ] + + +def _page_for_primary_table_bbox( + primary_bbox: list[float], + *, + tables: list[dict[str, Any]], + pages: dict[str, Any], +) -> tuple[Any, dict[str, Any] | None]: + """按与主表框重叠最大的 layout 表定位页对象。""" + best: tuple[float, Any, dict[str, Any]] | None = None + for table in tables: + page_no = table.get('page_no') or 1 + page = pages.get(str(page_no)) or pages.get(page_no) + bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None + if not isinstance(page, dict) or not isinstance(bbox, dict): + continue + try: + raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')] + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + except (KeyError, TypeError, ValueError): + continue + if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]: + continue + normalized = raw if max(raw) <= 1 else [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height] + overlap = _bbox_overlap(primary_bbox, normalized) + if best is None or overlap > best[0]: + best = (overlap, page_no, page) + if best is None: + fallback = pages.get('1') or pages.get(1) + return 1, fallback if isinstance(fallback, dict) else None + return best[1], best[2] + + def _bbox_overlap(left: list[float], right: list[float]) -> float: """计算两个归一化矩形的 IoU,供签名表区与实际表选择使用。""" x0, y0 = max(left[0], right[0]), max(left[1], right[1]) @@ -1383,6 +1566,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float: _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+') +def _band_headers_match_signature( + *, band_tokens: list[str], signature: dict[str, Any] | None, +) -> bool: + """判断冻结表头带读到的 token 是否足以代表签名表头。 + + 只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”, + 直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行) + 需要回退到表体顶部的结构搜索。 + """ + expected = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_tokens') or [] + ] + if not expected or not band_tokens: + return False + observed = [str(token).casefold() for token in band_tokens] + matched = sum(1 for token in expected if token in observed) + return matched / len(expected) >= 0.5 + + def _observe_primary_table_header( *, glyph_tables: dict[str, Any], @@ -1391,7 +1596,13 @@ def _observe_primary_table_header( primary_bbox: list[float] | None, signature: dict[str, Any] | None, ) -> tuple[list[str], list[float], list[float]]: - """仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。""" + """从实际主表顶部观测表头,与签名生成保持同一证据口径。 + + 先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为, + 不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到 + 错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑), + 从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。 + """ if not primary_bbox or len(primary_bbox) != 4: return [], [], [] glyphs = page_glyphs.get('1') or page_glyphs.get(1) @@ -1419,11 +1630,28 @@ def _observe_primary_table_header( item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False) if _usable_observed_header_token(str(item.get('text') or '')) ][:32] - tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] - centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans] + band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] + band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans] table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001) - widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans] - return tokens, centers, widths + band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans] + # 固定带有效 → 直接沿用(对正常模板零影响)。 + if _band_headers_match_signature(band_tokens=band_tokens, signature=signature): + return band_tokens, band_centers, band_widths + # 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。 + candidates = [{ + 'bbox': primary_bbox, + 'header_candidates': _observe_header_candidates( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox, + ), + }] + selected = _select_persisted_header_candidate(candidates=candidates, signature=signature) + if selected is not None: + header, _ = selected + return ( + [str(token).casefold() for token in header['header_tokens']], + header['column_centers'], header['column_width_ratios'], + ) + return band_tokens, band_centers, band_widths def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None: diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py index 6625a69d..26a26c88 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py @@ -14,6 +14,15 @@ from typing import Any from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + LayoutBBox, + _absolute_relative_region, + _group_visual_rows, + _inside_horizontal_region, + _table_glyphs, + _text_in_horizontal_region, + coordinate_profile_character_candidates, +) _NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$') @@ -84,12 +93,14 @@ def validate_profile_parse_candidate( fields=header_bound, glyphs=glyphs, page=page, ) - # [STEP 2] Line 字段覆盖 + # [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报) line_fields = [ field for table in profile.table_regions for layout in table.line_layouts for field in layout.field_regions if field.scope == 'line' ] - line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page) + line_coverage = _line_region_coverage_shift_tolerant( + profile=profile, glyphs=glyphs, page=page, layout=layout, + ) # [STEP 3] 明细行数启发式 line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page) @@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None: return None +def _line_region_coverage_shift_tolerant( + *, + profile: OrderCoordinateProfile, + glyphs: list[dict[str, Any]], + page: dict[str, Any], + layout: dict[str, Any], +) -> dict[str, Any]: + """按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。 + + 核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体 + 纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致 + ``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段 + 区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。 + 此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行 + 做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。 + + Args: + profile: 当前候选 Profile(含 table_regions)。 + glyphs: 当前页冻结坐标字符。 + page: 当前页尺寸。 + layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。 + + Returns: + {coverage_ratio, empty_region_count, total_region_count}。 + """ + if not profile.table_regions: + return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} + line_fields = [ + field for table in profile.table_regions for layout_item in table.line_layouts + for field in layout_item.field_regions if field.scope == 'line' + ] + if not line_fields: + return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} + + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + # 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。 + primary_region = next( + (table for table in profile.table_regions if table.line_layouts), None, + ) + raw_table = _locate_overlapping_raw_table( + primary_region=primary_region, layout=layout, page=page, profile=profile, + ) + width, height = float(page['width']), float(page['height']) + table_region = primary_region.region.model_dump() if primary_region is not None else None + reference_page_frame = _reference_page_frame_mapping(profile, page) + reconstruction_page_bbox = { + 'x0': 0.0, 'y0': 0.0, + 'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width, + 'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height, + } + # 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。 + characters, _ = coordinate_profile_character_candidates( + table_region=table_region or {}, + page_size=page, reference_page_frame=reference_page_frame, + page_characters=glyphs if isinstance(glyphs, list) else None, + table_characters=( + page_glyph_tables.get(raw_table.get('table_id')) + if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list) + else None + ), + raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None), + table_id=(raw_table.get('table_id') if raw_table is not None else None), + page_no=1, coordinate_transform=None, allow_table_fallback=True, + ) + if not isinstance(characters, list) or not characters: + return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page) + + page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox) + glyphs_in_table = _table_glyphs(characters, page_bbox) + visual_rows = _group_visual_rows(glyphs_in_table) + non_empty = 0 + measurable = 0 + for field in line_fields: + relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region + if not isinstance(relative, dict): + continue + measurable += 1 + absolute = _absolute_relative_region(page_bbox, relative) + if _region_is_covered(visual_rows=visual_rows, region=absolute): + non_empty += 1 + total = measurable + return { + 'coverage_ratio': non_empty / total if total else 1.0, + 'empty_region_count': total - non_empty, + 'total_region_count': total, + } + + +def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None: + """读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。""" + reference = profile.reference_page_frames.get(1) + if reference is None: + return None + return reference.model_dump() if hasattr(reference, 'model_dump') else reference + + +def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any: + """将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。""" + if isinstance(value, LayoutBBox): + return value + return LayoutBBox.model_validate(value) + + +def _locate_overlapping_raw_table( + *, + primary_region: Any, + layout: dict[str, Any], + page: dict[str, Any], + profile: OrderCoordinateProfile, +) -> dict[str, Any] | None: + """在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。 + + 命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取, + 避免把无物理表的场景误判为已定位到明细表。 + """ + if primary_region is None: + return None + reference_page_frame = _reference_page_frame_mapping(profile, page) + width, height = float(page['width']), float(page['height']) + projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width + projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height + if projection_width <= 0 or projection_height <= 0: + return None + relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region + if not isinstance(relative, dict): + return None + try: + absolute_region = { + 'x0': float(relative['x0']) * projection_width, + 'y0': float(relative['y0']) * projection_height, + 'x1': float(relative['x1']) * projection_width, + 'y1': float(relative['y1']) * projection_height, + } + except (KeyError, TypeError, ValueError): + return None + best: dict[str, Any] | None = None + best_overlap = 0.0 + for raw_table in layout.get('tables') or []: + if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1: + continue + bbox = raw_table.get('bbox') + if not isinstance(bbox, dict): + continue + overlap_x = ( + min(float(bbox.get('x1', 0)), absolute_region['x1']) + - max(float(bbox.get('x0', 0)), absolute_region['x0']) + ) + overlap_y = ( + min(float(bbox.get('y1', 0)), absolute_region['y1']) + - max(float(bbox.get('y0', 0)), absolute_region['y0']) + ) + if overlap_x <= 0 or overlap_y <= 0: + continue + overlap_area = overlap_x * overlap_y + if overlap_area > best_overlap: + best_overlap = overlap_area + best = raw_table + return best + + +def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool: + """判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。""" + for band in visual_rows: + selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)] + if _text_in_horizontal_region(selected, region).strip(): + return True + return False + + def _estimate_line_count( *, profile: OrderCoordinateProfile, diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_signature.py b/backend/app/services/shipping_notice/document_layout/order_profile_signature.py index da1376b5..75c831b8 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_signature.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_signature.py @@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_signature.py 用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。 依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。 逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。 + 另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。 """ from __future__ import annotations @@ -17,6 +18,7 @@ from typing import Any from app.services.shipping_notice.document_layout.coordinate_region_text import ( positioned_token_spans, read_coordinate_region_text, + visual_glyph_rows, ) from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile, RelativeRegion from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID @@ -27,15 +29,162 @@ LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature' MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID # 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。 +# 最后一条只匹配「标签 + 显式分隔符/空白数字」的粘连值(如 Qty: 24、Qty 24), +# 不得误杀 Qty.Req / Qty Req 这类列名(点号或纯字母后缀不是业务值)。 _DYNAMIC_TOKEN_PATTERNS = ( re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'), re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'), re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE), re.compile(r'^\d+([.,]\d+)?$'), - re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE), + re.compile( + r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)' + r'(?:\s*[:#=\-]\s*\S+|\s+\d)', + re.IGNORECASE, + ), ) +def clip_table_bbox_to_business_rows( + bbox: list[float] | None, + *, + page: dict[str, Any], + glyphs: list[dict[str, Any]] | None, + header_y1: float | None = None, + termination_rules: list[dict[str, Any]] | None = None, + exclusion_regions: list[dict[str, Any]] | None = None, +) -> list[float] | None: + """ + 将主表 bbox 底边裁到业务明细结束处,去掉 MinerU 粘连的表外备注区。 + + 核心逻辑:只使用模板声明的 termination_rules 锚点文案与 exclusion_regions; + 在表框内、表头下方命中最早终止点则裁 y1。无模板声明或未命中时 fail-open。 + + Args: + bbox: 归一化 [x0, y0, x1, y1]。 + page: 含 width/height 的页对象。 + glyphs: 该页 page_glyphs。 + header_y1: 可选表头下沿(归一化)。 + termination_rules: 表区 termination_rules 的 dict 列表(含 anchor.text/match_mode/region)。 + exclusion_regions: 表区 exclusion_regions 的相对框 dict 列表。 + + Returns: + 裁剪后的 bbox,或无法裁剪时的原 bbox。 + """ + if not isinstance(bbox, list) or len(bbox) != 4: + return bbox + try: + x0, y0, x1, y1 = (float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3])) + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + except (TypeError, ValueError): + return bbox + if width <= 0 or height <= 0 or x1 <= x0 or y1 <= y0: + return bbox + + floor = float(header_y1) if header_y1 is not None else (y0 + max(0.02, (y1 - y0) * 0.08)) + floor = min(max(floor, y0), y1) + stop_ys: list[float] = [] + + for region in exclusion_regions or []: + if not isinstance(region, dict): + continue + try: + ey0 = float(region['y0']) + ex0, ex1 = float(region['x0']), float(region['x1']) + except (KeyError, TypeError, ValueError): + continue + if ey0 <= floor or ey0 >= y1: + continue + if ex1 < x0 or ex0 > x1: + continue + stop_ys.append(ey0) + + rules = [item for item in (termination_rules or []) if isinstance(item, dict)] + if rules and isinstance(glyphs, list) and glyphs: + for row in visual_glyph_rows(glyphs): + row_meta = _normalized_glyph_row(row, width=width, height=height) + if row_meta is None: + continue + row_y, row_x0, row_x1, text = row_meta + if row_y <= floor or row_y >= y1: + continue + if row_x1 < x0 or row_x0 > x1: + continue + if _row_matches_termination_rules( + text=text, row_y=row_y, table_bbox=[x0, y0, x1, y1], rules=rules, + ): + stop_ys.append(row_y) + + if not stop_ys: + return bbox + clipped_y1 = max(floor + 1e-3, min(stop_ys) - 0.008) + if clipped_y1 >= y1 - 1e-3: + return bbox + return [x0, y0, x1, round(clipped_y1, 6)] + + +def _normalized_glyph_row( + row: list[dict[str, Any]], *, width: float, height: float, +) -> tuple[float, float, float, str] | None: + """将视觉行折叠为归一化 y/x 范围与拼接文本。""" + xs: list[float] = [] + ys: list[float] = [] + texts: list[str] = [] + for glyph in row: + box = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None + if not box: + continue + try: + gx0, gy0, gx1, gy1 = float(box['x0']), float(box['y0']), float(box['x1']), float(box['y1']) + except (KeyError, TypeError, ValueError): + continue + xs.extend((gx0 / width, gx1 / width)) + ys.append(((gy0 + gy1) / 2) / height) + texts.append(str(glyph.get('text') or '')) + if not xs or not ys: + return None + return sum(ys) / len(ys), min(xs), max(xs), ''.join(texts) + + +def _row_matches_termination_rules( + *, + text: str, + row_y: float, + table_bbox: list[float], + rules: list[dict[str, Any]], +) -> bool: + """按模板 termination_rules 判断视觉行是否为业务表结束锚点。""" + compact = ' '.join(text.split()) + if not compact: + return False + compact_key = compact.casefold().replace(' ', '') + x0, y0, x1, y1 = table_bbox + for rule in rules: + anchor = rule.get('anchor') if isinstance(rule.get('anchor'), dict) else None + if not isinstance(anchor, dict): + continue + expected = str(anchor.get('text') or '').strip() + if not expected: + continue + region = anchor.get('region') + if isinstance(region, dict): + try: + # region 相对表区;换算到页面归一化 y 再约束命中带。 + ry0 = y0 + (y1 - y0) * float(region['y0']) + ry1 = y0 + (y1 - y0) * float(region['y1']) + except (KeyError, TypeError, ValueError): + continue + if not ry0 <= row_y <= ry1: + continue + mode = str(anchor.get('match_mode') or 'contains') + expected_key = expected.casefold().replace(' ', '') + if mode == 'exact': + if compact == expected or compact_key == expected_key: + return True + elif expected in compact or (expected_key and expected_key in compact_key): + return True + return False + + def build_layout_signature( *, definition: dict[str, Any], @@ -206,7 +355,10 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) -> for layout in sample_layouts: observed = _observe_sample_table( - layout, target_region=region, header_region=header_region, + layout, + target_region=region, + header_region=header_region, + table_region=table, ) if observed is None: continue @@ -280,6 +432,7 @@ def _build_field_relation_graph( def _observe_sample_table( layout: dict[str, Any], *, target_region: RelativeRegion, header_region: RelativeRegion | None, + table_region: Any | None = None, ) -> dict[str, Any] | None: """读取样本中与标注区域重叠最高的真实表格及其页级字符几何。""" tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] @@ -318,8 +471,25 @@ def _observe_sample_table( header_tokens, centers, widths = _header_observation( header_glyphs, page=page, bbox=bbox, ) + header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None + termination_rules = [ + rule.model_dump() if hasattr(rule, 'model_dump') else rule + for rule in (getattr(table_region, 'termination_rules', None) or []) + ] + exclusion_regions = [ + region.model_dump() if hasattr(region, 'model_dump') else region + for region in (getattr(table_region, 'exclusion_regions', None) or []) + ] + clipped = clip_table_bbox_to_business_rows( + bbox, + page=page, + glyphs=glyphs if isinstance(glyphs, list) else None, + header_y1=header_y1, + termination_rules=termination_rules or None, + exclusion_regions=exclusion_regions or None, + ) return { - 'bbox': bbox, + 'bbox': clipped if isinstance(clipped, list) else bbox, 'header_tokens': header_tokens, 'column_centers': centers, 'column_width_ratios': widths, @@ -528,7 +698,12 @@ def _split_header_tokens(text: str) -> list[str]: def _is_dynamic_token(token: str) -> bool: - """判断 token 是否像 PO/日期/数量等动态值。""" + """ + 判断 token 是否像 PO/日期/数量等动态值。 + + 核心逻辑:日期、料号型编码、纯数字,以及「Qty:/PO: + 值」粘连串视为动态; + Qty.Req 等列名不含显式分隔后的值或空白数字,不得判动态。 + """ compact = token.strip() if not compact or len(compact) <= 1: return True 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 2d753d23..6c3a2a49 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -1339,8 +1339,31 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None: raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE') -def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None: - """将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。""" +def promote_approved_suite_for_publish( + *, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str, + actor_id: int | None = None, +) -> None: + """将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。 + + 核心逻辑: + [STEP 1] 定位当前草稿 checksum 下已批准的盲测集;缺失时直接返回(生产调用方 + 已通过 assert_profile_publishable 门禁,此守卫仅防御测试夹具伪造凭证)。 + [STEP 2] 同一 Profile 行重复发布相同内容时(如人工将已发布模板重置为草稿后 + 再次发布),发布 checksum 由规范化负载确定性复现,历史提升套件仍占用 + (profile_id, profile_checksum) 唯一键。若占用者仍是有效发布凭证(approved 且 + 最近一次 Run 通过且 checksum 一致),则直接复用历史凭证:新草稿集转为 + superseded 以保留其运行历史供审计,不再重写 checksum,避免唯一键冲突。 + [STEP 3] 常规路径:重写套件与其 Run 的 checksum 为发布 checksum。 + + Args: + profile: 即将发布的 Profile ORM 记录(发布事务内调用,不自行提交)。 + draft_checksum: 发布前草稿定义的规范化 checksum。 + published_checksum: 本次发布冻结的正式 checksum。 + actor_id: 触发发布的管理员主键,用于审计;允许为空。 + + Returns: + 无返回值;套件状态变更随发布事务一并提交。 + """ suite = ShippingDocumentProfileTestSuite.query.filter_by( profile_id=profile.id, profile_checksum=draft_checksum, status='approved', ).one_or_none() @@ -1348,6 +1371,31 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, # isolated lifecycle tests from fabricating a quality credential by monkeypatch. if suite is None: return + # [STEP 2] 唯一键占用检查:发布 checksum 相同意味着定义、Schema 与 adapter 证据 + # 完全一致,历史凭证对本次发布同样有效,无需也不允许重写第二个套件。 + occupant = ShippingDocumentProfileTestSuite.query.filter_by( + profile_id=profile.id, profile_checksum=published_checksum, + ).one_or_none() + if occupant is not None and occupant.id != suite.id: + occupant_last_run = occupant.runs[-1] if occupant.runs else None + if ( + occupant.status == 'approved' and occupant_last_run is not None + and occupant_last_run.status == 'passed' + and occupant_last_run.profile_checksum == published_checksum + ): + suite.status = 'superseded' + _audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={ + 'suite_id': suite.id, 'reused_suite_id': occupant.id, + 'reason_code': 'republish_identical_content', + }) + return + # 占用者不是有效凭证(人工改动等异常数据):拒绝发布并给出可定位的错误码, + # 禁止静默覆盖或删除历史盲测证据。 + raise ConflictError( + 'Published checksum is already occupied by another test suite', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT', + details={'suite_id': occupant.id}, + ) suite.profile_checksum = published_checksum for run in suite.runs: if run.profile_checksum == draft_checksum: diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index fad92a0a..df6820d2 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -23,6 +23,7 @@ from app.models import ( ShippingOrderIntake, ShippingOrderSnapshot, ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.business_fingerprint import ( CONTENT_FINGERPRINT_VERSION, @@ -40,19 +41,35 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str lifecycle = str(get('lifecycle_status', '') or '').strip().lower() if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}: return 'closed' - upload = str(get('upload_status', '') or '').strip().lower() - if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'): + upload = None + try: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if not isinstance(task, dict) and has_verified_upload_success(task): + upload = 'uploaded' + except Exception: + upload = None + if upload == 'uploaded': return 'completed' return 'active' def is_irreversible_task(task: ShippingNotice) -> bool: """已 uploaded 或终态任务不可原地覆盖源文件。""" - upload_status = str(task.upload_status or '').strip().lower() - return upload_status in {'uploaded', 'succeeded', 'success'} + try: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + return has_verified_upload_success(task) + except Exception: + return False def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]: + candidate = ( + db.session.query(ShippingOrderCandidate) + .filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + if getattr(task, 'order_task_id', None) else None + ) return { 'task_no': task.task_no, 'document_version': int(task.document_version or 1), @@ -60,14 +77,29 @@ def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: lis 'matched_fields': list(matched_fields), 'lifecycle': classify_task_lifecycle(task), 'created_at': utc_iso(task.created_at), - 'content_fingerprint': task.content_fingerprint, - 'content_fingerprint_version': task.content_fingerprint_version, + 'content_fingerprint': getattr(candidate, 'content_fingerprint', None), + 'content_fingerprint_version': getattr(candidate, 'content_fingerprint_version', None), } +def _task_content_fingerprint(task: ShippingNotice) -> tuple[str | None, str | None]: + """从建单来源 Candidate 读取内容指纹;正式 Notice 不再保存该投影。""" + if not getattr(task, 'order_task_id', None): + return None, None + candidate = ( + db.session.query(ShippingOrderCandidate.content_fingerprint, ShippingOrderCandidate.content_fingerprint_version) + .filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) + return (candidate[0], candidate[1]) if candidate else (None, None) + + def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]: """比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。""" - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: return [] proposed = { @@ -158,10 +190,13 @@ def detect_duplicates_for_intake( if content_hash: hash_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id) + .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.source_content_hash == content_hash, - ShippingNotice.lifecycle_status == 'active', + ShippingOrderTask.user_id == int(intake.user_id), + FileAsset.content_hash == content_hash, + ShippingOrderTask.lifecycle_status == 'active', ) .order_by(ShippingNotice.id.desc()) .limit(10) @@ -182,10 +217,12 @@ def detect_duplicates_for_intake( if fingerprint and strength in {'strong', 'medium'}: fp_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, + ShippingOrderTask.user_id == int(intake.user_id), + ShippingOrderCandidate.business_fingerprint == fingerprint, + ShippingOrderCandidate.fingerprint_version == version, ) .order_by(ShippingNotice.id.desc()) .limit(20) @@ -206,12 +243,13 @@ def detect_duplicates_for_intake( if matches and status == 'none': comparable = [ task for task in fp_tasks - if task.content_fingerprint and task.content_fingerprint_version == content_version + if _task_content_fingerprint(task)[0] + and _task_content_fingerprint(task)[1] == content_version ] if content_fingerprint and comparable: status = ( 'same_business_content' - if any(task.content_fingerprint == content_fingerprint for task in comparable) + if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable) else 'possible_revision' ) else: @@ -229,11 +267,13 @@ def detect_duplicates_for_intake( # 弱指纹:仅标记疑似,不按 active 强阻断 fp_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ShippingNotice.lifecycle_status == 'active', + ShippingOrderTask.user_id == int(intake.user_id), + ShippingOrderCandidate.business_fingerprint == fingerprint, + ShippingOrderCandidate.fingerprint_version == version, + ShippingOrderTask.lifecycle_status == 'active', ) .order_by(ShippingNotice.id.desc()) .limit(5) @@ -498,11 +538,10 @@ def detect_duplicates_for_candidate( if content_hash: hash_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.source_content_hash == content_hash, - ShippingNotice.lifecycle_status == 'active', - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id) + .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), FileAsset.content_hash == content_hash, ShippingOrderTask.lifecycle_status == 'active') ) if skipped_ids: hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) @@ -522,11 +561,9 @@ def detect_duplicates_for_candidate( if fingerprint and strength in {'strong', 'medium'}: fp_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version) ) if skipped_ids: fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) @@ -545,12 +582,13 @@ def detect_duplicates_for_candidate( if matches and status == 'none': comparable = [ task for task in fp_tasks - if task.content_fingerprint and task.content_fingerprint_version == content_version + if _task_content_fingerprint(task)[0] + and _task_content_fingerprint(task)[1] == content_version ] if content_fingerprint and comparable: status = ( 'same_business_content' - if any(task.content_fingerprint == content_fingerprint for task in comparable) + if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable) else 'possible_revision' ) else: @@ -564,12 +602,9 @@ def detect_duplicates_for_candidate( elif fingerprint and strength == 'weak' and status == 'none': weak_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ShippingNotice.lifecycle_status == 'active', - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version, ShippingOrderTask.lifecycle_status == 'active') ) if skipped_ids: weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) 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 aa4f11f2..e7bb63b7 100644 --- a/backend/app/services/shipping_notice/email_allocation_table_parser.py +++ b/backend/app/services/shipping_notice/email_allocation_table_parser.py @@ -3,6 +3,8 @@ 依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。 逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实 仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。 +非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。 +多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。 """ from __future__ import annotations @@ -31,10 +33,46 @@ def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, An } +def _supplement_row_identity(row: dict[str, Any]) -> tuple[str, str, str] | None: + """返回补充行跨表去重键;无次级身份时返回 None(不可安全覆盖,原样保留)。 + + 核心逻辑:PO 必选;次级键按 reservation_id → allocation_id → part_number → + customer_part_number 择一,避免把同 PO 不同明细误合成一行。 + + Args: + row: 已规范化的补充行(含 PO 与可选明细身份字段)。 + + Returns: + ``(po, field_code, value)``;缺 PO 或无可覆盖次级键时为 None。 + """ + po_number = normalize_po_number(row.get('customer_po_number') or row.get('po_number')) + if not po_number: + return None + po_key = po_number.upper() + for field_code in ('reservation_id', 'allocation_id', 'part_number', 'customer_part_number'): + value = str(row.get(field_code) or '').strip().upper() + if value: + return (po_key, field_code, value) + return None + + def _normalize_schema_row( values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str], ) -> dict[str, Any] | None: - """按冻结 Schema 规范化并校验 EML 单元格;非法字段不参与任何补充裁决。""" + """按冻结 Schema 规范化并校验 EML 单元格;非法非 PO 字段跳过,不拖垮整行。 + + 核心逻辑:PO 仍是行身份门槛;其余字段解析/校验失败只记 + ``email_supplement_field_invalid`` 并省略该字段,避免可选列(如 PO Date) + 非法时把 Reservation / 库存源线索一并丢掉。 + + Args: + values: 表头映射后的 field_code → 原始单元格文本。 + schema_definition: Run 冻结 Schema。 + issues: 可追加的问题码列表(调用方持有,本函数原地写入)。 + + Returns: + 规范化后的补充行;缺有效 PO 时返回 None。 + """ configs = _schema_configs(schema_definition) normalized: dict[str, Any] = {} for field_code, raw_value in values.items(): @@ -42,14 +80,15 @@ def _normalize_schema_row( if config is None: normalized[field_code] = raw_value continue + # [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后由 po 门槛统一拒行。 try: value = normalize_order_field_value(raw_value, config) except Exception: issues.append('email_supplement_field_invalid') - return None + continue if value is None or not validate_order_field_value(value, config): issues.append('email_supplement_field_invalid') - return None + continue normalized[field_code] = value po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number' po_number = normalize_po_number(normalized.get(po_code)) @@ -128,10 +167,23 @@ def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]: def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]: - """输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。""" + """输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。 + + 核心逻辑:按 HTML 出现顺序扫描全部可映射分配表;同行身份键以先到(更新)为准, + 旧表仅补全新表未覆盖的行,避免局部修订丢行或与旧单价假冲突。 + + Args: + html_tables: Intake 清洗后的顶层 HTML table 片段列表(文档顺序)。 + content_hash: 正文 Document 内容哈希,用于稳定 cell_id。 + schema_definition: Run 冻结 Schema。 + + Returns: + email-supplement.v1 结果(rows / issues / version)。 + """ result = empty_email_supplement_result() rows: list[dict[str, Any]] = [] issues: list[str] = [] + seen_identities: set[tuple[str, str, str]] = set() for table_index, html in enumerate(html_tables): try: grid = parse_html_grid(str(html or ''), table_id=f'email-supplement:{content_hash}:{table_index}') @@ -161,10 +213,18 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, ) if normalized is None: continue - rows.append({ + row = { **normalized, 'evidence': evidence, 'table_index': table_index, 'row_index': row_index, - }) + } + # [STEP] 有身份键则先到为准;无次级键无法跨表覆盖,整行保留。 + identity = _supplement_row_identity(row) + if identity is not None: + if identity in seen_identities: + issues.append('email_supplement_older_row_superseded') + continue + seen_identities.add(identity) + rows.append(row) result.update({'rows': rows, 'issues': sorted(set(issues))}) return result diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index 2babdf63..f8bc8091 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -570,7 +570,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), - 'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), + 'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), 'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'), @@ -613,7 +613,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'), 'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'), 'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'), - 'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'), + 'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'), } diff --git a/backend/app/services/shipping_notice/excel_template.py b/backend/app/services/shipping_notice/excel_template.py index cddbc91f..53f78b5a 100644 --- a/backend/app/services/shipping_notice/excel_template.py +++ b/backend/app/services/shipping_notice/excel_template.py @@ -36,7 +36,7 @@ ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'consta ALLOWED_ROW_MODES = {'header', 'line'} ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'} ALLOWED_SYSTEM_FACTS = { - 'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'export_sequence', + 'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'notice_line_no', } diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 9f0835ec..2e11c9b1 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -4,7 +4,9 @@ services/shipping_notice/export.py 用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。 依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。 逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板; - 在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费; + 导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配; + Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败; + 在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。 订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。 """ @@ -29,16 +31,55 @@ from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, ShippingNoticeLine, + ShippingNoticeLineInventoryMatch, ShippingInventoryField, ShippingInventorySource, ShippingOrderSnapshot, ShippingOrderField, ShippingNotice, + ShippingOrderTask, + ShippingCustomer, ) from app.path_utils import resolve_backend_relative_path from app.services.file_assets.storage import file_asset_storage +def _notice_source_code(task: ShippingNotice) -> str | None: + """返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。""" + task_id = getattr(task, 'order_task_id', None) + if task_id is None: + return None + task_id = int(task_id) + codes = [ + str(row[0]).strip().upper() + for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter( + ShippingNoticeLineInventoryMatch.task_id == task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result == 'matched', + ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None), + ).distinct().all() + if row[0] + ] + return codes[0] if len(codes) == 1 else None + + +def _notice_inventory_file_id(task: ShippingNotice) -> int | None: + """从 Notice 行级匹配读取本次导出的唯一库存文件。""" + task_id = getattr(task, 'order_task_id', None) + if task_id is None: + return None + task_id = int(task_id) + ids = [ + int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter( + ShippingNoticeLineInventoryMatch.task_id == task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result == 'matched', + ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + ).distinct().all() + ] + return ids[0] if len(ids) == 1 else None + + def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None: """ 确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。 @@ -73,16 +114,7 @@ def _storage_root() -> Path: def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice: - """后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。""" - if notice.order_snapshot_id: - return notice - if notice.order_task_id: - source = ShippingNotice.query.filter( - ShippingNotice.order_task_id == int(notice.order_task_id), - ShippingNotice.order_snapshot_id.isnot(None), - ).order_by(ShippingNotice.id.asc()).first() - if source is not None: - return source + """返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。""" return notice @@ -90,7 +122,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di """从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。""" from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked assert_task_not_supersession_blocked(task) - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于库存匹配的冻结订单快照') fields = (snapshot.schema_version.definition_json or {}).get('fields') or [] @@ -122,9 +156,10 @@ def _system_fact( task: ShippingNotice, key: str, *, - export_sequence: int | None = None, excel_business_no: str | None = None, notice_no: str | None = None, + notice_line_no: str | None = None, + notice_line_warehouse_id: str | None = None, export_date: date | None = None, ) -> Any: """ @@ -133,18 +168,16 @@ def _system_fact( Args: task: 发货任务。 key: 系统事实键;仅允许白名单内键。 - export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。 - Returns: 对应系统事实值;未知键返回 None。 """ values = { 'task_no': notice_no or task.task_no, 'business_no': notice_no or excel_business_no or task.business_no, - 'warehouse_id': task.inventory_warehouse_id, - 'inventory_source_code': task.inventory_source_code, + 'warehouse_id': notice_line_warehouse_id, + 'inventory_source_code': _notice_source_code(task), 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), - 'export_sequence': export_sequence, + 'notice_line_no': notice_line_no, } return values.get(key) @@ -164,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo ) +def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None: + """ + 从表头可写的 Notice 行推导唯一 Warehouse ID。 + + 核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头, + 多库位冲突时失败,避免把某一行的库位误写到整单表头。 + + Args: + notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。 + + Returns: + 唯一非空库位码;全部为空时返回 None。 + + Raises: + ValueError: 多行存在多个不同库位。 + """ + warehouses = { + str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper() + for line in (notice_lines or []) + if str(getattr(line, 'inventory_warehouse_id', None) or '').strip() + } + if len(warehouses) > 1: + raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头') + if len(warehouses) == 1: + return next(iter(warehouses)) + return None + + def _format_value(value: Any, formatter: str) -> Any: """应用发布契约允许的确定性格式化器。""" if value is None: @@ -191,9 +252,11 @@ def _format_value(value: Any, formatter: str) -> Any: def _mapping_value( mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], - header_values: dict[str, Any] | None = None, export_sequence: int | None = None, + header_values: dict[str, Any] | None = None, excel_business_no: str | None = None, notice_no: str | None = None, + notice_line_no: str | None = None, + notice_line_warehouse_id: str | None = None, export_date: date | None = None, field_id_by_code: dict[str, str] | None = None, ) -> Any: @@ -201,9 +264,7 @@ def _mapping_value( 按映射来源类型读取值;未知来源已在模板发布时被拒绝。 核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实; - export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。 - 项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 → - 导出行序号),与 UI 展示同一口径,禁止此处另造回退链。 + 通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。 Args: mapping: 已发布模板映射项。 @@ -211,7 +272,6 @@ def _mapping_value( order_values: 当前行或表头订单字段值(field_id 为键)。 inventory_values: 当前行库存字段值。 header_values: 明细行模式下可回退的表头字段。 - export_sequence: 本次导出行序号(1..N)。 field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。 Returns: @@ -224,13 +284,7 @@ def _mapping_value( field = db.session.get(ShippingOrderField, key) if key else None field_code = str(field.field_code or '') if field else '' if value in (None, '') and field_code == 'line_no': - from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no - - value = resolve_order_line_no( - field_values=order_values, - field_id_by_code=field_id_by_code, - fallback_sequence=export_sequence, - )['value'] + value = notice_line_no if value is None and mapping.get('row_mode') == 'line' and header_values is not None: value = header_values.get(key) elif kind == 'inventory_field': @@ -238,13 +292,12 @@ def _mapping_value( elif kind == 'system_fact': value = _system_fact( task, key, - export_sequence=export_sequence if key == 'export_sequence' else None, excel_business_no=excel_business_no, notice_no=notice_no, + notice_line_no=notice_line_no, + notice_line_warehouse_id=notice_line_warehouse_id, export_date=export_date, ) - if key == 'export_sequence' and value is None: - value = order_values.get('__export_sequence') else: value = key # 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串; @@ -263,6 +316,50 @@ def _match_text(value: Any) -> str: return str(value).strip().casefold() +def _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines: list[dict[str, Any]], + *, + inventory_field_keys: list[str], + wanted_keys: set[tuple[str, ...]], +) -> list[dict[str, Any]]: + """ + 仅保留与本单导出行 match_keys 命中的库存行。 + + 核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入 + 逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。 + + Args: + inventory_lines: 活动库存快照行。 + inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。 + wanted_keys: 本单导出行规范化后的键元组集合。 + + Returns: + 子集库存行;无候选时为空列表。 + """ + if not inventory_lines or not inventory_field_keys or not wanted_keys: + return [] + return [ + row for row in inventory_lines + if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys + ] + + +def _wanted_order_match_keys( + order_lines: list[dict[str, Any]], + *, + order_field_ids: list[str], +) -> set[tuple[str, ...]]: + """从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。""" + wanted: set[tuple[str, ...]] = set() + if not order_lines or not order_field_ids: + return wanted + for order_line in order_lines: + key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids) + if all(key): + wanted.add(key) + return wanted + + def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]: """返回模板直接引用的库存字段 ID,用于多命中一致性验证。""" raw_ids = { @@ -447,13 +544,20 @@ def _filename( if not pattern: raise ValueError('发货 Excel 文件名规则未配置') now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S') + owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task + customer_short_code = '' + if isinstance(owner, ShippingOrderTask): + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + facts = customer_resolution_facts(owner) + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None + customer_short_code = str(getattr(customer, 'short_code', None) or '') values = { 'task_no': notice_no or task.task_no, 'business_no': notice_no or excel_business_no or task.business_no or task.task_no, - 'source_code': task.inventory_source_code or '', + 'source_code': _notice_source_code(task) or '', 'ts': now, 'date': now[:8], - 'customer_short_code': task.customer_short_code_snapshot or '', + 'customer_short_code': customer_short_code, 'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '', 'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '', } @@ -474,7 +578,7 @@ def _input_checksum( 'task_id': task.id, 'source_id': source.id, 'template_id': template.id, 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, - 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, + 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task), 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, 'notice_id': notice_id, } @@ -499,24 +603,22 @@ def generate_shipment_excel( from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked + # OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。 + from app.models import ShippingOrderTask + if isinstance(task, ShippingOrderTask): + from app.services.shipping_notice.shipping_notice_creation_service import ( + create_shipping_notice_after_inventory_gate, + ) + task = create_shipping_notice_after_inventory_gate(task) if not task_is_active(task): raise ValueError('已作废或归档的任务不能生成发货 Excel') assert_task_not_supersession_blocked(task) assert_notice_has_no_export_artifact(task) # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 - source_code = str(task.inventory_source_code or '').strip().upper() + source_code = str(_notice_source_code(task) or '').strip().upper() source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: - # [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None, - # 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。 - first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter( - ShippingNoticeLineInventoryMatch.task_id == task.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result == 'matched', - ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None), - ).limit(1).first() - source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else '' - source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None + source = None if source is None: raise ValueError('库存源不存在或已停用,不能生成发货 Excel') template = source.excel_template @@ -528,13 +630,10 @@ def generate_shipment_excel( mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] if not mappings: raise ValueError('发货 Excel 模板没有已发布的字段映射') - # Fixed Sources receive task Warehouse ID from configuration; dynamic Sources - # resolve it only after Reservation ID + Part Number matches. This requirement - # applies only when the published template actually consumes that system fact. - if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip(): - raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel') source_notice = _source_notice_for_order_facts(task) - snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于导出的冻结订单快照') header_values, all_line_values = order_field_id_values(task) @@ -590,7 +689,7 @@ def generate_shipment_excel( ) except ConflictError: raise - # [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。 + # [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。 line_values = [] for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)): if line.id not in available_line_ids: @@ -598,12 +697,40 @@ def generate_shipment_excel( row = dict(values) row['__order_line_index'] = source_index line_values.append(row) - for index, row in enumerate(line_values, start=1): - row['__export_sequence'] = index from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution - # [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 + # [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part) + # 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。 inventory_lines = resolve_inventory_lines_for_execution(source_notice) + if (line_inventory_fields or header_inventory_fields) and match_keys and line_values: + from app.models import ShippingInventoryField + + match_field_ids = { + int(item.get('inventory_field_id')) + for item in match_keys + if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit() + } + catalog = { + str(item.id): str(item.id) + for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all() + } if match_field_ids else {} + order_field_ids: list[str] = [] + inventory_field_keys: list[str] = [] + for item in match_keys: + if not isinstance(item, dict): + continue + inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip()) + if not inv_key: + continue + order_field_ids.append(str(item.get('order_field_id') or '')) + inventory_field_keys.append(inv_key) + if order_field_ids and inventory_field_keys: + wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids) + inventory_lines = _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines, + inventory_field_keys=inventory_field_keys, + wanted_keys=wanted_keys, + ) release_overrides_by_line = _release_overrides_for_export_lines( line_values=line_values, release_overrides_by_source_line=release_overrides_by_source_line, @@ -656,15 +783,32 @@ def generate_shipment_excel( } for sheet, start_row in data_start_rows.items(): _clear_template_data_rows(wb[sheet], start_row) + # [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。 + notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( + ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), + ).all() + header_warehouse_id: str | None = None + header_warehouse_resolved = False for mapping in mappings: ws = wb[mapping['sheet']] start_row = int(mapping['start_row']) column = int(mapping['target_column']) if mapping['row_mode'] == 'header': + # PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。 + mapping_warehouse_id = None + if _template_requires_system_warehouse_id([mapping]): + if not header_warehouse_resolved: + header_warehouse_id = _unique_notice_warehouse_id(notice_lines) + header_warehouse_resolved = True + if not header_warehouse_id: + raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头') + mapping_warehouse_id = header_warehouse_id ws.cell(start_row, column).value = _mapping_value( mapping, task=task, order_values=header_values, inventory_values=header_inventory, excel_business_no=excel_business_no, export_date=export_date, + notice_line_no=None, + notice_line_warehouse_id=mapping_warehouse_id, field_id_by_code=field_id_by_code, ) continue @@ -675,7 +819,16 @@ def generate_shipment_excel( ws.cell(start_row + index, column).value = _mapping_value( mapping, task=task, order_values=order_line, inventory_values=inventory_line, header_values=header_values, - export_sequence=int(order_line.get('__export_sequence') or (index + 1)), + notice_line_no=( + int(notice_lines[index].line_no) + if index < len(notice_lines) and notice_lines[index].line_no is not None + else None + ), + notice_line_warehouse_id=( + notice_lines[index].inventory_warehouse_id + if index < len(notice_lines) + else None + ), excel_business_no=excel_business_no, export_date=export_date, field_id_by_code=field_id_by_code, @@ -691,7 +844,7 @@ def generate_shipment_excel( artifact_no=artifact_no, task_id=task.id, template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, - inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, + inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task), input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, notice_id=int(task.id), diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index 117bac2c..f44c6d5d 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -37,7 +37,8 @@ def _select_tasks( tasks = [] for task_no in normalized_tasks: task = get_task_for_user(task_no, user_id) - if task is None or ( + # 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。 + if not isinstance(task, ShippingNotice) or ( require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper() ): raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') @@ -61,7 +62,6 @@ def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExpo artifact = ShippingExportArtifact.query.filter( ShippingExportArtifact.task_id == task.id, ShippingExportArtifact.status.in_({'ready', 'uploaded'}), - ShippingExportArtifact.file_path == task.export_file_path, ).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first() if artifact is not None: result[int(task.id)] = [artifact] diff --git a/backend/app/services/shipping_notice/field_impact_analysis.py b/backend/app/services/shipping_notice/field_impact_analysis.py index 32753e86..3e74806c 100644 --- a/backend/app/services/shipping_notice/field_impact_analysis.py +++ b/backend/app/services/shipping_notice/field_impact_analysis.py @@ -317,3 +317,60 @@ def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[ 'warnings': warnings, 'can_publish': not blocked, } + + +def _definition_field_code_map(definition: dict[str, Any] | None) -> dict[str, str]: + """提取版本定义中 field_id → field_code 映射,用于字段语义键跨版本一致性校验。""" + if not isinstance(definition, dict): + return {} + result: dict[str, str] = {} + for item in (definition.get('fields') or []): + if not isinstance(item, dict): + continue + field_id = str(item.get('field_id') or '').strip() + field_code = str(item.get('field_code') or '').strip() + if field_id and field_code: + result[field_id] = field_code + return result + + +def analyze_published_field_code_changes( + previous_definition: dict[str, Any] | None, + next_definition: dict[str, Any] | None, +) -> dict[str, Any]: + """ + 已发布 field_code 不可变门禁:同一 field_id 不应在下一发布版本中更换 field_code。 + + 核心逻辑:只比较上一已发布版本与当前草稿「同一 field_id」的 field_code 是否变化; + 同一 field_code 漂移到新 field_id(废弃旧字段 + 新建)属于合法路径,不阻断。 + 仅在语义键被重命名时阻断,要求走「退役 + 新建」而非原地改名,保证 field_code 是 + 跨版本稳定引用锚点(供身份识别 resolver 等按语义键匹配)。 + + Args: + previous_definition: 上一已发布版本 definition;无则视为首次发布,不校验。 + next_definition: 即将发布的草稿 definition。 + + Returns: + 含 blocked、changed(field_id / previous_field_code / next_field_code)与 + changed_field_ids 的字典;changed 为空时 can_publish=True。 + """ + if previous_definition is None: + return {'blocked': False, 'changed': [], 'changed_field_ids': [], 'can_publish': True} + previous_map = _definition_field_code_map(previous_definition) + next_map = _definition_field_code_map(next_definition) + changed: list[dict[str, Any]] = [] + for field_id in sorted(set(previous_map) & set(next_map)): + previous_code = previous_map[field_id] + next_code = next_map[field_id] + if previous_code != next_code: + changed.append({ + 'field_id': field_id, + 'previous_field_code': previous_code, + 'next_field_code': next_code, + }) + return { + 'blocked': bool(changed), + 'changed': changed, + 'changed_field_ids': [item['field_id'] for item in changed], + 'can_publish': not changed, + } diff --git a/backend/app/services/shipping_notice/freight_cancellation_service.py b/backend/app/services/shipping_notice/freight_cancellation_service.py index b7bf5c5e..51d6ce72 100644 --- a/backend/app/services/shipping_notice/freight_cancellation_service.py +++ b/backend/app/services/shipping_notice/freight_cancellation_service.py @@ -16,8 +16,9 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent +from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.tool_common import task_event_task_id def complete_freight_cancellation( @@ -59,11 +60,16 @@ def complete_freight_cancellation( old.voided_at = datetime.utcnow() old.voided_by_id = int(actor_id) old.void_reason = 'freight_cancellation_completed' - if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required': - new.lifecycle_status = 'active' - new.pending_human_reason = None + # Notice 不再承载旧工作流阻断字段;解除修订阻断时更新其 OT 生命周期, + # 由 OT 的 Gate/状态投影重新计算当前工作面。 + new_owner = ( + db.session.get(ShippingOrderTask, int(new.order_task_id)) + if new.order_task_id is not None else None + ) + if new_owner is not None and new_owner.status == 'blocked': + new_owner.status = 'processing' db.session.add(ShippingTaskEvent( - task_id=old.id, + task_id=task_event_task_id(old), event_type='freight_cancellation_completed', actor_id=actor_id, detail_json={ @@ -74,7 +80,7 @@ def complete_freight_cancellation( }, )) db.session.add(ShippingTaskEvent( - task_id=new.id, + task_id=task_event_task_id(new), event_type='supersession_unblocked', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}, @@ -109,12 +115,19 @@ def complete_freight_cancellation( def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]: """构造取消处置前后快照(白名单字段)。""" + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + artifact = latest_export_artifact(task) + owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if task.order_task_id is not None else None + ) return { 'task_no': str(task.task_no), 'lifecycle_status': str(task.lifecycle_status or ''), - 'export_file_name': task.export_file_name, + 'export_file_name': getattr(artifact, 'file_name', None), 'void_reason': task.void_reason, - 'pending_human_reason': task.pending_human_reason, + 'owner_lifecycle_status': getattr(owner, 'lifecycle_status', None), + 'owner_void_reason': getattr(owner, 'void_reason', None), } @@ -150,11 +163,10 @@ def mark_cancelled_task_readonly( if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}: task.lifecycle_status = 'pending_void' task.void_reason = reason_text - task.pending_human_reason = 'pending_void' # co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。 after = _task_cancel_snapshot(task) db.session.add(ShippingTaskEvent( - task_id=int(task.id), + task_id=task_event_task_id(task), event_type='task_pending_void', actor_id=int(actor_id), detail_json={ diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index a7e87bba..e116e82c 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -1,15 +1,16 @@ """ services/shipping_notice/fulfillment_workflow.py -用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与自动串联编排。 +用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。 依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、 inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、 tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 -逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match; +逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload, + 由 ProcessGate complete→enqueue 独立 artifact/freight Attempt;遗留非 Gate 路径仅 + submit auto_progress(artifact_generation); STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel; AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警); - 开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传; 工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件; upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认); RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产; @@ -28,10 +29,13 @@ from flask import current_app from app import db from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch -from app.services.shipping_notice.constants import CP_UPLOADED +from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask +from app.services.shipping_notice.constants import POSITION_UPLOADED from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values -from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution +from app.services.shipping_notice.inventory_file_store import ( + active_inventory_file_for_task, + resolve_inventory_lines_for_execution, +) from app.services.shipping_notice.inventory_workflow import ( ensure_inventory, parse_inventory_lines, @@ -56,6 +60,8 @@ from app.services.shipping_notice.reservation_gate import task_reservation_gate_ from app.services.shipping_notice.task_field_gate import field_conflict_gate_response from app.services.shipping_notice.upload_attempt_service import ( complete_attempt, + has_verified_upload_success, + latest_export_artifact, record_manual_upload, start_rpa_attempt, ) @@ -75,6 +81,70 @@ from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.task_disposition_service import task_execution_block_reason +def _single_candidate_source_code(task: ShippingNotice) -> str | None: + """返回当前 CandidateSet 的唯一源;多源由行级匹配事实决定,不能伪造任务级源。""" + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_codes = task_frozen_inventory_source_codes(task) + return source_codes[0] if len(source_codes) == 1 else None + + +def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask: + """将正式 Notice 输入解析为 OT owner;流程错误事实统一写入 OT。""" + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id: + owner = db.session.get(ShippingOrderTask, int(order_task_id)) + if owner is not None: + return owner + return task + + +def _set_workflow_error(task: ShippingNotice | ShippingOrderTask, message: str | None) -> None: + """写入流程错误;正式 Notice 通过关联 OT 承接,不写 Notice 已删除列。""" + owner = _workflow_owner(task) + if hasattr(owner, 'error_message'): + owner.error_message = message + + +def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None: + """读取流程错误;正式 Notice 通过关联 OT 承接。""" + return getattr(_workflow_owner(task), 'error_message', None) + + +def _resolved_ok_source_codes(task: ShippingNotice) -> list[str]: + """从当前行级 Match 派生已满足库存源,禁止读取已废弃的 Task JSON 投影。""" + rows = _current_line_results(task) + return sorted({ + str(row.get('resolved_inventory_source_code') or '').strip() + for row in rows + if str(row.get('disposition') or row.get('match_result') or '').strip().lower() == 'matched' + and str(row.get('resolved_inventory_source_code') or '').strip() + }) + + +def _current_export_artifact(task: ShippingNotice): + """获取当前有效导出 Artifact;履约流程禁止读取 Notice 的旧文件投影。""" + return latest_export_artifact(task) + + +def _export_file_path(task: ShippingNotice) -> str | None: + artifact = _current_export_artifact(task) + return str(artifact.file_path) if artifact is not None and artifact.file_path else None + + +def _export_file_name(task: ShippingNotice) -> str | None: + artifact = _current_export_artifact(task) + return str(artifact.file_name) if artifact is not None and artifact.file_name else None + + +def _upload_status(task: ShippingNotice) -> str | None: + """Notice 面 upload_status:经统一投影,成功只返回 uploaded。""" + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + return project_notice_upload_status(task) + + def _cfg_bool(key: str, default: bool = False) -> bool: """ 读取布尔配置;键缺失时返回 default(调用方须与 settings 默认值对齐)。 @@ -116,6 +186,8 @@ def _rpa_callback_success(value: Any) -> bool: # [BE-05] RPA 绿色 DOM 成功证据允许的 kind 白名单(与 freight_rpa_worker 对齐)。 _RPA_SUCCESS_EVIDENCE_KINDS = frozenset({ 'configured_success_selector', + 'crane_order_status_dom', + 'dsv_upload_success_dom', 'dsv_history_green_dom', 'green_success_dom', }) @@ -286,7 +358,7 @@ def _reservation_gate_response( **serialize_task_for_tool(task), "reservation_id_required": detail, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, forbidden_next_tools=forbidden_next_tools, ) @@ -382,7 +454,8 @@ def _trigger_freight_upload_rpa( # 校验或人工确认(mark_manual_uploaded)兜底,避免“点了没反应”。attempts/max_attempts # 仍用于运行中提示文案。 - if not task.export_file_path: + artifact = _current_export_artifact(task) + if artifact is None or not artifact.file_path: return tool_response( status='failed', task=task, @@ -400,7 +473,7 @@ def _trigger_freight_upload_rpa( if isinstance(exc.details, dict): detail = str(exc.details.get('detail_message') or '').strip() apply_task_transition(task, TaskTransition.WAITING_UPLOAD) - task.error_message = detail or str(exc.message or exc) + _set_workflow_error(task, detail or str(exc.message or exc)) log_task_event( task, 'upload_rpa_not_ready', @@ -410,7 +483,7 @@ def _trigger_freight_upload_rpa( return tool_response( status='needs_human', task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), stop_agent_turn=True, next_required_action='货代上传 RPA 未就绪:请启动 Worker、核对凭据与共享目录后重试,或人工上传并登记凭据。', @@ -442,16 +515,16 @@ def _trigger_freight_upload_rpa( upload_source = dict(rpa_source) upload_config = upload_source.get('upload_config_json') if isinstance(upload_source, dict) else None if connector_type not in {'dbs', 'crane'} or not isinstance(upload_config, dict) or not upload_config.get('enabled'): - task.error_message = ( + _set_workflow_error(task, ( '该连接未启用“发货 Excel 自动上传”,请管理员先在“系统连接”完成上传配置并启用后再触发,' '或人工下载 Excel 后上传并登记凭据。' - ) + )) log_task_event(task, 'upload_rpa_config_missing', {'connector_type': connector_type or None}) db.session.commit() return tool_response( status='needs_human', task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), stop_agent_turn=True, next_required_action='请在“系统连接”补齐上传配置并启用,或人工上传。', @@ -461,7 +534,7 @@ def _trigger_freight_upload_rpa( queue_path, trigger_path, callback_id = write_upload_trigger( task.task_no, - str(task.export_file_path), + str(artifact.file_path), payload={ 'mode': str(body.get('mode') or 'auto'), }, @@ -492,10 +565,7 @@ def _trigger_freight_upload_rpa( apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING) # 业务决定:重新发起 RPA 上传时立即把 upload_status 置为 uploading 并清空上一次失败原因, # 使前端在触发瞬间即显示「上传中」并隐藏旧的失败文案;RPA 结果回来后由 complete_attempt 覆盖为真实状态。 - task.upload_status = 'uploading' - task.upload_error_code = None - task.upload_error_message = None - task.error_message = None + _set_workflow_error(task, None) timeout = _rpa_upload_timeout_seconds() set_task_step_progress( task, @@ -529,8 +599,8 @@ def _trigger_freight_upload_rpa( actor_type='system', task_no=task.task_no, conversation_id=task.conversation_id, - before={'upload_status': str(task.upload_status or '')}, - after={'upload_status': str(task.upload_status or 'pending'), 'pending_human_reason': 'upload_rpa_pending'}, + before={'upload_status': 'pending'}, + after={'upload_status': 'uploading', 'pending_human_reason': 'upload_rpa_pending'}, metadata={'attempt_id': int(attempt.id), 'artifact_id': int(attempt.artifact_id)}, source='system', ) @@ -614,8 +684,8 @@ def _sync_workflow_stage( ) -def _released_line_keys_for_task(task: ShippingNotice) -> set[str]: - """读取当前任务已审计的短缺放行行键集,供满足性与聚合重算共用。 +def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: + """读取当前任务已审计的短缺放行冻结行 ID,供满足性与聚合重算共用。 核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集, 保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。 @@ -624,18 +694,27 @@ def _released_line_keys_for_task(task: ShippingNotice) -> set[str]: if task.id is None: return set() - return { - str(row.line_key) - for row in ( - ShippingOrderReviewLineDecision.query - .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) - .filter( - ShippingOrderReviewCase.confirmed_task_id == int(task.id), - ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', - ) - .all() + if not getattr(task, 'order_snapshot_id', None): + return set() + decisions = ( + ShippingOrderReviewLineDecision.query + .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) + .filter( + ShippingOrderReviewCase.confirmed_task_id == int(task.id), + ShippingOrderReviewLineDecision.is_active.is_(True), + ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', ) + .all() + ) + from app.models import ShippingOrderSnapshot + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if snapshot is None: + return set() + return { + int(snapshot.lines[int(row.line_index)].id) + for row in decisions + if row.line_index is not None + and 0 <= int(row.line_index) < len(snapshot.lines) } @@ -653,25 +732,64 @@ def match_completed(task: ShippingNotice) -> bool: rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() if not rows: return False - released_keys = _released_line_keys_for_task(task) + from app.models import ShippingOrderSnapshot + + snapshot = ( + db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if getattr(task, 'order_snapshot_id', None) else None + ) + expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} + current_line_ids = { + int(row.snapshot_line_id) + for row in rows + if getattr(row, 'snapshot_line_id', None) is not None + } + # 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。 + if expected_line_ids and current_line_ids != expected_line_ids: + return False + released_ids = _released_snapshot_line_ids_for_task(task) for row in rows: result = str(row.match_result or '').strip() shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None)) if result == 'matched' and shortage <= 0: continue - if str(row.line_key) in released_keys and shortage > 0: + if int(row.snapshot_line_id) in released_ids and shortage > 0: continue return False return True +def inventory_match_facts_complete(task: ShippingNotice) -> bool: + """判断当前行级匹配是否覆盖冻结订单全部项次且不再处于准备中。""" + from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderSnapshot + + if task.id is None or not getattr(task, 'order_snapshot_id', None): + return False + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if snapshot is None or not snapshot.lines: + return False + rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + by_line_id = { + int(row.snapshot_line_id): row + for row in rows + if getattr(row, 'snapshot_line_id', None) is not None + } + expected_line_ids = {int(line.id) for line in snapshot.lines} + if set(by_line_id) != expected_line_ids: + return False + return all(str(row.match_result or '').strip().lower() != 'preparing' for row in by_line_id.values()) + + def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]: """读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。""" from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot from app.services.shipping_notice.export import _source_notice_for_order_facts source_notice = _source_notice_for_order_facts(task) - snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None or source_notice.id is None: return set() decisions = ( @@ -754,7 +872,19 @@ def _match_step_progress_fields( def excel_gate_error(task: ShippingNotice) -> str | None: """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" - if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path: + # 库存准备失败是硬门禁:即使任务上残留旧的 match/export 投影,也不得继续生成 + # 发货 Excel。恢复只能由显式库存准备重试或人工上传重新建立成功事实。 + from app.models import ShippingInventoryPreparationAttempt + + latest_preparation = ( + ShippingInventoryPreparationAttempt.query + .filter_by(task_id=int(task.id)) + .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .first() + ) + if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed': + return 'workflow.fulfillment.inventory_preparation_failed' + if _upload_status(task) == 'uploaded' and _export_file_path(task): return None # 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。 if not match_completed(task) and not exportable_snapshot_line_ids(task): @@ -781,69 +911,51 @@ def try_auto_chain_after_match( payload: dict[str, Any] | None = None, ) -> dict[str, Any]: """ - 匹配成功后自动串联 Excel 导出;AUTO_UPLOAD 开启时继续触发货代上传 RPA。 + 匹配成功后的下游衔接入口(履约编排)。 - 核心逻辑:match_result 为 ok 后默认自动生成 Excel; - SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true 时调用 upload_to_freight(mode=auto); - 关闭时停在 wait_manual_upload 待人工登记。 + 核心逻辑: + - Gate Attempt 路径(``_orchestrator_internal_dispatch=True``):**直接返回**匹配结果, + 禁止同 Attempt 内嵌 ``generate_excel`` / ``upload_to_freight``;由 + ``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 入队独立 + ``artifact_generation`` / freight Attempt。 + - 非 Gate 遗留路径(deprecated):仅 ``run_task_auto_progress(resume_gate_code= + artifact_generation)`` 提交下一 Attempt,仍禁止直跑 generate。 Args: - task: 当前 ShippingNotice。 + task: 当前 ShippingNotice / OT。 match_result: match_inventory 的 Tool 响应。 - payload: 原始请求体,用于读取 auto_chain_fallback 与 lang 等字段。 + payload: 原始请求体;Gate 路径须含 ``_orchestrator_internal_dispatch``。 Returns: - dict[str, Any]: 串联后的 Tool 响应;未触发串联时原样返回 match_result。 + dict[str, Any]: 未触发下游时原样返回 match_result;遗留路径返回 auto_progress 响应。 """ if match_result.get("status") != "ok": return match_result + + # [STEP] Gate Attempt 内禁止跨门禁产物副作用(编排分离契约)。 + if isinstance(payload, dict) and payload.get('_orchestrator_internal_dispatch'): + return match_result + if not should_auto_chain_after_match(payload): return match_result - result = match_result - from app.services.shipping_notice.tool_common import merge_tool_payload - from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state + # [DEPRECATED] 非 Gate 聊天/Tool 兼容:只提交 artifact Attempt,不直跑 Excel。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress - tool_payload = merge_tool_payload(task, payload) - - # [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。 - if _auto_generate_excel_enabled(): - db.session.refresh(task) - if not task.export_file_path and excel_gate_error(task) is None: - gen = generate_excel(tool_payload) - if gen.get("status") != "ok": - return gen - result = prepend_tool_message(gen, str(result.get("message") or "")) - - # [STEP 2] Excel 就绪后:开启 AUTO_UPLOAD 则触发货代 RPA,否则停待人工上传。 - db.session.refresh(task) - ui = resolve_task_ui_state(task) - excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( - task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded' + trigger = str((payload or {}).get('source') or (payload or {}).get('trigger') or 'legacy_auto_chain').strip() + actor_raw = (payload or {}).get('operator_id') or (payload or {}).get('actor_id') or (payload or {}).get('_trusted_user_id') + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + str(task.task_no), + trigger=trigger, + expected_version=None, + idempotency_key=str((payload or {}).get('idempotency_key') or '').strip() or None, + resume_gate_code='artifact_generation', + operator_id=operator_id, ) - if excel_ready and _auto_upload_enabled(): - upload_result = upload_to_freight({ - **tool_payload, - 'task_id': task.task_no, - 'mode': 'auto', - }) - return prepend_tool_message(upload_result, str(result.get('message') or '')) - if excel_ready: - return tool_response( - status="ok", - task=task, - message=str( - result.get("message") - or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。" - ), - data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, - stop_agent_turn=True, - forbidden_next_tools=["upload_to_freight"], - ) - - return result - def _order_extraction_gate_response( task: ShippingNotice, @@ -866,16 +978,16 @@ def _order_extraction_gate_response( return None -def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, Any]: +def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, Any]: """ - 题5B:行级库存匹配(仅目标 line_key)—— 避免整单重算覆盖其他行证据/时间戳。 + 题5B:行级库存匹配(仅目标订单 line_no)——避免整单重算覆盖其他行证据/时间戳。 【AI 触发时机】:用户仅对某一行点「重试匹配库存」或系统侧决策为 ACTION_REMATCH & 有 snapshot_id 时调用; - 必须 line_key 非空,不回退到整单。 + 必须 line_no 为正整数,不回退到整单。 核心逻辑: [STEP 1] 共用 match_inventory 的门禁/库存快照载入; - [STEP 2] 仅 purpose_lines 中 line_key == 目标 的那条 purpose_line 生成单元素 stp_order_lines; + [STEP 2] 仅按订单 line_no 定位 purpose_line,生成单元素 stp_order_lines; [STEP 3] 调 match_order_lines_across_candidates(单条 order_lines); [STEP 4] persist_line_inventory_match_facts:line_results 只写该条(其他行 untouched); [STEP 5] 整单汇总用:match_status 按全行事实重算(读现有的 line_inventory_match 表), @@ -883,7 +995,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, Args: payload: 含 task_no / operator_id / expected_order_task_no 等,与 match_inventory 一致。 - line_key: 必填;目标行业务键(shipping_order_fields.line_key 或 line-{idx})。 + line_no: 必填;订单内 1-based 项次。 Returns: Tool 标准响应(status ok / needs_human / failed)。 @@ -908,11 +1020,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, resume_gate_code='inventory_matching', operator_id=operator_id, - line_scope_key=str(line_key or '').strip() or None, + line_scope_key=str(line_no) if line_no is not None else None, ) - target_key = str(line_key or '').strip() - if not target_key: - return tool_response(status='failed', message='行级库存匹配必须提供 line_key') + try: + target_line_no = int(line_no) + except (TypeError, ValueError): + return tool_response(status='failed', message='行级库存匹配必须提供有效 line_no') + if target_line_no < 1: + return tool_response(status='failed', message='行级库存匹配必须提供有效 line_no') lang = resolve_lang(payload) actor_id = _event_actor_id(payload) task = resolve_task_from_payload(payload) @@ -924,9 +1039,8 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, build_inventory_candidate_primary_action, get_active_candidate_set, ) - if str(task.inventory_source_status or '').strip() == 'candidates_frozen': - active_candidate_set = get_active_candidate_set(task) - if active_candidate_set is None: + active_candidate_set = get_active_candidate_set(task) + if active_candidate_set is None: return tool_response( status='needs_human', task=task, @@ -938,7 +1052,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, ), 'primary_action': build_inventory_candidate_primary_action(), }, - checkpoint='inventory_source_review', + position='inventory_source_review', stop_agent_turn=True, ) # ownership & gates @@ -983,11 +1097,38 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, task, legacy_payload_lines=parse_inventory_lines(payload), ) if not inventory_lines: - # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义) - inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key} + # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义); + # 保留 Gate 内部调度标记,并尽量带上该行 source_codes,避免回退成整单 RPA。 + inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_no': target_line_no} + if payload.get('_orchestrator_internal_dispatch'): + inv_payload['_orchestrator_internal_dispatch'] = True + scoped_codes = [ + str(code).strip().upper() + for code in (payload.get('source_codes') or []) + if str(code).strip() + ] + if not scoped_codes: + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + candidate_line = next( + ( + line for line in get_active_candidate_lines(task) + if int(getattr(line, 'line_no', 0) or 0) == target_line_no + ), + None, + ) + scoped_codes = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if scoped_codes: + inv_payload['source_codes'] = scoped_codes lang_suffix = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() if lang_suffix: inv_payload["lang"] = lang_suffix + for key in ('operator_id', 'actor_user_id', 'mode'): + if payload.get(key) is not None: + inv_payload[key] = payload.get(key) return ensure_inventory(inv_payload) if not is_inventory_source_stable(task): return tool_response( @@ -995,7 +1136,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, task=task, message="库存源尚未确定,无法执行行级库存匹配。", data=serialize_task_for_tool(task), - checkpoint="inventory_source_review", + position="inventory_source_review", stop_agent_turn=True, ) from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes @@ -1011,24 +1152,22 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, _order_header_values, order_field_lines = order_field_id_values(task) purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'}) - # [STEP 2] 定位目标行 purpose_line + order_field_line + # [STEP 2] 按不可变订单项次定位目标行;库存事实使用 snapshot_line_id。 target_pair: tuple[int, dict[str, Any], dict[str, Any]] | None = None + target_idx = target_line_no - 1 for idx, purpose_line in enumerate(purpose_lines): + if idx != target_idx: + continue ofl = order_field_lines[idx] if idx < len(order_field_lines) else {} - candidate_key = str( - purpose_line.get('line_key') - or ofl.get('line_key') - or f'line-{idx + 1}' - ).strip() - if candidate_key == target_key: + if idx == target_idx: target_pair = (idx, purpose_line, ofl) break if target_pair is None: - # line_key 未找到(可能草稿与 OT 行未对齐) + # 订单项次未找到。 return tool_response( status='failed', task=task, - message=f'未找到行 {target_key},无法执行行级库存匹配。', + message=f'未找到订单项次 {target_line_no},无法执行行级库存匹配。', data=serialize_task_for_tool(task), ) orig_idx, purpose_line, order_field_line = target_pair @@ -1051,7 +1190,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, lifecycle_status='inventory_matching', event_code='inventory_match_line_started', actor_id=actor_id, - payload={'task_no': task.task_no, 'line_key': target_key, 'line_index': orig_idx}, + payload={'task_no': task.task_no, 'line_no': target_line_no, 'line_index': orig_idx}, ) db.session.flush() @@ -1070,7 +1209,8 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, '__display_reservation_id': display_rsv, '__display_uom': display_uom, 'uom': display_uom, - 'line_key': order_field_line.get('line_key') or target_key, + 'line_no': target_line_no, + 'line_no': target_line_no, 'line_index': orig_idx, }] # [STEP 3] 只跑目标行 match @@ -1079,14 +1219,10 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, inventory_lines=inventory_lines or [], header_reservation_id=header_reservation, ) - # resolutions 注入 line_key(保证 persist 时精准) + # 匹配器结果保留 line_index;持久化按订单项次顺序落库。 for res in (match_payload.get('resolutions') or []): if isinstance(res, dict): - res['line_key'] = ( - str(res.get('line_key') or '').strip() - or order_field_line.get('line_key') - or target_key - ) + res['line_no'] = target_line_no # [STEP 4] 持久化仅本行(其他行 is_current 保持不变) from app.services.shipping_notice.line_inventory_match_persistence import ( persist_line_inventory_match_facts, @@ -1094,26 +1230,21 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, persist_line_inventory_match_facts( task=task, match_payload=match_payload, - inventory_snapshot_id=( - int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None - ), + inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, matching_rule_version='stp_line_v2', ) - # 行级 apply_line_inventory_resolutions:但不能全量覆盖 task.match_status, - # 改写成「增量合并」:把本 line 的 resolution 合并进 task.step_payload_json.line_inventory_resolutions, - # 再基于现有的全部 current 行事实重算 match_status。 - _merge_line_inventory_resolutions(task, match_payload, line_key=target_key) + # 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。 + _merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None) line_results = list(match_payload.get('line_results') or []) from app.services.shipping_notice.reservation_service import record_inventory_verification verification = record_inventory_verification( - task, inventory_snapshot_id=task.inventory_snapshot_id, - source_config_version=task.inventory_source_config_version, line_results=line_results, + task, inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, + source_config_version=active_inventory_file_for_task(task).source_config_version if active_inventory_file_for_task(task) else None, line_results=line_results, ) - # [STEP 5] 基于 current 行事实重新聚合 match_status,避免局部 ok 覆盖全局 shortage。 + # [STEP 5] 基于 current 行事实计算本次门禁结果,避免局部 ok 覆盖整单缺口。 aggregate_match_status, aggregate_shortages = _recompute_task_match_aggregate(task) - task.match_status = aggregate_match_status # shortages 保持整单范围(用于展示),行级单独记录到 detail_json line_result_status = str(match_payload.get('match_status') or 'unfulfillable') set_task_step_progress( @@ -1125,7 +1256,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, progress_percent=50, detail=( t("workflow.fulfillment.match_line_result", lang=lang) - .format(line_key=target_key, line_result=line_result_status) + .format(line_no=f'#{target_line_no}', line_result=line_result_status) ), ) match_summary = format_match_summary( @@ -1134,7 +1265,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, task_no=task.task_no, lang=lang, ) - if aggregate_match_status == 'fulfillable' and task.inventory_source_code: + if aggregate_match_status == 'fulfillable': apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE) log_task_event( task, @@ -1142,9 +1273,9 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, { "match_status": aggregate_match_status, "verification_id": verification.id, - "resolved_ok_source_codes": (task.step_payload_json or {}).get('resolved_ok_source_codes'), - "excel_binding_source_code": task.inventory_source_code, - "line_key": target_key, + "resolved_ok_source_codes": _resolved_ok_source_codes(task), + "excel_binding_source_code": _single_candidate_source_code(task), + "line_no": target_line_no, "line_result": line_result_status, }, actor_id=actor_id, @@ -1164,7 +1295,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, task_id=task.task_no, message=match_summary, data=serialize_task_for_tool(task), - checkpoint=f'line:{target_key}:rematch:ok', + position=f'line_no:{target_line_no}:rematch:ok', ) return try_auto_chain_after_match(task, match_result, payload=payload) apply_task_transition(task, TaskTransition.MATCH_SHORTAGE) @@ -1173,7 +1304,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, "matched_stp_line_rematch_shortage", { "match_status": aggregate_match_status, - "line_key": target_key, + "line_no": target_line_no, "line_result": line_result_status, "shortages": aggregate_shortages, }, @@ -1194,31 +1325,21 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, task=task, message=match_summary, data=serialize_task_for_tool(task), - checkpoint=f'shortage_review:line:{target_key}', + position=f'shortage_review:line_no:{target_line_no}', stop_agent_turn=True, forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) def _merge_line_inventory_resolutions( - task: ShippingNotice, match_payload: dict[str, Any], *, line_key: str + task: ShippingNotice, match_payload: dict[str, Any], *, snapshot_line_id: int | None ) -> None: - """把行级 match_payload.resolutions 合并进 task.step_payload_json.line_inventory_resolutions(只替换/追加本行条目)。""" - payload_step = dict(task.step_payload_json or {}) - old_resolutions = [ - r for r in list(payload_step.get('line_inventory_resolutions') or []) - if isinstance(r, dict) and str(r.get('line_key') or f'line-{int(r.get("line_index") or 0) + 1}').strip() != str(line_key) - ] - new_resolutions = [r for r in list(match_payload.get('resolutions') or []) if isinstance(r, dict)] - merged_resolutions = [*old_resolutions, *new_resolutions] - payload_step['line_inventory_resolutions'] = merged_resolutions - payload_step.pop('multi_source_excel_block', None) - task.step_payload_json = payload_step - # line_results_json & shortage_json 保持整单范围不在这里单行替换;统一由 recompute 使用 facts 重算 + """保留旧调用签名;匹配事实统一由 LineInventoryMatch 持久化。""" + del task, match_payload, snapshot_line_id def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]: - """根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。 + """根据当前 LineMatch 重新计算门禁结果(fulfillable/partial/unfulfillable)与缺口。 核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage) 且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂, @@ -1231,11 +1352,11 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic ) if not rows: return 'unfulfillable', [] - released_keys = _released_line_keys_for_task(task) + released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task) has_ok = False has_block = False shortages: list[dict[str, Any]] = [] - task.line_results_json = [] + line_results: list[dict[str, Any]] = [] for row in rows: match_result = str(getattr(row, 'match_result', '') or '').strip() required_qty = getattr(row, 'required_qty', None) @@ -1243,7 +1364,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic shortage_qty = getattr(row, 'shortage_qty', None) entry = { 'line_index': int(getattr(row, 'line_index', 0) or 0), - 'line_key': str(getattr(row, 'line_key', '') or ''), + 'snapshot_line_id': int(getattr(row, 'snapshot_line_id', 0) or 0), + 'line_no': int(getattr(row, 'line_no', 0) or 0), 'disposition': match_result or 'not_found', 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), @@ -1255,7 +1377,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic } # 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。 shortage = _line_shortage_qty(shortage_qty) - released = str(getattr(row, 'line_key', '') or '') in released_keys + released = entry['snapshot_line_id'] in released_snapshot_line_ids if match_result == 'matched' and shortage <= 0: entry['line_status'] = 'ok' has_ok = True @@ -1267,8 +1389,16 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic entry['line_status'] = 'shortage' has_block = True shortages.append(entry) - task.line_results_json.append(entry) - task.shortage_json = {'lines': shortages} + line_results.append(entry) + owner = _workflow_owner(task) + if hasattr(owner, 'step_payload_json'): + payload = dict(owner.step_payload_json or {}) + payload['current_match_projection'] = { + 'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'), + 'line_results': line_results, + 'shortage': {'lines': shortages}, + } + owner.step_payload_json = payload if has_block and has_ok: status = 'partial' elif has_block: @@ -1279,16 +1409,59 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: - """返回 task.line_results_json(若没初始化则用现查询 facts 重算)供 format_match_summary。""" - cached = list(task.line_results_json or []) - if cached: - return cached - _recompute_task_match_aggregate(task) - return list(task.line_results_json or []) + """返回当前行级 Match 聚合结果;OT 不回读 step_payload_json 缓存。""" + if task.__class__.__name__ == 'ShippingOrderTask': + rows = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), is_current=True) + .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .all() + ) + return [ + { + 'line_no': int(getattr(row, 'line_no', 0) or 0), + 'line_index': getattr(row, 'line_index', None), + 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), + 'disposition': getattr(row, 'match_result', None), + 'match_result': getattr(row, 'match_result', None), + 'inventory_status': getattr(row, 'inventory_status', None), + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'required_qty': getattr(row, 'required_qty', None), + 'available_qty': getattr(row, 'available_qty', None), + 'shortage_qty': getattr(row, 'shortage_qty', None), + 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'candidate_source_codes': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), + } + for row in rows + ] + rows = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), is_current=True) + .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .all() + ) + return [ + { + 'line_no': int(getattr(row, 'line_no', 0) or 0), + 'line_index': getattr(row, 'line_index', None), + 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), + 'disposition': getattr(row, 'match_result', None), + 'match_result': getattr(row, 'match_result', None), + 'inventory_status': getattr(row, 'inventory_status', None), + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'required_qty': getattr(row, 'required_qty', None), + 'available_qty': getattr(row, 'available_qty', None), + 'shortage_qty': getattr(row, 'shortage_qty', None), + 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + } + for row in rows + ] def recompute_task_fulfillment_state(task: ShippingNotice) -> str: - """按当前匹配/放行事实重算任务履约态:match_status、line_results_json、shortage_json 与 review/pending。 + """按当前匹配/放行事实重算任务履约态与复核迁移,不写入旧库存投影列。 核心逻辑:委托 ``_recompute_task_match_aggregate``(与 ``match_completed`` 同款放行语义), 再据此同步 ``review_status``/``pending_human_reason`` 并应用对应任务迁移。 @@ -1298,10 +1471,9 @@ def recompute_task_fulfillment_state(task: ShippingNotice) -> str: task: 待重算的 ShippingNotice(尚未 commit)。 Returns: - 重算后的 match_status(fulfillable / partial / unfulfillable)。 + 重算后的门禁聚合状态(fulfillable / partial / unfulfillable)。 """ status, _shortages = _recompute_task_match_aggregate(task) - task.match_status = status if status == 'fulfillable': apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE) else: @@ -1318,7 +1490,7 @@ def _profile_match_persistence_payload( 将单源 Profile 匹配结果转换为结构化行事实写入载荷。 核心逻辑:按结果稳定行序补齐 line_index;resolutions 不写临时 line-N, - 由持久化层使用同一行序关联 Case 草稿的真实 line_key。 + 由持久化层使用冻结订单行的 snapshot_line_id 关联库存事实。 Args: line_results: match_notice_lines 返回的逐行结果。 @@ -1339,9 +1511,8 @@ def _profile_match_persistence_payload( 'resolutions': [ { 'line_index': index, - # 让持久化层按 Case 草稿的 line_key(如 machine-1)解析; - # 不写入临时 line-N,避免 Review Projection 无法关联事实。 - 'line_key': row.get('line_key'), + 'snapshot_line_id': row.get('snapshot_line_id'), + 'line_no': row.get('line_no'), 'part_number': row.get('part_number'), 'effective_reservation_id': row.get('reservation_id'), 'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage', @@ -1485,7 +1656,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task=task, message="库存源尚未确定,无法执行库存匹配。", data=serialize_task_for_tool(task), - checkpoint="inventory_source_review", + position="inventory_source_review", stop_agent_turn=True, ) @@ -1502,8 +1673,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 人工指定源后仅保留 forced_match_source_code 对应库存行,消解多源/多文件冲突。 inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task) use_stp_cross_match = ( - str(task.inventory_source_status or '').strip() == 'candidates_frozen' - or len(task_frozen_inventory_source_codes(task)) > 1 + len(task_frozen_inventory_source_codes(task)) >= 1 or any(isinstance(row, dict) and row.get('__source_code') for row in (inventory_lines or [])) ) if use_stp_cross_match: @@ -1532,10 +1702,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: or purpose_line.get('unit') or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom') ), - 'line_key': ( - (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key') - or f'line-{index + 1}' - ), + 'line_no': index + 1, }) match_payload = match_order_lines_across_candidates( order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines), @@ -1550,21 +1717,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: persist_line_inventory_match_facts( task=task, match_payload=match_payload, - inventory_snapshot_id=( - int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None - ), + inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, matching_rule_version='stp_line_v2', ) # 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单, # 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。 match_status, shortages = _recompute_task_match_aggregate(task) - line_results = list(task.line_results_json or []) - task.match_status = match_status - task.shortage_json = {'lines': shortages} + line_results = _current_line_results(task) from app.services.shipping_notice.reservation_service import record_inventory_verification verification = record_inventory_verification( - task, inventory_snapshot_id=task.inventory_snapshot_id, - source_config_version=task.inventory_source_config_version, line_results=line_results, + task, inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, + source_config_version=active_inventory_file_for_task(task).source_config_version if active_inventory_file_for_task(task) else None, line_results=line_results, ) set_task_step_progress( task, @@ -1583,7 +1746,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: lang=lang, ) # STP:仅全部明细 ok(match_completed)且已投影库存源时自动制单。 - if match_completed(task) and task.inventory_source_code: + if match_completed(task): apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE) log_task_event( task, @@ -1591,8 +1754,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: { "match_status": match_status, "verification_id": verification.id, - "resolved_ok_source_codes": (task.step_payload_json or {}).get('resolved_ok_source_codes'), - "excel_binding_source_code": task.inventory_source_code, + "resolved_ok_source_codes": _resolved_ok_source_codes(task), + "excel_binding_source_code": _single_candidate_source_code(task), }, actor_id=actor_id, source='workspace_api' if actor_id else 'system', @@ -1637,7 +1800,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=match_summary, data=serialize_task_for_tool(task), - checkpoint="shortage_review", + position="shortage_review", stop_agent_turn=True, forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) @@ -1661,7 +1824,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: from app.models import ShippingInventoryField, ShippingInventorySource - source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first() + source_code = _single_candidate_source_code(task) + source = ShippingInventorySource.query.filter_by(source_code=source_code).first() definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] mapped_field_ids = [ @@ -1691,18 +1855,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task=task, match_payload=_profile_match_persistence_payload( line_results, - inventory_source_code=task.inventory_source_code, + inventory_source_code=source_code, ), - inventory_snapshot_id=(int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None), + inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, matching_rule_version='profile_match_v1', ) - task.match_status = match_status - task.line_results_json = line_results - task.shortage_json = shortage from app.services.shipping_notice.reservation_service import record_inventory_verification verification = record_inventory_verification( - task, inventory_snapshot_id=task.inventory_snapshot_id, - source_config_version=task.inventory_source_config_version, line_results=line_results, + task, inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, + source_config_version=active_inventory_file_for_task(task).source_config_version if active_inventory_file_for_task(task) else None, line_results=line_results, ) set_task_step_progress( task, @@ -1843,9 +2004,34 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: forbidden_next_tools=["upload_to_freight"], ) - # [STEP 1] 已有旧 Artifact 不等于本轮没有可导出预约单;库存刷新后 + # [STEP 1] 库存准备失败优先于旧 Artifact 复用;失败轮次必须停在通知准备, + # 不能因为任务上残留旧 Excel 就伪装成可继续。 + gate_error = excel_gate_error(task) + if gate_error: + return tool_response( + status="failed", + task_id=task.task_no, + message=t(gate_error, lang=lang) if gate_error.startswith("workflow.") else gate_error, + data=serialize_task_for_tool(task), + forbidden_next_tools=["upload_to_freight"], + next_required_action=t("workflow.fulfillment.match_first", lang=lang), + ) + + # [P0] 仅在库存源稳定且库存匹配门禁通过后物化正式 Notice;Excel、Artifact 与上传均绑定 Notice。 + from app.services.shipping_notice.shipping_notice_creation_service import create_shipping_notice_after_inventory_gate + from app.models import ShippingOrderTask + if isinstance(task, ShippingOrderTask): + try: + task = create_shipping_notice_after_inventory_gate(task) + except ConflictError as exc: + return tool_response( + status="failed", task_id=task.task_no, message=str(exc), + data=serialize_task_for_tool(task), forbidden_next_tools=["upload_to_freight"], + ) + + # [STEP 2] 已有旧 Artifact 不等于本轮没有可导出预约单;库存刷新后 # 仍须允许缺货项生成下一轮 Excel。仅当最新核验没有未占用的可用预约单时复用下载结果。 - if task.export_file_path and not task_export_error_message(task): + if _export_file_path(task) and not task_export_error_message(task): from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids try: @@ -1861,12 +2047,12 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: status="ok", task_id=task.task_no, message=t("workflow.fulfillment.excel_exists", lang=lang).format( - file=task.export_file_name or task.export_file_path + file=_export_file_name(task) or _export_file_path(task) ), data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"}, ) - # [STEP 2] 先校验是否满足导出门禁。 + # [STEP 3] 先校验是否满足导出门禁。 # 只要当前库存轮次存在可导出行即可生成滚动 Excel;未满足行继续停留在库存满足性 Gate。 gate_error = excel_gate_error(task) if gate_error: @@ -1918,16 +2104,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: }, forbidden_next_tools=["upload_to_freight"], ) - task.export_file_path = path - task.export_file_name = filename # 绑定导出时的 order_data_version,供 formal edit Excel 冻结指纹校验。 - export_payload = dict(task.step_payload_json or {}) - export_payload['export_meta'] = { - 'order_data_version': int(task.order_data_version or 1), - 'artifact_no': getattr(artifact, 'artifact_no', None), - 'file_name': filename, - } - task.step_payload_json = export_payload apply_task_transition(task, TaskTransition.WAITING_UPLOAD) # [BE-06] Excel 就绪后 OT 进入货代上传段(waiting_upload → freight_uploading)。 from app.services.shipping_notice.order_task_stage_machine import ( @@ -2037,7 +2214,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: return reservation_gate # [STEP 1] 先确保至少有一份 Artifact;后续上传始终由 Artifact 而非 Task 文件指针驱动。 - if not task.export_file_path: + if _current_export_artifact(task) is None: gen = generate_excel({"task_id": task.task_no}) if gen.get("status") != "ok": return gen @@ -2086,7 +2263,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: ) operator_id = payload.get('operator_id') - before_upload_status = str(task.upload_status or '') + before_upload_status = _upload_status(task) or 'pending' try: attempt = record_manual_upload( task, @@ -2116,7 +2293,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: conversation_id=task.conversation_id, reason_code='task_closed_after_upload', before={'upload_status': before_upload_status or 'pending'}, - after={'upload_status': str(task.upload_status or 'uploaded')}, + after={'upload_status': 'uploaded'}, metadata={ 'attempt_id': attempt.id, 'artifact_id': attempt.artifact_id, @@ -2147,7 +2324,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: task_id=task.task_no, message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None, + position=POSITION_UPLOADED if has_verified_upload_success(task) else None, ) @@ -2198,31 +2375,34 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: 可选 freight_ref_no、error_message。 Returns: - dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。 + dict[str, Any]: 成功时 position=uploaded;失败时 needs_human 并附带 error_message。 """ lang = resolve_lang(payload) - task = resolve_task_from_payload(payload) - if not task: - return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + try: + attempt_id = int(payload.get('attempt_id')) + except (TypeError, ValueError): + return tool_response(status='failed', message='attempt_id is required') + from app.models import ShippingUploadAttempt + attempt = db.session.get(ShippingUploadAttempt, attempt_id) + if attempt is None: + return tool_response(status='failed', message='Upload attempt not found') + from app.models import ShippingExportArtifact + artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) + task = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None + if not isinstance(task, ShippingNotice): + return tool_response(status='failed', message='Upload attempt does not belong to a shipping notice') + supplied_ref = str(payload.get('task_id') or payload.get('task_no') or '').strip() + if supplied_ref and supplied_ref not in {str(task.task_no or ''), str(task.business_no or '')}: + return tool_response( + status='failed', task=task, + message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task), + ) disposition_gate = _task_disposition_gate_response(task) if disposition_gate is not None: return disposition_gate customer_gate = customer_gate_tool_response(task, operation='rpa_report_upload') if customer_gate is not None: return customer_gate - - try: - attempt_id = int(payload.get('attempt_id')) - except (TypeError, ValueError): - return tool_response(status='failed', task=task, message='attempt_id is required', data=serialize_task_for_tool(task)) - from app.models import ShippingUploadAttempt - attempt = db.session.get(ShippingUploadAttempt, attempt_id) - if attempt is None: - return tool_response(status='failed', task=task, message='Upload attempt not found', data=serialize_task_for_tool(task)) - from app.models import ShippingExportArtifact - artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) - if artifact is None or artifact.task_id != task.id: - return tool_response(status='failed', task=task, message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task)) try: success = _rpa_callback_success(payload.get("success")) except ValidationError as exc: @@ -2320,12 +2500,11 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: task_id=task.task_no, message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None, + position=POSITION_UPLOADED if has_verified_upload_success(task) else None, ) if completed.status == 'unknown': # unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。 - task.upload_finished_at = datetime.utcnow() set_task_step_progress( task, step_key="step7_upload_freight", @@ -2335,18 +2514,17 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: progress_percent=100, detail=t("workflow.fulfillment.upload_unknown_detail", lang=lang), ) - task.error_message = completed.error_message or 'RPA upload result unknown' - log_task_event(task, "upload_rpa_unknown", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message}) + _set_workflow_error(task, completed.error_message or 'RPA upload result unknown') + log_task_event(task, "upload_rpa_unknown", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": _workflow_error(task)}) db.session.commit() return tool_response( status="needs_human", task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), ) apply_task_transition(task, TaskTransition.WAITING_UPLOAD) - task.upload_finished_at = datetime.utcnow() set_task_step_progress( task, step_key="step7_upload_freight", @@ -2356,15 +2534,15 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: progress_percent=100, detail=t("workflow.fulfillment.upload_failed_detail", lang=lang), ) - task.error_message = completed.error_message or 'RPA upload failed' - log_task_event(task, "upload_rpa_failed", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message}) + _set_workflow_error(task, completed.error_message or 'RPA upload failed') + log_task_event(task, "upload_rpa_failed", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": _workflow_error(task)}) # 业务决定:货代上传 RPA 不按次数熔断,失败后仍可重试或转人工确认;此处保留真实失败原因, # 不再以「已达最大重试次数」覆盖错误正文。 db.session.commit() return tool_response( status="needs_human", task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), ) @@ -2379,7 +2557,7 @@ def run_auto_progress_fulfillment_steps( 核心逻辑:自动匹配与生成 Excel;AUTO_UPLOAD 开启时触发 upload_to_freight(mode=auto); 关闭时停在 wait_manual_upload 待人工登记。 """ - from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state + from app.services.shipping_notice.state_machine import resolve_task_ui_state # [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。 if _auto_match_enabled() and not match_completed(task): @@ -2389,17 +2567,15 @@ def run_auto_progress_fulfillment_steps( steps.append("库存匹配") # [STEP 2] 匹配完成后按配置自动生成 Excel。 - if _auto_generate_excel_enabled() and match_completed(task) and not task.export_file_path: + if _auto_generate_excel_enabled() and match_completed(task) and _current_export_artifact(task) is None: gen = generate_excel({"task_id": task.task_no}) if gen.get("status") != "ok": return gen steps.append("生成发货 Excel") # [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。 - ui = resolve_task_ui_state(task) - excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( - task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded' - ) + # excel_ready 只读领域产物事实,禁止 UserMode/resolve_task_ui_state 裁决。 + excel_ready = bool(_export_file_path(task)) and _upload_status(task) != 'uploaded' if excel_ready and _auto_upload_enabled(): steps.append("触发货代上传 RPA") return upload_to_freight({ @@ -2414,7 +2590,7 @@ def run_auto_progress_fulfillment_steps( task=task, message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=resolve_task_ui_state(task).position, stop_agent_turn=True, forbidden_next_tools=["upload_to_freight"], ) diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index aa96cf8a..bffe2e20 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -113,6 +113,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。", "workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。", "workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。", + "workflow.fulfillment.inventory_preparation_failed": "库存准备失败。请人工重试或上传库存文件后再继续。", "workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}", "workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)", "workflow.fulfillment.generate_running": "正在生成发货 Excel", @@ -238,6 +239,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.", "workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.", "workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.", + "workflow.fulfillment.inventory_preparation_failed": "Inventory preparation failed. Retry manually or upload an inventory file before continuing.", "workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}", "workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)", "workflow.fulfillment.generate_running": "Generating shipment Excel.", @@ -363,6 +365,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่", "workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก", "workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน", + "workflow.fulfillment.inventory_preparation_failed": "การเตรียมสต็อกล้มเหลว โปรดลองด้วยตนเองหรืออัปโหลดไฟล์สต็อกก่อนดำเนินการต่อ", "workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}", "workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)", "workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel", diff --git a/backend/app/services/shipping_notice/identity_resolution/resolver.py b/backend/app/services/shipping_notice/identity_resolution/resolver.py index dcacbade..249ace2a 100644 --- a/backend/app/services/shipping_notice/identity_resolution/resolver.py +++ b/backend/app/services/shipping_notice/identity_resolution/resolver.py @@ -86,7 +86,7 @@ def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[Shipping def definition_context_field_is_compatible( definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str, ) -> bool: - """校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。""" + """字段绑定主谓词:先认定同一 UUID 即同字段;否则按 field_code + scope + value_type 判断语义兼容承接规则快照。""" expected_id = str(definition.get('context_field_id') or '') if actual_field_id == expected_id: return True @@ -111,15 +111,19 @@ def definition_context_field_is_compatible( def _resolved_context_field_id( definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]], ) -> str | None: - """优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。""" + """按 field_config.field_code 语义键定位当前字段;UUID 直配仅保留为同字段快速命中。 + + 规则定义以 field_code(不随 Schema 版本重建而漂移)作为跨版本稳定引用锚点; + UUID 直接命中只作为无漂移时的快捷路径,避免 Schema 重发布打断识别链路。 + 旧快照若缺少 field_code,则回退到 UUID 直配路径,保证向后兼容。 + """ + if extraction is not None: + for field_id in header_values: + if definition_context_field_is_compatible(definition, extraction, field_id): + return field_id expected_id = str(definition.get('context_field_id') or '') if expected_id in header_values: return expected_id - if extraction is None: - return None - for field_id in header_values: - if definition_context_field_is_compatible(definition, extraction, field_id): - return field_id return None diff --git a/backend/app/services/shipping_notice/identity_rules/service.py b/backend/app/services/shipping_notice/identity_rules/service.py index 202ebf65..adb1636e 100644 --- a/backend/app/services/shipping_notice/identity_rules/service.py +++ b/backend/app/services/shipping_notice/identity_rules/service.py @@ -12,8 +12,6 @@ import hashlib import json import re import uuid -from pathlib import Path -import urllib.request from datetime import datetime from typing import Any @@ -112,19 +110,6 @@ def _published_schema_version() -> ShippingOrderSchemaVersion | None: def _published_field_config(field_id: str) -> dict[str, Any] | None: """读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。""" - # #region debug-point A/B/C/E:published-schema-state - try: - debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env' - debug_values = { - line.split('=', 1)[0]: line.split('=', 1)[1].strip() - for line in debug_env.read_text(encoding='utf-8').splitlines() - if '=' in line - } - published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all() - urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() - except Exception: - pass - # #endregion published = _published_schema_version() return next(( item for item in ((published.definition_json if published else {}) or {}).get('fields', []) diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py index 2f467423..acdf8873 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py @@ -193,7 +193,7 @@ def _collect_order_line_candidates( line_codes = list(task_level_source_codes_ordered) line_projections.append({ - 'line_key': f'{task.id}:{line_no}', + # 该阶段只产生候选投影;冻结档建立后由 snapshot_line_id 作为唯一行身份。 'line_index': idx, 'line_no': line_no, 'source_line_no': source_line_no, @@ -276,19 +276,13 @@ def _invalidate_task_candidate_outputs( ShippingUploadAttempt, ) - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.export_file_path = None - task.export_file_name = None - task.upload_status = None - payload = dict(task.step_payload_json or {}) payload.pop('line_inventory_resolutions', None) payload.pop('resolved_ok_source_codes', None) payload.pop('excel_binding_source_code', None) payload.pop('multi_source_excel_block', None) - task.step_payload_json = payload + if task.__class__.__name__ != 'ShippingOrderTask': + task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}} ( session.query(ShippingNoticeLineInventoryMatch) @@ -306,12 +300,18 @@ def _invalidate_task_candidate_outputs( ) .update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False) ) - artifact_ids = [ - row[0] for row in session.query(ShippingExportArtifact.id).filter( - ShippingExportArtifact.task_id == int(task.id), - ShippingExportArtifact.status.in_(('ready', 'uploading')), + notice_ids = [ + int(row.id) + for row in session.query(ShippingNotice.id).filter( + ShippingNotice.order_task_id == int(task.id), ).all() ] + artifact_ids = [ + row[0] for row in session.query(ShippingExportArtifact.id).filter( + ShippingExportArtifact.task_id.in_(notice_ids), + ShippingExportArtifact.status.in_(('ready', 'uploading')), + ).all() + ] if notice_ids else [] if artifact_ids: session.query(ShippingExportArtifact).filter( ShippingExportArtifact.id.in_(artifact_ids), @@ -358,6 +358,7 @@ def freeze_candidates_for_task( execution_id: int | None = None, frozen_by_id: int | None = None, line_projections: list[dict[str, Any]] | None = None, + preserve_empty_line_candidates: bool = False, session: Session | None = None, ) -> CandidateFreezeResult: """ @@ -370,7 +371,6 @@ def freeze_candidates_for_task( [STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。 [STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。 [STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。 - [STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。 Args: task: 已 flush 的 ShippingNotice(有 id 字段)。 @@ -380,6 +380,8 @@ def freeze_candidates_for_task( execution_id: 可选的 ProcessExecution 绑定 ID。 frozen_by_id: 人工覆盖冻结时的操作人 ID。 line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。 + preserve_empty_line_candidates: 仅人工逐项选源时为 True;保留尚未选择源的 + Snapshot 行为空列表,使 Gate 能继续阻断而不会误触发整单库存准备。 session: 可选的 SQLAlchemy Session(缺省用 db.session)。 Returns: @@ -421,18 +423,14 @@ def freeze_candidates_for_task( continue codes_raw = item.get('candidate_inventory_source_codes') or [] codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()] - if not codes: + if not codes and not preserve_empty_line_candidates: codes = list(task_source_codes_ordered) - line_index = item.get('line_index') try: line_no = int(item.get('line_no') or 0) except (TypeError, ValueError): line_no = 0 if line_no <= 0: - try: - line_no = int(line_index) + 1 - except (TypeError, ValueError): - line_no = len(signatures) + 1 + raise ValueError('候选行缺少持久化 line_no,禁止从 line_index 派生项次') signatures.append(( line_no, str(item.get('source_line_no') or '').strip() or None, @@ -599,22 +597,22 @@ def freeze_candidates_for_task( if getattr(task, 'id', None) is not None: task.active_inventory_candidate_set_id = int(new_set.id) - # 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。 - from app.services.shipping_notice.auto_progress_controller import ( - supersede_auto_progress_for_candidate_refreeze, - ) + # 人工逐项选源正由当前 GateAttempt 执行时,不能把它自己 supersede, + # 否则选源已落库但 Attempt 无法完成。该 Execution 只更新候选版本,仍停在 + # routing Gate;所有项次选完后才进入库存准备。其他重冻结仍取消旧链。 + current_execution_id = getattr(task, 'active_process_execution_id', None) + if execution_id is not None and int(current_execution_id or 0) == int(execution_id): + from app.models import ShippingProcessExecution - supersede_auto_progress_for_candidate_refreeze(task) + current_execution = session.get(ShippingProcessExecution, int(execution_id)) + if current_execution is not None: + current_execution.candidate_set_id = int(new_set.id) + else: + from app.services.shipping_notice.auto_progress_controller import ( + supersede_auto_progress_for_candidate_refreeze, + ) - # [STEP 5] 回填 task 字段(幂等覆盖) - task.inventory_source_status = 'candidates_frozen' - task.inventory_source_method = ( - 'manual_override_freeze' if frozen_by_id is not None - else (adjudication.method or 'rule_evaluation_freeze') - ) - task.inventory_source_config_version = config_version - task.inventory_routing_fingerprint = routing_fingerprint - # 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节 + supersede_auto_progress_for_candidate_refreeze(task) return CandidateFreezeResult( candidate_set_id=new_set.id, @@ -624,3 +622,204 @@ def freeze_candidates_for_task( manifest_snapshot_sha256=manifest_sha256, set_version=set_version, ) + + +def freeze_manual_line_source_selection( + task: ShippingNotice, + *, + line_no: int, + source_code: str, + actor_id: int | None, + reason: str | None, + execution_id: int | None, + session: Session | None = None, +) -> tuple[CandidateFreezeResult, bool]: + """ + 将通知准备的人工选源冻结为新的 CandidateSet 版本。 + + 核心逻辑:以冻结 Snapshot 的全量 line_no 为骨架,继承当前候选行的选择后仅替换目标项次。 + 没有自动候选时也会先创建全量 CandidateLine;未选源项保持空数组,只有每一项都有源时才返回 + ``all_lines_selected=True``,调用方据此允许进入库存准备/RPA。 + + Args: + task: 已冻结订单对应的 OT。 + line_no: 用户选择库存源的 Snapshot 项次,必须存在。 + source_code: 已启用库存源编码。 + actor_id: 操作人,用于候选源与候选行审计。 + reason: 人工选择原因。 + execution_id: 当前流程 Execution,用于绑定候选版本。 + session: 可选数据库会话。 + + Returns: + (CandidateFreezeResult, all_lines_selected)。 + + Raises: + ValueError: OT 未冻结 Snapshot 或项次不存在。 + """ + session = session or db.session + snapshot = ( + session.query(ShippingOrderSnapshot) + .filter(ShippingOrderSnapshot.task_id == int(task.id)) + .one_or_none() + ) + if snapshot is None: + raise ValueError('人工选源前必须先冻结订单 Snapshot') + + snapshot_lines = sorted(list(snapshot.lines or []), key=lambda row: int(row.line_no)) + wanted_line = int(line_no) + if not any(int(row.line_no) == wanted_line for row in snapshot_lines): + raise ValueError('未找到该订单项次') + + active_set = ( + session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + if task.active_inventory_candidate_set_id is not None else None + ) + existing_codes = { + int(row.line_no): [str(code).strip().upper() for code in (row.source_codes_json or []) if str(code).strip()] + for row in (active_set.lines if active_set is not None else []) + } + line_projections: list[dict[str, Any]] = [] + for row in snapshot_lines: + current_line_no = int(row.line_no) + codes = [source_code] if current_line_no == wanted_line else existing_codes.get(current_line_no, []) + line_projections.append({ + 'line_no': current_line_no, + 'source_line_no': str(row.line_no), + 'part_number': row.part_number, + 'reservation_id': row.reservation_id, + 'candidate_inventory_source_codes': codes, + }) + + source_codes = [] + for projection in line_projections: + for code in projection['candidate_inventory_source_codes']: + if code not in source_codes: + source_codes.append(code) + adjudication = InventorySourceAdjudication( + status='manual', + method='manual_line_selection', + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)), + candidates=[{'source_code': code} for code in source_codes], + evidence=[{'line_no': wanted_line, 'source_code': source_code, 'reason': reason or '人工指定库存源'}], + reason='manual_line_selection', + ) + result = freeze_candidates_for_task( + task, + adjudication=adjudication, + execution_id=execution_id, + frozen_by_id=actor_id, + line_projections=line_projections, + preserve_empty_line_candidates=True, + session=session, + ) + return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections) + + +def freeze_wave_notice_routing( + notice: ShippingNotice, + *, + source_notice: ShippingNotice | None = None, +) -> CandidateFreezeResult | None: + """ + 按波次自身行重跑库存源路由并冻结候选集(设计 D8:波次不再继承首通知源)。 + + 【AI 触发时机】建波次通知(post_ot_fulfillment_wave)且在写入波次 ShippingNoticeLine 后调用; + 仅当波次行需要独立路由(不同行可能不同仓)时使用。 + + 核心逻辑:以订单级 header(field_id 值)+ 波次行 ShippingNoticeLine.field_values_json + 逐行调用 ``evaluate_inventory_source_rules_for_field_values(scope='line')`` 得到行级候选; + 以全波次行候选并集作为任务级候选集,调用 ``freeze_candidates_for_task`` 冻结 Set/Source/Line + (候选快照已在本地,后续匹配不重复 RPA)。 + + Args: + notice: 已 flush 且已写入波次行的波次通知。 + source_notice: 订单首个冻结通知(提供订单级 header 事实);缺省用 notice。 + + Returns: + CandidateFreezeResult;无任何波次行候选时返回 None(交由无候选阻断,不冻结)。 + """ + from app.models.shipping_notice_line import ShippingNoticeLine + from app.services.shipping_notice.export import order_field_id_values + from app.services.shipping_notice.inventory_routing_engine import ( + evaluate_inventory_source_rules_for_field_values, + ) + + src = source_notice or notice + try: + header, _full_lines = order_field_id_values(src) + except ValueError: + header = {} + + wave_lines = ( + ShippingNoticeLine.query.filter_by(notice_id=int(notice.id)).order_by(ShippingNoticeLine.position).all() + if getattr(notice, 'id', None) is not None + else [] + ) + # [回退] 与首单路径一致(_collect_order_line_candidates):行级无规则命中时回退到订单级 task 候选集, + # 避免波次行「一条规则都不命中」时被算成无候选而卡死。 + task_result = evaluate_inventory_source_rules_for_field_values( + header_field_values=header, scope='task', + ) + task_source_codes = [str(c or '').strip().upper() for c in (getattr(task_result, 'source_codes', None) or []) if str(c or '').strip()] + + line_projections: list[dict[str, Any]] = [] + task_codes: list[str] = [] + seen: set[str] = set() + for idx, line in enumerate(wave_lines): + line_values = dict(getattr(line, 'field_values_json', None) or {}) + line_result = evaluate_inventory_source_rules_for_field_values( + header_field_values=header, + line_field_values=line_values, + scope='line', + ) + resolved = str(getattr(line_result, 'status', '') or '') == 'resolved' and bool(getattr(line_result, 'source_codes', None)) + if resolved: + codes = [str(c or '').strip().upper() for c in (getattr(line_result, 'source_codes', None) or []) if str(c or '').strip()] + else: + codes = list(task_source_codes) + if not codes: + codes = list(task_source_codes) + for code in codes: + if code not in seen: + seen.add(code) + task_codes.append(code) + line_projections.append({ + 'line_index': idx, + 'line_no': idx + 1, + 'source_line_no': str(getattr(line, 'line_no', None) or '').strip() or None, + 'part_number': str(getattr(line, 'part_number', None) or '').strip() or None, + 'reservation_id': str(getattr(line, 'reservation_id', None) or '').strip() or None, + 'candidate_inventory_source_codes': codes, + 'selection_mode': 'line_rule' if resolved else 'task_fallback', + 'routing_status': str(getattr(line_result, 'status', '') or ''), + 'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()), + }) + + if not task_codes: + return None + + from app.services.shipping_notice.inventory_source_rules import ( + InventorySourceAdjudication, + _candidate, + compute_routing_fingerprint, + extract_routing_context, + ) + + candidates = [] + for code in task_codes: + src_cfg = get_database_inventory_source(code) + if src_cfg: + candidates.append(_candidate(src_cfg)) + adjudication = InventorySourceAdjudication( + status='candidates_frozen', + method='wave_line_routing', + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(extract_routing_context(notice)), + candidates=candidates, + ) + return freeze_candidates_for_task( + notice, + adjudication=adjudication, + line_projections=line_projections, + ) diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/inventory_candidate_projection.py index 46bc4385..bb42bcff 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/inventory_candidate_projection.py @@ -2,9 +2,9 @@ services/shipping_notice/inventory_candidate_projection.py 用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。 -依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、 +依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、 ShippingTaskInventoryRpaAttempt。 -逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、 + 逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、 坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。 """ @@ -21,7 +21,7 @@ from app.models import ( ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, ShippingInventoryFile, - ShippingNotice, + ShippingOrderTask, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt, ) @@ -55,7 +55,7 @@ def _normalized_codes(codes: list[Any] | None) -> list[str]: def _candidate_set_filter( - task: ShippingNotice, + task: ShippingOrderTask, *, include_drafts: bool = False, session: Session | None = None, @@ -83,14 +83,14 @@ def _candidate_set_filter( def get_active_candidate_set( - task: ShippingNotice, + task: ShippingOrderTask, *, session: Session | None = None, ) -> ShippingInventoryCandidateSet | None: """ 读取正式 Task 当前 frozen CandidateSet。 - 核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id; + 核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id; 指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。 """ candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None) @@ -107,7 +107,7 @@ def get_active_candidate_set( def get_active_candidate_sources( - task: ShippingNotice, + task: ShippingOrderTask, *, session: Session | None = None, ) -> list[ShippingInventoryCandidateSource]: @@ -129,7 +129,7 @@ def get_active_candidate_sources( def get_active_candidate_lines( - task: ShippingNotice, + task: ShippingOrderTask, *, session: Session | None = None, ) -> list[ShippingInventoryCandidateLine]: @@ -150,8 +150,51 @@ def get_active_candidate_lines( return list(rows) +def active_inventory_runtime_facts( + task: ShippingOrderTask, + *, + session: Session | None = None, +) -> dict[str, Any]: + """ + 读取通知准备的当前运行事实,替代 OT 上的库存路由和快照投影列。 + + 核心逻辑:库存源只读当前 CandidateSet/Source;库存文件只读 active Link;配置版本 + 取 CandidateSource 的冻结版本,不能回读 Task 的可变历史字段。 + + Args: + task: 当前订单任务。 + session: 可选数据库会话。 + + Returns: + source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。 + """ + from app.models import ShippingTaskInventoryLink + + sess = _session(session) + candidate_set = get_active_candidate_set(task, session=sess) + sources = get_active_candidate_sources(task, session=sess) + source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()] + versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()] + link = ( + sess.query(ShippingTaskInventoryLink) + .filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True)) + .order_by(ShippingTaskInventoryLink.id.desc()) + .first() + if getattr(task, 'id', None) is not None else None + ) + return { + 'candidate_set': candidate_set, + 'candidate_set_id': getattr(candidate_set, 'id', None), + 'source_codes': source_codes, + 'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None, + 'active_link': link, + 'inventory_file_id': getattr(link, 'inventory_file_id', None), + 'inventory_file': getattr(link, 'inventory_file', None), + } + + def get_candidate_set_by_version( - task: ShippingNotice, + task: ShippingOrderTask, version: int, *, include_drafts: bool = False, @@ -271,7 +314,7 @@ def _candidate_lines_for_set( def build_inventory_candidate_blocking_reason( code: str, *, - task: ShippingNotice, + task: ShippingOrderTask, details: dict[str, Any] | None = None, ) -> dict[str, Any]: """构造统一 blocking_reason DTO。""" @@ -293,7 +336,7 @@ def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rule } -def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]: +def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]: """查询任务下每个候选源的最新 Attempt 摘要。""" task_no = str(getattr(task, 'task_no', '') or '').strip() if not task_no or not source_codes: @@ -346,7 +389,7 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str, return prepared, pending, failed -def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]: +def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]: """读取任务当前生效的行级匹配事实。""" if getattr(task, 'id', None) is None: return [] @@ -367,7 +410,7 @@ def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) def project_inventory_candidate_detail( - task: ShippingNotice, + task: ShippingOrderTask, *, version: str | int = 'current', session: Session | None = None, @@ -426,7 +469,7 @@ def project_inventory_candidate_detail( def project_inventory_candidate_facts( - task: ShippingNotice, + task: ShippingOrderTask, *, session: Session | None = None, include_history: bool = False, @@ -493,14 +536,20 @@ def project_inventory_candidate_facts( allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None)) serialized = { 'id': int(row.id), - 'line_key': str(row.line_key or ''), + 'snapshot_line_id': int(row.snapshot_line_id), + 'line_no': int(row.line_no), 'line_index': getattr(row, 'line_index', None), 'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'), 'candidate_set_id': getattr(row, 'candidate_set_id', None), 'candidate_set_version': getattr(row, 'candidate_set_version', None), 'candidate_line_id': getattr(row, 'candidate_line_id', None), 'allowed_source_codes_snapshot': allowed_codes, - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + # [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源), + # 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。 + 'resolved_inventory_source_code': ( + getattr(row, 'inventory_source_code', None) + or (allowed_codes[0] if len(allowed_codes) == 1 else None) + ), 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None), 'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')), diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index 8e34636c..d404cdec 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -3,7 +3,9 @@ services/shipping_notice/inventory_file_store.py 用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。 依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 -逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。 +逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); + fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution: + 冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。 """ from __future__ import annotations @@ -19,7 +21,15 @@ from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink +from app.models import ( + ShippingInventoryFile, + ShippingNotice, + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingTaskEvent, + ShippingTaskInventoryLink, +) +from app.services.shipping_notice.tool_common import task_event_task_id from app.services.shipping_notice.export import _storage_root from app.services.shipping_notice.inventory_snapshot import ( parse_inventory_excel_with_meta, @@ -29,10 +39,14 @@ from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, task_inventory_identity, ) -from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version +from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, +) def _can_relink_inventory(task: ShippingNotice) -> bool: """判断任务是否允许被新的批次库存快照影响;终态任务不能回退。""" - return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \ + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + return not has_verified_upload_success(task) \ and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'} @@ -129,11 +143,28 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None: def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None: - """读取任务当前 active link 指向的库存快照。""" - if task.id is None: + """ + 读取任务当前 active link 指向的库存快照。 + + 核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入 + ``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。 + + Args: + task: OT 或已绑定 ``order_task_id`` 的正式 Notice。 + + Returns: + 当前有效库存文件;无 active Link 时返回 None。 + """ + # [STEP] Link 归属 OT:Notice.id 与 OT.id 不同,禁止误用 Notice 主键查 Link。 + task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + if task_id is None: return None link = ( - ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True) + ShippingTaskInventoryLink.query.filter_by( + task_id=int(task_id), + is_active=True, + invalidated_at=None, + ) .order_by(ShippingTaskInventoryLink.id.desc()) .first() ) @@ -162,24 +193,33 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] | return path, filename +def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。""" + cached_rows = [ + row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict) + ] + if cached_rows: + return cached_rows, {'source': 'inventory_file_cache'} + + rows, column_meta = parse_inventory_snapshot_file(inv_file) + rows = [row for row in rows if isinstance(row, dict)] + if rows: + inv_file.inventory_lines_json = rows + inv_file.line_count = len(rows) + db.session.flush() + return rows, column_meta + + def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]: - """读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。""" + """读取任务活动库存文件的行事实;解析失败由调用方 Gate 转为可解释状态。""" inv_file = active_inventory_file_for_task(task) - if inv_file and isinstance(inv_file.inventory_lines_json, list): - rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)] - if not rows and Path(inv_file.storage_path).is_file(): - try: - reparsed, _meta = parse_inventory_snapshot_file(inv_file) - if reparsed: - inv_file.inventory_lines_json = reparsed - inv_file.line_count = len(reparsed) - db.session.flush() - rows = reparsed - except Exception: # noqa: BLE001 - # 解析失败时保留原快照,交由上层 Gate 报告可解释错误。 - pass + if inv_file is None: + return [] + try: + rows, _column_meta = read_inventory_file_lines(inv_file) return rows - return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] + except (OSError, ValueError, AppError): + return [] def resolve_inventory_lines_for_execution( @@ -188,22 +228,42 @@ def resolve_inventory_lines_for_execution( legacy_payload_lines: list[dict[str, Any]] | None = None, ) -> list[dict[str, Any]]: """ - 解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。 + 解析库存匹配与导出的统一运行输入。 + + 核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源 + ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File; + 否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。 Args: - task: 当前正式发货通知。 + task: 当前正式发货通知 / OT。 legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。 Returns: - 本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。 + 本次执行使用的库存行;不会回写任务或通知单的库存行缓存。 """ + # [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。 + from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, + ) + from app.services.shipping_notice.stp_line_inventory_match import ( + prepare_candidate_inventory_lines, + ) + + if len(task_frozen_inventory_source_codes(task)) >= 1: + prep = prepare_candidate_inventory_lines(task) + if prep.get('status') == 'ready': + rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)] + if rows: + return rows + + # [STEP 2] 单源 / 无冻结:活动 Link 文件是行事实。 if active_inventory_file_for_task(task) is not None: return active_inventory_lines_for_task(task) if isinstance(legacy_payload_lines, list): rows = [row for row in legacy_payload_lines if isinstance(row, dict)] if rows: return rows - return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] + return [] def has_uploaded_inventory_file(task: ShippingNotice) -> bool: @@ -214,6 +274,60 @@ def has_uploaded_inventory_file(task: ShippingNotice) -> bool: return False +def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool: + """判断 OT 是否已绑定一份有效且已解析的库存文件。""" + inv_file = active_inventory_file_for_task(task) + return bool( + inv_file is not None + and str(inv_file.snapshot_status or '').strip().lower() == 'ready' + and inv_file.invalidated_at is None + and int(inv_file.line_count or 0) > 0 + ) + + +def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]: + """读取 OT 当前有效的行级库存匹配事实。""" + task_id = getattr(task, 'id', None) + if task_id is None: + return [] + return ShippingNoticeLineInventoryMatch.query.filter_by( + task_id=int(task_id), is_current=True, + ).all() + + +def inventory_matches_complete_for_task(task: ShippingNotice) -> bool: + """判断当前 Match 是否已覆盖冻结订单全部项次且不在准备中。""" + task_id = getattr(task, 'id', None) + snapshot_id = getattr(task, 'order_snapshot_id', None) + if task_id is None or not snapshot_id: + return False + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) + if snapshot is None or not snapshot.lines: + return False + matches = { + int(row.snapshot_line_id): row + for row in current_inventory_matches_for_task(task) + if row.snapshot_line_id is not None + } + expected = {int(line.id) for line in snapshot.lines} + return set(matches) == expected and all( + str(row.match_result or '').strip().lower() != 'preparing' + for row in matches.values() + ) + + +def current_inventory_matches_have_shortage(task: ShippingNotice) -> bool: + """判断当前行级匹配中是否存在尚未满足的缺口或匹配失败。""" + for row in current_inventory_matches_for_task(task): + try: + shortage = float(row.shortage_qty or 0) + except (TypeError, ValueError): + shortage = 0.0 + if str(row.match_result or '').strip().lower() != 'matched' or shortage > 0: + return True + return False + + def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool: """判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。""" if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs): @@ -314,9 +428,11 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi mapping_source='parsing_profile', mapping_confirmed=True, source_code=source_code, - source_type=str(task.inventory_connector_type or "").strip() or None, + source_type=str( + (get_database_inventory_source(source_code) or {}).get('connector_type') or '' + ).strip() or None, warehouse_id=warehouse_id, - source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(), + source_config_version=inventory_sources_runtime_version(), source_query_json={'trigger_type': 'manual_upload'}, identity_status="pending", snapshot_status="ready", @@ -442,7 +558,7 @@ def replace_task_inventory_link( db.session.add(new_link) db.session.add( ShippingTaskEvent( - task_id=task.id, + task_id=task_event_task_id(task), event_type="inventory_file_linked", detail_json={ "inventory_file_no": inv_file.inventory_file_no, @@ -524,8 +640,6 @@ def apply_inventory_parse_result_to_linked_tasks( continue if not _can_relink_inventory(link.task): continue - link.task.inventory_snapshot_id = inv_file.id - link.task.inventory_lines_json = inventory_lines linked_tasks.append(link.task) return linked_tasks @@ -569,7 +683,8 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> task = link.task if not link.is_active or not task: continue - if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task): set_task_step_progress( task, step_key="step5_match_inventory", diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index f5eda453..9d7640d6 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -3,7 +3,8 @@ services/shipping_notice/inventory_mapping_workflow.py 用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。 依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。 -逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。 +逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析; + 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。 """ from __future__ import annotations @@ -13,6 +14,7 @@ from typing import Any from app import db from app.models import ShippingNotice from app.services.shipping_notice.inventory_file_store import ( + _can_relink_inventory, active_inventory_file_for_task, apply_inventory_parse_result_to_linked_tasks, start_inventory_file_linked_tasks, @@ -36,9 +38,14 @@ def inventory_loaded_response( field_mapping: dict[str, str] | None = None, mapping_source: str | None = None, commit: bool = True, + persist_lines: bool = True, ) -> dict[str, Any]: """ - 写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。 + 将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。 + + 核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库) + 写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态, + 禁止覆盖共享 File 上已有行缓存。 Args: task: 当前正式发货任务。 @@ -50,13 +57,18 @@ def inventory_loaded_response( field_mapping: published Profile 的字段映射快照。 mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。 commit: False 时仅 flush,供批量回调维持外层事务边界。 + persist_lines: False 时不写 File.inventory_lines_json(复用路径)。 Returns: Tool 标准响应;成功后任务可直接进入库存匹配。 """ inv_file = active_inventory_file_for_task(task) + if inv_file is None: + raise ValueError('OT 库存解析结果必须先绑定到有效库存文件') + + # [STEP] 首次落库写 File;复用只推进状态,避免共享快照被 OT 私有/合并行覆盖。 linked_tasks: list[ShippingNotice] = [] - if inv_file: + if persist_lines: linked_tasks = apply_inventory_parse_result_to_linked_tasks( inv_file, inventory_lines, @@ -65,7 +77,11 @@ def inventory_loaded_response( mapping_confirmed=True, ) else: - task.inventory_lines_json = inventory_lines + linked_tasks = [ + link.task + for link in (inv_file.links or []) + if link.is_active and link.task and _can_relink_inventory(link.task) + ] # [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态, # 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新 @@ -73,9 +89,6 @@ def inventory_loaded_response( for affected in [task, *linked_tasks]: if affected is None: continue - affected.match_status = None - affected.line_results_json = None - affected.shortage_json = None try: order_lines = task_line_purpose_values(task) @@ -127,6 +140,7 @@ def inventory_loaded_response( "column_meta": column_meta, "inventory_file_no": inv_file.inventory_file_no if inv_file else None, "linked_task_nos": [item.task_no for item in linked_tasks], + "persist_lines": bool(persist_lines), }, ) if commit: @@ -144,5 +158,6 @@ def inventory_loaded_response( "inventory_row_count": len(inventory_lines), "field_alignment": field_alignment, "warnings": warnings or [], + "persist_lines": bool(persist_lines), }, ) diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/inventory_parsing_profile.py index c7124551..f36fe1ca 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/shipping_notice/inventory_parsing_profile.py @@ -56,8 +56,37 @@ def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> se return match_ids | quantity_ids -def _validate_definition(raw: Any) -> dict[str, Any]: - """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。""" +# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。 +def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: + """校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。""" + from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS + + movement_codes = {field.code for field in MOVEMENT_FIELDS} + mapping = definition.get('field_mapping') or {} + mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()} + unknown = mapped_codes - movement_codes + if unknown: + raise ValidationError( + f'Movement parsing profile references unknown field: {sorted(unknown)}', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes} + if missing: + raise ValidationError( + f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + return mapped_codes + + +def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]: + """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。 + + Args: + raw: 解析定义对象。 + purpose: 'inventory'(沿用库存字段目录与 match_keys)或 + 'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 + """ if not isinstance(raw, dict): raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') field_mapping = raw.get('field_mapping') @@ -65,6 +94,19 @@ def _validate_definition(raw: Any) -> dict[str, Any]: raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') if any(not str(value or '').strip() for value in field_mapping.values()): raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + header_row_index = raw.get('header_row_index') + if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): + raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + + if purpose == 'movement': + _required_movement_field_ids(raw) + return { + 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, + 'header_row_index': header_row_index, + 'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()}, + 'match_keys': [], + } + catalog_fields = _catalog_fields(field_mapping) _required_catalog_field_ids(catalog_fields) match_keys = raw.get('match_keys') @@ -87,9 +129,6 @@ def _validate_definition(raw: Any) -> dict[str, Any]: seen_order_fields.add(field.id) seen_inventory_fields.add(inventory_field) normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field}) - header_row_index = raw.get('header_row_index') - if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): - raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') return { 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, 'header_row_index': header_row_index, @@ -151,7 +190,7 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: sample_analysis = profile.sample_analysis return { 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, - 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, + 'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, 'definition': profile.definition_json or {}, 'checksum': profile.checksum, 'published_at': profile.published_at.isoformat() if profile.published_at else None, 'source_count': len(profile.sources), @@ -193,6 +232,15 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id) db.session.add(profile) + purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower() + if purpose not in {'inventory', 'movement'}: + raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + if profile_id and purpose != profile.purpose: + raise ValidationError( + 'Draft parsing profile purpose is immutable', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + profile.purpose = purpose profile.display_name = str(data.get('display_name') or code).strip() requested_file_format = str(data.get('file_format') or 'xlsx').lower() if requested_file_format not in {'xls', 'xlsx', 'csv'}: @@ -203,7 +251,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', ) profile.file_format = requested_file_format - definition = _validate_definition(data.get('definition')) + definition = _validate_definition(data.get('definition'), purpose=purpose) if profile.file_format == 'csv' and definition.get('sheet_name'): raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') sample_analysis = _require_sample_evidence( diff --git a/backend/app/services/shipping_notice/inventory_recovery_service.py b/backend/app/services/shipping_notice/inventory_recovery_service.py index 8aa35058..0271b1f4 100644 --- a/backend/app/services/shipping_notice/inventory_recovery_service.py +++ b/backend/app/services/shipping_notice/inventory_recovery_service.py @@ -16,16 +16,19 @@ from app.models import ( ShippingInventoryFile, ShippingInventoryPreparationAttempt, ShippingInventoryPreparationSourceAttempt, - ShippingNotice, + ShippingOrderTask, + ShippingOrderCandidate, ShippingTaskInventoryLink, ) from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable +from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes +from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts def create_inventory_preparation_round( - *, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None, + *, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None, action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None, gate_attempt_id: int | None = None, ) -> ShippingInventoryPreparationAttempt: @@ -50,8 +53,7 @@ def create_inventory_preparation_round( db.session.flush() codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()] if not codes: - codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()] - codes = [code for code in codes if code] + codes = task_frozen_inventory_source_codes(task) active_file = active_inventory_file_for_task(task) for source_code in codes: reusable, _reuse_reasons = check_inventory_snapshot_reusable( @@ -76,8 +78,14 @@ def create_inventory_preparation_round( ) db.session.add(source) db.session.flush() + source_candidate = ( + db.session.query(ShippingOrderCandidate) + .filter(ShippingOrderCandidate.consumed_task_id == int(task.id)) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) round_row.combination_input_fingerprint = build_inventory_combination_fingerprint( - task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''), + task_snapshot_fingerprint=str(getattr(source_candidate, 'content_fingerprint', '') or ''), candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''), sources=[ { @@ -99,7 +107,7 @@ def create_inventory_preparation_round( for item in round_row.source_attempts ], reservation_version=str(getattr(task, 'order_data_version', '') or ''), - matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''), + matching_rule_version=str(active_inventory_runtime_facts(task).get('source_config_version') or ''), ) db.session.flush() return round_row diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 081964e4..15acc0fc 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -20,8 +20,8 @@ from typing import Any from app import db from app.core.errors import AppError, ServiceUnavailableError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent -from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING +from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent +from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file from app.services.shipping_notice.inventory_snapshot_store import ( find_latest_ready_snapshot, @@ -78,6 +78,30 @@ from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.task_disposition_service import task_execution_block_reason +def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask: + """将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。""" + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id: + owner = db.session.get(ShippingOrderTask, int(order_task_id)) + if owner is not None: + return owner + return task + + +def _set_workflow_error(task: ShippingNotice | ShippingOrderTask, message: str | None) -> None: + """写入库存流程错误;正式 Notice 通过关联 OT 承接。""" + owner = _workflow_owner(task) + if hasattr(owner, 'error_message'): + owner.error_message = message + + +def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None: + """读取库存流程错误;正式 Notice 通过关联 OT 承接。""" + return getattr(_workflow_owner(task), 'error_message', None) + + def latest_task_event(task: ShippingNotice, event_type: str) -> ShippingTaskEvent | None: """返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。""" if task.id is None: @@ -160,34 +184,22 @@ def _try_reuse_inventory_snapshot( ) db.session.flush() - cached_lines = [ - row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict) - ] - if cached_lines: + from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + try: + lines, column_meta = read_inventory_file_lines(snapshot) + except (OSError, ValueError, AppError): + lines, column_meta = [], {} + if lines: + # 复用:行缓存已由 read_inventory_file_lines 保证;只 Link + 推进,不覆盖 File。 return inventory_loaded_response( task, - cached_lines, - column_meta={"source": "snapshot_reuse"}, + lines, + column_meta=column_meta, source="snapshot_reuse", event_type="inventory_snapshot_reused", + persist_lines=False, ) - path = Path(snapshot.storage_path) - if path.is_file(): - from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file - - lines, column_meta = parse_inventory_snapshot_file(snapshot) - if lines: - snapshot.inventory_lines_json = lines - snapshot.line_count = len(lines) - return inventory_loaded_response( - task, - lines, - column_meta=column_meta, - source="snapshot_reuse", - event_type="inventory_snapshot_reused", - ) - db.session.commit() return tool_response( status="running", @@ -209,9 +221,11 @@ def _save_last_inventory_rpa_runtime(task: ShippingNotice, payload: dict[str, An source_code = str(payload.get("source_code") or "").strip() if source_code: runtime["source_code"] = source_code - step_payload = dict(task.step_payload_json or {}) - step_payload["last_inventory_rpa_runtime"] = runtime - task.step_payload_json = step_payload + owner = _workflow_owner(task) + if hasattr(owner, 'step_payload_json'): + step_payload = dict(owner.step_payload_json or {}) + step_payload["last_inventory_rpa_runtime"] = runtime + owner.step_payload_json = step_payload return runtime @@ -252,10 +266,10 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | Returns: tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。 """ - if ( - task.pending_human_reason != PH_RPA_PENDING - or task.inventory_lines_json - ): + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task): return None, None, None last_trigger = latest_task_event(task, "inventory_rpa_triggered") if not last_trigger or not isinstance(last_trigger.created_at, datetime): @@ -301,24 +315,43 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor "inventory_rpa_wait_rechecked", {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) + # [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落 + # rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。 + log_task_event( + task, + "inventory_rpa_failed", + { + "error": "timeout", + "elapsed_seconds": elapsed, + "timeout_seconds": timeout_seconds, + }, + ) + log_task_event( + task, + "inventory_rpa_exhausted", + {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, + ) db.session.flush() - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel" + apply_task_transition(task, TaskTransition.RPA_EXHAUSTED) + _set_workflow_error(task, "RPA 库存导出等待超时,已停止自动重试,请选择重新获取库存或上传库存 Excel") db.session.commit() return tool_response( status="needs_human", task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]: """从任务正式库存身份推导快照预期二元组。""" + from app.services.shipping_notice.inventory_source_gate import task_inventory_identity + + identity = task_inventory_identity(task) return ( - str(task.inventory_source_code or "").strip().upper(), - str(task.inventory_warehouse_id or "").strip().upper(), + str(identity['inventory_source_code'] or "").strip().upper(), + str(identity['inventory_warehouse_id'] or "").strip().upper(), ) @@ -627,23 +660,29 @@ def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str, return _expected_rpa_callback_run_no(task) -def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice: - """对任务行加悲观锁,防止并发回调重复消费同一轮次。""" +def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask: + """对订单任务行加悲观锁,防止并发回调重复消费同一轮次。""" if task.id is None: return task - # ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许 - # 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。 return ( - db.session.query(ShippingNotice) + db.session.query(ShippingOrderTask) .filter_by(id=task.id) - .with_for_update(of=ShippingNotice) + .with_for_update(of=ShippingOrderTask) .one() ) def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str: """读取已消费(处理完成)的 RPA 轮次 run_no。""" - return str(task.inventory_rpa_consumed_run_no or "").strip() + from app.models import ShippingTaskInventoryRpaAttempt + + attempt = ( + ShippingTaskInventoryRpaAttempt.query + .filter_by(task_no=str(task.task_no or ''), status='consumed') + .order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc()) + .first() + ) + return str(getattr(attempt, 'source_run_no', '') or '').strip() def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> None: @@ -651,7 +690,16 @@ def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> No effective = str(run_no or "").strip() if not effective: return - task.inventory_rpa_consumed_run_no = effective + from app.models import ShippingTaskInventoryRpaAttempt + + attempt = ( + ShippingTaskInventoryRpaAttempt.query + .filter_by(task_no=str(task.task_no or ''), source_run_no=effective) + .one_or_none() + ) + if attempt is not None: + attempt.status = 'consumed' + attempt.consumed_at = datetime.utcnow() def _validate_rpa_callback_not_replayed(task: ShippingNotice, run_no: str) -> str | None: @@ -789,7 +837,7 @@ def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None: "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, ) @@ -811,7 +859,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ 核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。 """ callback_source = str(payload.get("source_code") or "").strip().upper() - task_source = str(task.inventory_source_code or "").strip().upper() + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + task_sources = set(task_frozen_inventory_source_codes(task)) if not callback_source: return tool_response( status="failed", @@ -819,7 +869,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ message="RPA 成功回调缺少 source_code,已拒绝入库", data=serialize_task_for_tool(task), ) - if not task_source or callback_source != task_source: + if callback_source not in task_sources: return tool_response( status="failed", task=task, @@ -829,10 +879,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - source = get_database_inventory_source(task_source) + source = get_database_inventory_source(callback_source) is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed' callback_wh = str(payload.get("warehouse_id") or "").strip().upper() - task_wh = str(task.inventory_warehouse_id or "").strip().upper() + from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + + task_wh = resolve_inventory_source_warehouse_id(task, source=source) or '' if is_fixed and (not callback_wh or callback_wh != task_wh): return tool_response( status="failed", @@ -1026,7 +1078,9 @@ def _batch_snapshot_verify_warehouse_id( if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match': return None if task: - warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() + from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + + warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or '' return warehouse_id or None if item is not None: warehouse_id = str(item.get("warehouse_id") or "").strip().upper() @@ -1062,8 +1116,20 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[ return None -def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, Any]: - """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。""" +def ensure_inventory_via_rpa( + task: ShippingNotice, + *, + mode: str, + allow_auto_retry: bool = True, + source_codes: list[str] | None = None, +) -> dict[str, Any]: + """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。 + + Args: + allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。 + poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 + source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。 + """ from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" @@ -1101,7 +1167,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, ) @@ -1110,31 +1176,38 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa") except AppError: apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) - task.current_step = "step2_parse_confirm" - task.error_message = "库存源尚未确定,无法启动 RPA" + # OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。 + task.stage = "inventory_source_resolving" + _set_workflow_error(task, "库存源尚未确定,无法启动 RPA") db.session.commit() return tool_response( status="needs_human", task=task, message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", data=serialize_task_for_tool(task), - checkpoint=CP_INVENTORY_SOURCE_REVIEW, + position=POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) rpa_source = task_rpa_inventory_source(task) or {} - # 首次自动与人工重试都必须创建逐源 Attempt。只有该路径会冻结 + # 首次自动与人工显式重试才可能创建逐源 Attempt;自动路径读到失败事实时 + # 必须收口,不能重试。只有该路径会冻结 # source_run_no/lease_token/candidate_set/execution/gate 身份,Worker 回调才可精确收口。 # 下方保留的旧单票逻辑仅用于历史代码阅读,所有受支持 mode 均在这里返回。 if mode in {'auto', 'retry_rpa'}: from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared - prepared = ensure_all_required_sources_prepared(task, mode=mode) + prepared = ensure_all_required_sources_prepared( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=source_codes, + ) db.session.flush() if prepared.pending_source_codes: apply_task_transition(task, TaskTransition.RPA_PENDING) - task.error_message = None + _set_workflow_error(task, None) set_task_step_progress( task, step_key='step3_inventory_prepare', @@ -1158,6 +1231,11 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An ) if prepared.all_prepared: return tool_response(status='completed', task=task, message='库存快照已准备完成。') + # [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时返回 + # status='failed'(executor 的 _tool_outcome 映射为 blocked_retryable): + # 失败是可重试的技术结果,不是需要用户决策的人工阻断;重试由用户显式动作发起。 + # 显式重试/首次投递路径(allow_auto_retry=True)维持 needs_human 人工兑底。 + poll_read_only = not allow_auto_retry set_task_step_progress( task, step_key='step3_inventory_prepare', @@ -1172,11 +1250,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An ) db.session.commit() return tool_response( - status='needs_human', task=task, + status='failed' if poll_read_only else 'needs_human', task=task, message='库存 RPA 未能为全部库存源生成结果。', data={**serialize_task_for_tool(task), 'rpa': { 'failed_source_codes': prepared.failed_source_codes, 'source_attempts': prepared.source_attempts, + 'poll_read_only': poll_read_only, }}, ) @@ -1188,10 +1267,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An # [STEP 1] 先检查当前是否已有进行中的 RPA 导出。 # 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。 timeout_seconds = rpa_inventory_timeout_seconds() - if ( - task.pending_human_reason == PH_RPA_PENDING - and not task.inventory_lines_json - ): + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task): last_trigger = latest_task_event(task, "inventory_rpa_triggered") if last_trigger and isinstance(last_trigger.created_at, datetime): elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds()) @@ -1215,7 +1294,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An ) last_failed = latest_task_event(task, "inventory_rpa_failed") if not last_failed or (last_failed.created_at < last_trigger.created_at): - task.error_message = "RPA 库存导出等待超时" + _set_workflow_error(task, "RPA 库存导出等待超时") log_task_event( task, "inventory_rpa_failed", @@ -1227,14 +1306,14 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An ) db.session.flush( ) apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel" + _set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel") db.session.commit() return tool_response( status="needs_human", task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) # [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。 @@ -1256,10 +1335,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An except ServiceUnavailableError as exc: trigger = None detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE) - task.error_message = detail_message[:500] + _set_workflow_error(task, detail_message[:500]) if trigger: apply_task_transition(task, TaskTransition.RPA_PENDING) - task.error_message = None + _set_workflow_error(task, None) progress_message = ( "已重新触发库存获取,等待结果" if manual_retry_round @@ -1312,14 +1391,14 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An ) apply_task_transition(task, TaskTransition.INV_UNAVAIL) - offline_message = (task.error_message or "").strip() + offline_message = (_workflow_error(task) or "").strip() if offline_message == RPA_WORKER_OFFLINE_MESSAGE: human_message = RPA_WORKER_OFFLINE_MESSAGE detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。" else: human_message = "RPA 库存目录未配置或触发失败" detail = "请重新获取库存,或手动上传货代库存 Excel。" - task.error_message = human_message[:500] + _set_workflow_error(task, human_message[:500]) set_task_step_progress( task, step_key="step3_inventory_prepare", @@ -1338,7 +1417,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An task=task, message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message, data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) @@ -1469,15 +1548,7 @@ def _handle_rpa_inventory_skipped( detail = str(payload.get("message") or payload.get("error_message") or "").strip() message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail) apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = None - step_payload = dict(task.step_payload_json or {}) - step_payload["inventory_rpa_skipped"] = { - "skip_reason": skip_reason, - "message": detail or message, - "reported_at": datetime.utcnow().isoformat(), - "rpa_runtime": runtime, - } - task.step_payload_json = step_payload + _set_workflow_error(task, None) set_task_step_progress( task, step_key="step3_inventory_prepare", @@ -1506,7 +1577,7 @@ def _handle_rpa_inventory_skipped( task=task, message=message, data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) @@ -1519,9 +1590,9 @@ def _handle_rpa_inventory_failed( ) -> dict[str, Any]: """处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。""" apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] + _set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500]) log_task_event(task, "inventory_rpa_failed", { - "error": task.error_message, + "error": _workflow_error(task), "error_code": str(payload.get("error_code") or "rpa_export_failed"), "rpa_runtime": runtime, }) @@ -1530,7 +1601,7 @@ def _handle_rpa_inventory_failed( step_key='step3_inventory_prepare', step_title='获取库存', status='needs_human', - message=task.error_message, + message=_workflow_error(task), progress_percent=100, detail='请重新获取库存或上传库存 Excel。', extra={'error_code': str(payload.get('error_code') or 'rpa_export_failed')}, @@ -1544,11 +1615,51 @@ def _handle_rpa_inventory_failed( return tool_response( status="needs_human", task=task, - message=task.error_message, + message=_workflow_error(task), data=serialize_task_for_tool(task), ) +def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) -> None: + """收口回调处理失败,避免 RPA Attempt 与 Gate 留在外部等待。""" + from app.models import ShippingProcessExecution + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + for item in payload.get('results') or []: + if not isinstance(item, dict): + continue + task_no = str(item.get('task_no') or '').strip() + source_code = str(item.get('source_code') or '').strip().upper() + source_run_no = str(item.get('source_run_no') or '').strip() + task = resolve_task_from_payload({'task_no': task_no}, allow_conversation_fallback=False) + if not isinstance(task, ShippingOrderTask) or not source_code or not source_run_no: + continue + task = _lock_task_for_rpa_callback(task) + per_source_callback_handler( + task, + source_code=source_code, + run_no=source_run_no, + callback_payload={ + **dict(item), + 'schema_version': str(payload.get('schema_version') or item.get('schema_version') or ''), + 'error_code': 'callback_processing_failed', + 'error_message': error, + }, + ) + _handle_rpa_inventory_failed( + task, + {'error_code': 'callback_processing_failed', 'error_message': error}, + _save_last_inventory_rpa_runtime(task, payload), + commit=False, + ) + if task.active_process_execution_id: + execution = db.session.get(ShippingProcessExecution, int(task.active_process_execution_id)) + if execution is not None and str(execution.status or '').lower() != 'superseded': + sync_fulfillment_gates_from_task(execution=execution, actor_type='system') + db.session.commit() + + def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: """RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。""" from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response @@ -1756,7 +1867,9 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: trigger_type="on_demand", success=True, user_id=task.user_id, - verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None, + verify_warehouse_id=( + _expected_snapshot_identity_from_task(task)[1] or None + ), ) if not created_new: reuse_error = _validate_reused_snapshot_callback_file(inv_file, path) @@ -2044,6 +2157,43 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: ) +def _resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None: + """将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。 + + Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``, + Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。 + 安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。 + """ + text = str(raw_path or '').strip() + if not text: + return None + try: + root = allowed_root.resolve() + except OSError: + return None + + candidate = Path(text) + try: + resolved = candidate.resolve() + if resolved.is_file(): + resolved.relative_to(root) + return resolved + except (OSError, ValueError, RuntimeError): + pass + + name = Path(text.replace('\\', '/')).name.strip() + if not name or name in {'.', '..'} or '/' in name or '\\' in name: + return None + mapped = (root / name).resolve() + try: + mapped.relative_to(root) + except ValueError: + return None + if mapped.is_file(): + return mapped + return None + + def _persist_batch_callback_receipt( payload: dict[str, Any], *, @@ -2084,12 +2234,8 @@ def _persist_batch_callback_receipt( continue raw_path = str(item.get('file_path') or '').strip() - source_path = Path(raw_path).resolve() if raw_path else None - if source_path is None or not source_path.is_file(): - return None - try: - source_path.relative_to(allowed_root) - except ValueError: + source_path = _resolve_shared_inventory_drop_file(raw_path, allowed_root=allowed_root) + if source_path is None: return None suffix = source_path.suffix.lower() @@ -2120,27 +2266,34 @@ def _received_batch_callback_file_path( callback_id: str, ) -> Path | None: """验证 batch 处理可读取的文件仅来自 RPA drop 或本回调受控收件区。""" - candidate = Path(file_path).resolve() if file_path else None - if candidate is None or not candidate.is_file(): - return None - allowed_roots: list[Path] = [] - drop_dir = inventory_drop_dir() - if drop_dir is not None: - allowed_roots.append(drop_dir.resolve()) from app.services.shipping_notice.export import _storage_root safe_callback_id = ''.join( char if char.isalnum() or char in {'-', '_'} else '_' for char in callback_id ).strip('_') or 'unknown' - allowed_roots.append((_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve()) - for allowed_root in allowed_roots: - try: - candidate.relative_to(allowed_root) - return candidate - except ValueError: - continue - return None + receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve() + + drop_dir = inventory_drop_dir() + if drop_dir is not None: + mapped = _resolve_shared_inventory_drop_file(file_path, allowed_root=drop_dir) + if mapped is not None: + return mapped + + text = str(file_path or '').strip() + if not text: + return None + try: + candidate = Path(text).resolve() + except (OSError, RuntimeError): + return None + if not candidate.is_file(): + return None + try: + candidate.relative_to(receipt_root) + return candidate + except ValueError: + return None def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: @@ -2577,7 +2730,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any **(inv_file.schema_preview_json or {}), 'structure_validation': column_meta['structure_validation'], } - if lines and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active': + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if lines and not has_verified_upload_success(task) and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active': inventory_loaded_response( task, lines, @@ -2805,7 +2959,7 @@ def _validate_repair_inventory_snapshot( return "inventory_source_unstable" from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - source = get_database_inventory_source(task.inventory_source_code) + source = get_database_inventory_source(inv_file.source_code) if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed': if not inventory_identities_match( task, diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index e371ecc0..24df9f41 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -18,7 +18,9 @@ from sqlalchemy import event as _sa_event from sqlalchemy.orm import Session from app import db +from app.core.errors import AppError from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink +from app.services.shipping_notice.tool_common import task_event_task_id from app.services.shipping_notice.inventory_file_store import ( _can_relink_inventory, generate_inventory_file_no, @@ -468,24 +470,24 @@ def link_snapshot_to_task( from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - source = get_database_inventory_source(task.inventory_source_code) + source = get_database_inventory_source(inv_file.source_code) if source is None: return None resolved_warehouse_id = inv_file.warehouse_id if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match': from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse - lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)] - if not lines and Path(inv_file.storage_path).is_file(): - from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines - lines, _column_meta = parse_inventory_snapshot_file(inv_file) - inv_file.inventory_lines_json = lines - inv_file.line_count = len(lines) + try: + lines, _column_meta = read_inventory_file_lines(inv_file) + except (OSError, ValueError, AppError): + lines = [] resolution = resolve_dynamic_warehouse( task=task, inventory_lines=lines, fallback_warehouse_id=inv_file.warehouse_id, + source_code=inv_file.source_code, ) if not resolution.warehouse_id: # identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因 @@ -513,10 +515,6 @@ def link_snapshot_to_task( if not identity_ok: return None - # 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。 - if not task.inventory_warehouse_id: - task.inventory_warehouse_id = resolved_warehouse_id - link = replace_task_inventory_link(task, inv_file, role=role) link.link_reason = reason link.matched_warehouse_id = resolved_warehouse_id @@ -533,10 +531,9 @@ def link_snapshot_to_task( "inventory_file_no": inv_file.inventory_file_no, "trigger_type": (inv_file.source_query_json or {}).get("trigger_type"), } - task.inventory_snapshot_id = inv_file.id db.session.add( ShippingTaskEvent( - task_id=task.id, + task_id=task_event_task_id(task), event_type="inventory_snapshot_linked", detail_json={ "inventory_file_no": inv_file.inventory_file_no, @@ -574,7 +571,7 @@ def link_snapshot_to_task_for_preparation( from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - source = get_database_inventory_source(task.inventory_source_code) + source = get_database_inventory_source(inv_file.source_code) if ( source is None or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match' @@ -595,7 +592,6 @@ def link_snapshot_to_task_for_preparation( 'inventory_file_no': inv_file.inventory_file_no, 'identity_status': inv_file.identity_status, } - task.inventory_snapshot_id = inv_file.id return link diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index 743dc127..d84d0305 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -1,9 +1,10 @@ """ services/shipping_notice/inventory_source_gate.py -用途:库存源稳定性门禁、独立字段写入与路由指纹管理。 -依赖:inventory_source_rules、inventory_source_repository、models.ShippingNotice、core.errors。 +用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。 +依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。 逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备); + apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet; 解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。 """ @@ -12,7 +13,7 @@ from __future__ import annotations from typing import Any from app.core.errors import AppError -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.inventory_source_rules import ( InventorySourceAdjudication, adjudicate_inventory_source, @@ -29,8 +30,6 @@ from app.services.shipping_notice.inventory_source_repository import ( ) -STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"}) - INVENTORY_SOURCE_ERROR_CODES = { "unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED", "ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS", @@ -42,7 +41,7 @@ INVENTORY_SOURCE_ERROR_CODES = { } -def is_inventory_source_stable(task: ShippingNotice) -> bool: +def is_inventory_source_stable(task: ShippingOrderTask) -> bool: """ 判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。 @@ -50,135 +49,87 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool: STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。 不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。 """ - status = str(task.inventory_source_status or "").strip() - if status not in STABLE_INVENTORY_SOURCE_STATUSES: - return False + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - if status == "candidates_frozen": - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - - codes = task_frozen_inventory_source_codes(task) - return bool(codes) and all(get_database_inventory_source(code) for code in codes) - - code = str(task.inventory_source_code or "").strip().upper() - if not code: + codes = task_frozen_inventory_source_codes(task) + lines = get_active_candidate_lines(task) + if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines): return False - connector_type = str(task.inventory_connector_type or "").strip() - if not connector_type: - return False - source = get_database_inventory_source(code) - if not source: - return False - if connector_type != str(source.get("connector_type") or "").strip(): - return False - - mode = str(source.get('warehouse_resolution_mode') or '').strip().lower() - fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper() - task_warehouse = str(task.inventory_warehouse_id or '').strip().upper() - if mode == 'fixed' and task_warehouse != fixed_warehouse: - return False - + for code in codes: + source = get_database_inventory_source(code) + if not source: + return False + if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'fixed' and not str(source.get('fixed_warehouse_id') or '').strip(): + return False return True -def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool: +def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool: """比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。""" - previous = str(task.inventory_routing_fingerprint or "").strip() + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + + current = get_active_candidate_set(task) + previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip() if not previous: return False return previous != compute_routing_fingerprint(context) -def inventory_source_config_changed(task: ShippingNotice) -> bool: +def inventory_source_config_changed(task: ShippingOrderTask) -> bool: """ 配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。 核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务; 只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。 """ - status = str(task.inventory_source_status or "").strip() - if status not in STABLE_INVENTORY_SOURCE_STATUSES: - # 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。 - return bool(status) return not is_inventory_source_stable(task) -def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None: - """将标准化目的地线索写入任务独立字段。""" - task.destination_code = str(context.get("destination_code") or "").strip().upper() or None - task.destination_city = str(context.get("destination_city") or "").strip() or None - task.destination_country = str(context.get("destination_country") or "").strip().upper() or None - task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None - - -def clear_inventory_source_confirmation(task: ShippingNotice) -> None: +def clear_inventory_source_confirmation(task: ShippingOrderTask) -> None: """路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。""" - task.inventory_source_confirmed_by = None - task.inventory_source_confirmed_at = None - if str(task.inventory_source_status or "").strip() == "user_confirmed": - task.inventory_source_status = "unresolved" - task.inventory_source_method = None - payload = dict(task.step_payload_json or {}) + payload = dict(getattr(task, 'step_payload_json', None) or {}) payload.pop("rpa_inventory_source", None) task.step_payload_json = payload def apply_inventory_source_adjudication( - task: ShippingNotice, + task: ShippingOrderTask, adjudication: InventorySourceAdjudication, + *, + execution_id: int | None = None, ) -> None: """ - 将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。 - 核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。 + 将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。 + + 核心逻辑:仅 resolved / ambiguous / candidates_frozen 且候选非空时冻结; + unresolved/conflicted/invalid 即使误带候选也不得冻结(防全源兜底污染)。 + + Args: + execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前 + 正在执行的门禁链(否则会误 supersede 活动 Execution)。 """ - context = extract_routing_context(task) - fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context) - task.inventory_routing_fingerprint = fingerprint - apply_destination_fields(task, context) - - task.inventory_source_status = adjudication.status - task.inventory_source_method = adjudication.method or None - task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version() - - if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: - task.inventory_source_code = adjudication.source_code - task.inventory_connector_type = adjudication.connector_type - task.inventory_warehouse_id = adjudication.warehouse_id or None - elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES: - task.inventory_source_code = None - task.inventory_connector_type = None - task.inventory_warehouse_id = None - payload = dict(task.step_payload_json or {}) - payload.pop("rpa_inventory_source", None) - task.step_payload_json = payload - - payload = dict(task.step_payload_json or {}) - payload["inventory_source_resolution"] = { - "status": adjudication.status, - "method": adjudication.method, - "reason": adjudication.reason, - "destination_candidates": adjudication.destination_candidates, - "candidates": adjudication.candidates, - "evidence": adjudication.evidence, - "conflicts": adjudication.conflicts, - "config_version": adjudication.config_version, - "routing_fingerprint": fingerprint, - } - if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source - - rpa_source = task_rpa_inventory_source(task) - if rpa_source: - payload["rpa_inventory_source"] = rpa_source - else: - payload.pop("rpa_inventory_source", None) - task.step_payload_json = payload + status = str(adjudication.status or '').strip().lower() + if status not in {'resolved', 'ambiguous', 'candidates_frozen'}: + return + if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)): + freeze_candidates_for_task( + task, adjudication=adjudication, execution_id=execution_id, + ) -def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication: +def adjudicate_and_apply_inventory_source( + task: ShippingOrderTask, + *, + execution_id: int | None = None, +) -> InventorySourceAdjudication: """ 对任务执行库存源裁决并写入独立字段。 - 【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。 + 【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决; + 库存准备 Gate 在任务尚无冻结候选源时补裁决(传入当前 execution_id 以避免撤销活动链)。 + + Args: + execution_id: 可选;透传给冻结服务,使重冻结不撤销当前正在执行的门禁链。 """ context = extract_routing_context(task) if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context): @@ -201,7 +152,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour ) ): try: - freeze_result = freeze_candidates_for_task(task, adjudication=adjudication) + freeze_result = freeze_candidates_for_task( + task, adjudication=adjudication, execution_id=execution_id, + ) # 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段, # 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。 evidence_merged = list(adjudication.evidence or []) @@ -232,12 +185,12 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour # 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。 pass - apply_inventory_source_adjudication(task, adjudication) + apply_inventory_source_adjudication(task, adjudication, execution_id=execution_id) return adjudication def transition_task_to_inventory_source_review( - task: ShippingNotice, + task: ShippingOrderTask, adjudication: InventorySourceAdjudication, *, error_message: str | None = None, @@ -245,15 +198,17 @@ def transition_task_to_inventory_source_review( """ 将任务持久化到库存源规则重算检查点,并写入候选裁决信息。 - 核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮; - 解析复核必须在进入本检查点前完成,不保存延后复核标记。 + 核心逻辑:写入 INVENTORY_SOURCE_REVIEW 过渡与 stage,但不产生人工选源按钮; + 解析复核必须在进入本阶段前完成,不保存延后复核标记。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) - task.current_step = "step2_parse_confirm" + # OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流, + # 不能在通知准备前写入 OT。 + task.stage = "inventory_source_resolving" task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源" - payload = dict(task.step_payload_json or {}) + payload = dict(getattr(task, 'step_payload_json', None) or {}) payload["inventory_source_resolution"] = { "status": adjudication.status, "method": adjudication.method, @@ -268,7 +223,7 @@ def transition_task_to_inventory_source_review( task.step_payload_json = payload -def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication: +def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySourceAdjudication: """ 对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。 @@ -282,7 +237,7 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc def assert_inventory_source_gate( - task: ShippingNotice, + task: ShippingOrderTask, *, operation: str = "continue", ) -> None: @@ -307,36 +262,67 @@ def assert_inventory_source_gate( ) if is_inventory_source_stable(task): return - status = str(task.inventory_source_status or "unresolved").strip() - code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"]) - reason_by_status = { - "conflicted": "inventory_source_conflicted", - "changed": "inventory_source_changed", - "identity_mismatch": "inventory_source_identity_mismatch", - } + code = INVENTORY_SOURCE_ERROR_CODES['unresolved'] raise AppError( code=code, message="库存源尚未确定,无法继续后续流程", http_status=409, details={ "operation": operation, - "inventory_source_status": status, + "inventory_source_status": 'unresolved', "task_no": task.task_no, - "reason_code": reason_by_status.get(status, "require_manual_review"), + "reason_code": "require_manual_review", }, ) -def task_inventory_identity(task: ShippingNotice) -> dict[str, str | None]: - """返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。""" +def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]: + """返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。""" + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_codes = task_frozen_inventory_source_codes(task) + source_code = source_codes[0] if len(source_codes) == 1 else None + source = get_database_inventory_source(source_code) if source_code else None return { - "inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None, - "inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None, + "inventory_source_code": source_code, + "inventory_warehouse_id": resolve_inventory_source_warehouse_id(task, source=source), } +def resolve_inventory_source_warehouse_id( + task: ShippingOrderTask, + *, + source: dict[str, Any] | None, +) -> str | None: + """解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。""" + if not source: + return None + mode = str(source.get('warehouse_resolution_mode') or '').strip().lower() + if mode == 'fixed': + return str(source.get('fixed_warehouse_id') or '').strip().upper() or None + + task_id = getattr(task, 'id', None) + source_code = str(source.get('source_code') or '').strip().upper() + if not task_id or not source_code: + return None + from app.models import ShippingTaskInventoryLink + + link = ShippingTaskInventoryLink.query.filter_by( + task_id=int(task_id), + matched_source_code=source_code, + is_active=True, + ).order_by(ShippingTaskInventoryLink.id.desc()).first() + if link is None: + return None + return ( + str(link.matched_warehouse_id or '').strip().upper() + or str(getattr(link.inventory_file, 'warehouse_id', '') or '').strip().upper() + or None + ) + + def inventory_identities_match( - task: ShippingNotice, + task: ShippingOrderTask, *, source_code: str | None, warehouse_id: str | None, @@ -344,8 +330,7 @@ def inventory_identities_match( """ 校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。 - 核心逻辑:单源任务要求与 task.inventory_source_code 一致; - candidates_frozen 时允许文件源属于冻结候选集合。 + 核心逻辑:单源任务要求与唯一 CandidateSource 一致;多源允许文件源属于当前 CandidateSet。 """ if not is_inventory_source_stable(task): return False diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py index 599a7021..44e34072 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/inventory_source_rules.py @@ -4,7 +4,8 @@ services/shipping_notice/inventory_source_rules.py 用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。 依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。 逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行; - 本模块仍负责任务级裁决与快照消歧(履约阶段);Warehouse 由 Source/匹配决定。 + 行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源; + Warehouse 由 Source/匹配决定。 """ from __future__ import annotations @@ -15,7 +16,8 @@ from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any -from app.models import ShippingNotice +from app import db +from app.models import ShippingNotice, ShippingOrderSnapshot from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity from app.services.shipping_notice.inventory_source_repository import ( @@ -49,17 +51,26 @@ InventorySourceResolution = InventorySourceAdjudication def extract_routing_context(task: ShippingNotice) -> dict[str, Any]: - """投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。""" - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + """从冻结订单(冻结前为当前 Extraction)读取路由审计上下文。""" header = current_header_field_values_or_empty(task) + snapshot_id = getattr(task, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + if snapshot is not None: + fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or []) + frozen_values = dict(snapshot.header_values_json or {}) + header = { + str(field.get('field_code') or ''): frozen_values.get(str(field.get('field_id') or '')) + for field in fields + if field.get('scope') == 'header' and str(field.get('field_code') or '') + } return { - 'destination_code': task.destination_code, - 'destination_city': task.destination_city, - 'destination_country': task.destination_country, - 'warehouse_hint': task.warehouse_hint, + 'destination_code': header.get('destination_code'), + 'destination_city': header.get('destination_city'), + 'destination_country': header.get('destination_country'), + 'warehouse_hint': header.get('warehouse_hint'), 'customer_code': header.get('customer_code'), - 'customer_name': header.get('customer_name') or header.get('bill_to_customer'), - 'order_type': payload.get('order_type'), + 'customer_name': header.get('customer_name'), + 'order_type': header.get('order_type'), 'destination_candidates': [], } @@ -101,7 +112,12 @@ def _from_source(*, status: str, source: dict[str, Any], method: str, context: d def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication: - """将规则引擎候选集转换为可执行或待人工确认的裁决。""" + """ + 将规则引擎候选集转换为可执行或待人工确认的裁决。 + + 核心逻辑:只保留规则给出且当前仍可用的 Source;unresolved/空候选时 candidates + 必须为空,禁止回退到全部启用库存源(否则会错误触发全源 RPA)。 + """ sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))] evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}] if result.status == 'resolved' and len(sources) == 1: @@ -110,7 +126,7 @@ def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySo status=result.status, config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())], + candidates=[_candidate(item) for item in sources], evidence=evidence, reason='routing_rule_' + result.status, ) @@ -165,7 +181,7 @@ def resolve_ambiguous_source_from_ready_snapshots( if len(order_keys) != len(order_lines): return adjudication - from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot matched: list[tuple[dict[str, Any], Any]] = [] @@ -179,12 +195,10 @@ def resolve_ambiguous_source_from_ready_snapshots( if snapshot is None: checked.append({'source_code': source_code, 'snapshot': 'missing'}) continue - lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)] - if not lines: - try: - lines, _column_meta = parse_inventory_snapshot_file(snapshot) - except (OSError, ValueError): - lines = [] + try: + lines, _column_meta = read_inventory_file_lines(snapshot) + except (OSError, ValueError): + lines = [] inventory_keys = { key for row in lines if isinstance(row, dict) and (key := _snapshot_match_key(row)) @@ -227,19 +241,41 @@ def resolve_ambiguous_source_from_ready_snapshots( def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication: - """先评估任务级规则,再在所有订单行一致时接受行级规则结果。""" + """ + 先评估任务级规则,再在订单行一致时接受行级规则结果。 + + 核心逻辑:任务级有结论直接用;否则要求各行非 unresolved 且 + (status, source_codes) 一致(含 ambiguous 多候选)才采纳行级结果。 + 仅「各行 resolved 到不同单源」时合并为 ambiguous;不得把 unresolved 扩成全源。 + """ context = extract_routing_context(task) task_result = evaluate_inventory_source_rules(task=task) if task_result.status != 'unresolved': return _result_to_adjudication(task_result, context) line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in _task_routing_lines(task)] - resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1} - if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results): - return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context) - if len(resolved_codes) > 1: + # [STEP] 各行一致的非 unresolved(含 ambiguous)直接采纳,修复 PREFIX 多候选被丢弃。 + if line_results and all(item.status != 'unresolved' for item in line_results): + first = line_results[0] + if all( + item.status == first.status and item.source_codes == first.source_codes + for item in line_results + ): + return _result_to_adjudication(first, context) + resolved_codes = { + item.source_codes[0] + for item in line_results + if item.status == 'resolved' and len(item.source_codes) == 1 + } + if len(resolved_codes) > 1 and all(item.status == 'resolved' for item in line_results): return InventorySourceAdjudication( - 'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes], + 'ambiguous', + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[ + _candidate(item) + for item in list_database_inventory_sources() + if item['source_code'] in resolved_codes + ], reason='line_rules_resolve_different_sources', ) return _result_to_adjudication(task_result, context) @@ -251,10 +287,7 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: - """按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。""" - primary = get_database_inventory_source(task.inventory_source_code) - if primary is not None: - return primary + """按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。""" from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes for code in task_frozen_inventory_source_codes(task): @@ -265,7 +298,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None: - """持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。""" + """持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。""" from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication del source diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py index ddc06ab4..5de59882 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/inventory_upload.py @@ -19,7 +19,7 @@ from typing import Any from flask import current_app from werkzeug.datastructures import FileStorage -from app.models import ShippingInventoryFile, ShippingNotice +from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.export import _storage_root from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path _TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv") @@ -163,7 +163,7 @@ def install_task_inventory_attachment_from_file( def rebuild_task_inventory_attachment_from_snapshot( - task: ShippingNotice | str, + task: ShippingOrderTask | ShippingNotice | str, inv_file: ShippingInventoryFile, ) -> Path: """ @@ -177,7 +177,7 @@ def rebuild_task_inventory_attachment_from_snapshot( Returns: 重建后的任务正式附件路径。 """ - task_no = task.task_no if isinstance(task, ShippingNotice) else str(task or "").strip() + task_no = str(getattr(task, "task_no", task) or "").strip() if not task_no: raise ValueError("task_no is required") storage_path = Path(str(inv_file.storage_path or "")) diff --git a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py b/backend/app/services/shipping_notice/inventory_warehouse_resolution.py index 9c7bbb9b..f5e16c2b 100644 --- a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py +++ b/backend/app/services/shipping_notice/inventory_warehouse_resolution.py @@ -29,9 +29,9 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: return values if values and all(values) else None -def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution: +def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution: """按站点已发布解析方案为全部订单行寻找唯一 Warehouse。""" - source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first() + source = ShippingInventorySource.query.filter_by(source_code=source_code).first() definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)] diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index a734c743..30608a44 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -2,8 +2,11 @@ services/shipping_notice/inventory_workflow.py 用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。 -依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、动态订单字段。 -逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。 +依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、 + inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 +逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除; + payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓); + STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。 """ from __future__ import annotations @@ -13,9 +16,9 @@ from typing import Any from app import db from app.core.errors import AppError -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, + POSITION_INVENTORY_SOURCE_REVIEW, ) from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload @@ -52,7 +55,108 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non return None -def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, Any] | None: +def _link_ready_candidate_prep_or_block( + task: ShippingOrderTask, + prep: dict[str, Any], + *, + lang: str, +) -> dict[str, Any] | None: + """ + STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。 + + 核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded + 快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human, + 禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。 + + Args: + task: 已冻结候选源的订单任务。 + prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。 + lang: 文案语言。 + + Returns: + None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。 + """ + from app.models import ShippingInventoryFile + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + + # [STEP 1] 已绑定则无需重复 link。 + if active_inventory_file_for_task(task) is not None: + return None + + # [STEP 2] 从候选准备证据解析待绑定快照编号。 + file_no = '' + for item in list(prep.get('evidence') or []): + if not isinstance(item, dict): + continue + if str(item.get('status') or '').strip().lower() != 'loaded': + continue + file_no = str(item.get('inventory_file_no') or '').strip() + if file_no: + break + if not file_no: + for row in list(prep.get('lines') or []): + if not isinstance(row, dict): + continue + file_no = str(row.get('__inventory_file_no') or '').strip() + if file_no: + break + + inv_file = ( + ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first() + if file_no + else None + ) + link = None + if inv_file is not None: + link = link_snapshot_to_task( + task, + inv_file, + reason='stp_candidate_prep', + role='owner', + audit_payload={ + 'candidate_set_id': prep.get('candidate_set_id'), + 'loaded_source_codes': list(prep.get('loaded_source_codes') or []), + }, + ) + if link is not None: + db.session.flush() + return None + + # [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。 + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key='step3_inventory_prepare', + step_title='获取库存', + status='needs_human', + message=t('workflow.inventory.unavailable', lang=lang), + progress_percent=0, + detail=t('workflow.inventory.unavailable', lang=lang), + ) + log_task_event( + task, + 'inventory_candidate_link_failed', + { + 'inventory_file_no': file_no or None, + 'loaded_source_codes': list(prep.get('loaded_source_codes') or []), + 'candidate_set_id': prep.get('candidate_set_id'), + }, + ) + db.session.commit() + return tool_response( + status='needs_human', + task=task, + message=t('workflow.inventory.unavailable', lang=lang), + data={ + **serialize_task_for_tool(task), + 'blocking_reason': {'code': 'inventory_file_missing'}, + 'inventory_file_no': file_no or None, + }, + ) + + +def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None: """ 库存入口统一检查订单侧 Reservation ID。 @@ -74,7 +178,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, forbidden_next_tools=[ "ensure_inventory", @@ -86,7 +190,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, ) -def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lang: str) -> dict[str, Any] | None: +def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, lang: str) -> dict[str, Any] | None: """ 库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。 核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。 @@ -102,7 +206,7 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan task=task, message='订单解析已确认后必须先冻结订单快照,才能进入库存链路。', data={**serialize_task_for_tool(task), 'error_code': 'SHIPPING.ORDER_SNAPSHOT_REQUIRED'}, - checkpoint='order_freeze', + position='order_freeze', stop_agent_turn=True, forbidden_next_tools=['ensure_inventory', 'parse_inventory', 'match_inventory', 'generate_shipment_excel'], ) @@ -112,6 +216,43 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan reservation_gate = _reservation_gate_response(task, lang=lang) if reservation_gate is not None: return reservation_gate + if operation == "ensure_inventory": + # [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或 + # 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。 + from app.services.shipping_notice.inventory_candidate_projection import ( + get_active_candidate_lines, + get_active_candidate_set, + get_active_candidate_sources, + ) + + candidate_set = get_active_candidate_set(task) + sources = get_active_candidate_sources(task) + lines = get_active_candidate_lines(task) + invalid_lines = [ + line for line in lines + if not list(getattr(line, "source_codes_json", None) or []) + ] + if ( + not task.order_snapshot_id + or candidate_set is None + or str(getattr(candidate_set, "lifecycle_status", "") or "").lower() != "frozen" + or not sources + or not lines + or invalid_lines + ): + return tool_response( + status="needs_human", + task=task, + message="库存源候选集尚未冻结完成,暂不能准备库存。", + data={ + **serialize_task_for_tool(task), + "error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED", + "position": POSITION_INVENTORY_SOURCE_REVIEW, + }, + position=POSITION_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"], + ) if is_inventory_source_stable(task): return None try: @@ -123,7 +264,7 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan task=task, message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) return None @@ -138,7 +279,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang) if gate_resp is not None: return gate_resp - if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if has_verified_upload_success(task) or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}: return tool_response( status="failed", task=task, @@ -253,6 +395,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: resume_gate_code='inventory_preparation', operator_id=operator_id, inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto', + line_scope_key=( + str( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + or '' + ).strip() or None + ), ) lang = resolve_lang(payload) task = resolve_task_from_payload(payload) @@ -267,6 +417,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 1] 优先接受当前请求直接携带的库存明细。 # 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。 mode = str(payload.get("mode") or "auto").strip().lower() + # 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实, + # 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。 + allow_auto_retry = bool(payload.get('allow_auto_retry', True)) + scoped_source_codes = [ + str(code).strip().upper() + for code in (payload.get('source_codes') or []) + if str(code).strip() + ] or None inventory_lines = parse_inventory_lines(payload) if inventory_lines: return inventory_loaded_response( @@ -280,7 +438,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: if mode == "retry_rpa": from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa - return ensure_inventory_via_rpa(task, mode=mode) + return ensure_inventory_via_rpa( + task, mode=mode, source_codes=scoped_source_codes, + ) if mode == "auto": from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot @@ -290,7 +450,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。 frozen_codes = task_frozen_inventory_source_codes(task) - if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen': + if len(frozen_codes) >= 1: prep = prepare_candidate_inventory_lines(task) if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing': apply_task_transition(task, TaskTransition.INV_UNAVAIL) @@ -319,7 +479,75 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: }, }, ) - if prep.get('status') == 'missing_files': + if prep.get('status') in {'missing_files', 'partial_missing'}: + # [STEP] 缺失源自动批次探测(设计 D3/D4):不再停在 needs_human; + # 已有 ready 快照的源由 ensure_all_required_sources_prepared 复用, + # 仅缺失源进入单批次 trigger;回调后由下一轮 ensure 继续推进匹配。 + from app.services.shipping_notice.per_source_rpa_service import ( + ensure_all_required_sources_prepared, + ) + probe = ensure_all_required_sources_prepared( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=scoped_source_codes, + ) + if probe.pending_source_codes: + apply_task_transition(task, TaskTransition.RPA_PENDING) + task.error_message = None + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="running", + message="已触发库存获取,等待各库存源回调。", + progress_percent=60, + detail="等待库存 RPA 回调", + ) + db.session.commit() + return tool_response( + status="running", + task=task, + message="已触发库存获取,等待各库存源回调。", + data={ + **serialize_task_for_tool(task), + 'rpa': {'pending_source_codes': list(probe.pending_source_codes)}, + }, + ) + if probe.all_prepared: + # 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。 + prep = prepare_candidate_inventory_lines(task) + else: + # 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。 + log_task_event(task, "inventory_probe_failed", { + 'failed_source_codes': list(probe.failed_source_codes or []), + }) + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message="库存 RPA 未能为全部库存源生成结果。", + progress_percent=100, + detail="请重新获取库存或上传库存 Excel。", + ) + db.session.commit() + return tool_response( + # [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时 + # 返回 status='failed'(executor 映射为 blocked_retryable), + # 不伪装成人工阻断;显式路径维持 needs_human。 + status="failed" if not allow_auto_retry else "needs_human", + task=task, + message="库存 RPA 未能为全部库存源生成结果。", + data={ + **serialize_task_for_tool(task), + 'blocking_reason': {'code': 'inventory_preparation_failed'}, + 'poll_read_only': not allow_auto_retry, + }, + ) + if prep.get('status') in {'missing_files', 'partial_missing'}: + # 防御:探测后仍缺失(如快照在探测窗口内失效),不得带着残缺数据进入匹配。 apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, @@ -343,40 +571,17 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: 'missing_source_codes': prep.get('missing_source_codes') or [], }, ) - if prep.get('status') == 'partial_missing': - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - set_task_step_progress( - task, - step_key="step3_inventory_prepare", - step_title="获取库存", - status="needs_human", - message=t("workflow.inventory.unavailable", lang=lang), - progress_percent=0, - detail=t("workflow.inventory.unavailable", lang=lang), - ) - log_task_event(task, "inventory_candidate_files_partial", { - 'missing_source_codes': prep.get('missing_source_codes') or [], - 'loaded_source_codes': prep.get('loaded_source_codes') or [], - }) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.unavailable", lang=lang), - data={ - **serialize_task_for_tool(task), - 'missing_source_codes': prep.get('missing_source_codes') or [], - 'loaded_source_codes': prep.get('loaded_source_codes') or [], - }, - ) - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response - + # [STEP] ready 快照复用:先 Link,再只推进状态;不把合并行写进共享 File。 + link_block = _link_ready_candidate_prep_or_block(task, prep, lang=lang) + if link_block is not None: + return link_block return inventory_loaded_response( task, list(prep.get('lines') or []), column_meta={'source': 'stp_candidate_prep'}, source='stp_candidate_prep', event_type='inventory_candidates_prepared', + persist_lines=False, ) reused = _try_reuse_inventory_snapshot( @@ -391,11 +596,18 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 否则任务会错误停在人审且没有可执行的恢复动作。 from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa - return ensure_inventory_via_rpa(task, mode=mode) + return ensure_inventory_via_rpa( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=scoped_source_codes, + ) # [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。 # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 - if task.inventory_lines_json: + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + if has_ready_inventory_file_for_task(task): apply_task_transition(task, TaskTransition.INVENTORY_READY) db.session.commit() return tool_response( diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 7b702675..b6cebb0d 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -3,8 +3,10 @@ services/shipping_notice/lifecycle_projection.py 用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 -逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。 - 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 +逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因; + [B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时 + 兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作; + 阶段入口与实际动作权限必须分开。 """ from __future__ import annotations @@ -36,6 +38,9 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { 'duplicate_detection': 'order_review', 'field_conflict_resolution': 'order_review', 'order_freeze_readiness': 'order_review', + # 建单前已存在当前有效 Candidate 的未确认 Review Case 仍属「订单复核」工作面: + # 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。 + 'order_review_build': 'order_review', 'task_creation': 'order_review', 'inventory_source_routing': 'fulfillment_prep', 'inventory_preparation': 'fulfillment_prep', @@ -49,8 +54,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { } # 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于 -# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在 -# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。 +# 读模型展示,不推进订单、不创建任务,也不授予任何动作。[B''] 它是阶段的唯一 +# 权威;正式 Gate 仅在技术阶段缺失时提供兜底,不能覆盖有效处理阶段。 LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'upload_received': 'intake_parse', 'email_parsing': 'intake_parse', @@ -60,7 +65,7 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'waiting_review': 'order_review', 'customer_resolving': 'order_review', 'duplicate_checking': 'order_review', - 'inventory_source_resolving': 'order_review', + 'inventory_source_resolving': 'fulfillment_prep', 'order_creating': 'fulfillment_prep', 'inventory_fetching': 'fulfillment_prep', 'inventory_preparation': 'fulfillment_prep', @@ -114,11 +119,12 @@ def project_lifecycle( verified_upload_success: bool = False, processing_stage: str | None = None, ) -> dict[str, Any]: - """按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。 + """按成功事实 → 已持久化阶段 → 正式 Gate → 阻断归属的固定优先级裁决生命周期。 - ``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能 - 授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算 - 阶段或放开按钮。 + [B''] 阶段唯一权威:只要 ``processing_stage``(OT.stage / Run.processing_stage)是合法 + 15 阶成员,就直接映射五阶段,正式 Gate 不能覆盖或升降它。``gate_code`` 只在处理 + 阶段缺失时兜底(如任务详情无 OT.stage 上下文),且仅用于「订单检查」面板诊断; + 它不再能改变阶段。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。 """ gate = current_gate if isinstance(current_gate, dict) else {} gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() @@ -127,14 +133,16 @@ def project_lifecycle( if verified_upload_success: lifecycle_stage = 'upload_complete' authority = 'verified_upload_success' - elif gate_code in LIFECYCLE_STAGE_BY_GATE: - lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] - authority = 'process_gate' + # [B''] 处理阶段是阶段唯一权威。合法 15 阶直接映射五阶段;Gate 不再覆盖它。 elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[ str(processing_stage or '').strip().lower() ] authority = 'processing_stage' + # [B''] 正式 Gate 仅在处理阶段缺失时兜底,用于「订单检查」面板,不改变阶段。 + elif gate_code in LIFECYCLE_STAGE_BY_GATE: + lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] + authority = 'process_gate' else: reason = blocking_reason if isinstance(blocking_reason, dict) else {} reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip() diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py index 973b9d34..be7ff00b 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -24,7 +24,7 @@ from app.services.shipping_notice.line_inventory_match_persistence import resolv from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, - list_eligible_post_ot_line_keys, + list_eligible_post_ot_snapshot_line_ids, ) from app.services.shipping_notice.order_review_fulfillment_decision_service import ( project_review_case_line_decisions, @@ -35,7 +35,7 @@ from app.services.shipping_notice.post_ot_wave_progress_service import schedule_ def _mark_auto_fulfill_failed( case: ShippingOrderReviewCase, *, - line_keys: list[str], + snapshot_line_ids: list[str], error_code: str, message: str, ) -> None: @@ -46,12 +46,18 @@ def _mark_auto_fulfill_failed( """ now = datetime.utcnow() formal_task_id = getattr(case, 'confirmed_task_id', None) - for key in line_keys: + projection = project_review_case_line_decisions(case) + draft_id_by_snapshot_id = { + str(item.get('snapshot_line_id')): str(item.get('draft_line_id') or '').strip() + for item in list(projection.get('lines') or []) + if isinstance(item, dict) and item.get('snapshot_line_id') is not None + } + for key in snapshot_line_ids: key_s = str(key) if formal_task_id is not None: fact = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True) + .filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True) .first() ) if fact is not None: @@ -67,9 +73,12 @@ def _mark_auto_fulfill_failed( fact.detail_json = detail fact.updated_at = now + draft_line_id = draft_id_by_snapshot_id.get(key_s) + if not draft_line_id: + continue row = ( ShippingOrderReviewLineDecision.query - .filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True) + .filter_by(review_case_id=int(case.id), draft_line_id=draft_line_id, is_active=True) .first() ) if row is None: @@ -116,10 +125,10 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, } - eligible = list_eligible_post_ot_line_keys(case) + eligible = list_eligible_post_ot_snapshot_line_ids(case) projection = project_review_case_line_decisions(case) unassigned = [ - str(item.get('line_key') or '') + str(item.get('snapshot_line_id') or '') for item in list(projection.get('lines') or []) if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'} ] @@ -129,7 +138,7 @@ def coordinate_post_ot_auto_fulfill( 'reason': 'no_eligible_lines', 'trigger': trigger, 'case_no': case.case_no, - 'accepted_line_keys': [], + 'accepted_snapshot_line_ids': [], } # [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并, # 绝不静默替用户决定 Notice 的合并范围。 @@ -139,7 +148,7 @@ def coordinate_post_ot_auto_fulfill( 'reason': 'manual_wave_selection_required', 'trigger': trigger, 'case_no': case.case_no, - 'accepted_line_keys': [], + 'accepted_snapshot_line_ids': [], } idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}' @@ -147,7 +156,7 @@ def coordinate_post_ot_auto_fulfill( # [STEP 1] 整波创建(失败则整波回滚) result = create_post_ot_fulfillment_wave( case_no=str(case.case_no), - line_keys=eligible, + snapshot_line_ids=[int(item) for item in eligible], decision_source='system', actor_user_id=None, reason=f'auto_fulfill:{trigger}', @@ -157,7 +166,7 @@ def coordinate_post_ot_auto_fulfill( progress = schedule_post_ot_wave_progress( task_no=str(result.get('task_no') or ''), wave_no=result.get('wave_no'), - line_keys=list(result.get('accepted_line_keys') or eligible), + snapshot_line_ids=[int(item) for item in (result.get('accepted_snapshot_line_ids') or eligible)], review_case_id=int(result.get('review_case_id') or case.id), idempotency_row_id=result.get('idempotency_row_id'), request_idempotency_key=str(result.get('idempotency_key') or idem_key), @@ -170,7 +179,7 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, 'wave_progress': progress, **{k: result.get(k) for k in ( - 'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys', + 'task_no', 'wave_no', 'accepted_snapshot_line_ids', 'skipped_snapshot_line_ids', 'idempotency_row_id', 'idempotent_replay', )}, } @@ -185,7 +194,7 @@ def coordinate_post_ot_auto_fulfill( if refreshed is not None: _mark_auto_fulfill_failed( refreshed, - line_keys=eligible, + snapshot_line_ids=eligible, error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED', message=str(exc)[:1000], ) @@ -195,7 +204,7 @@ def coordinate_post_ot_auto_fulfill( 'trigger': trigger, 'case_no': case_no_hint, 'error': str(exc)[:500], - 'eligible_line_keys': eligible, + 'eligible_snapshot_line_ids': eligible, } diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 707b26c7..63835bef 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -3,7 +3,7 @@ services/shipping_notice/line_inventory_match_persistence.py 用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。 依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。 -逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库; +逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库; 新快照新增行并切换 is_current;不覆盖历史快照事实。 """ @@ -26,19 +26,6 @@ from app.services.shipping_notice.inventory_candidate_projection import ( ) -def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]: - """Case 草稿行序 → line_key。""" - if case is None or case.current_draft is None: - return {} - out: dict[int, str] = {} - for idx, line in enumerate(list(case.current_draft.lines_json or [])): - if not isinstance(line, dict): - continue - key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}' - out[idx] = key - return out - - def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None: """ 反查确认到该 OT 的 Review Case。 @@ -85,6 +72,24 @@ def map_disposition_to_match_codes( return 'result_missing', 'unavailable' +def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> str | None: + """ + 行级已定源:优先取匹配结果,缺失时回退到任务级已定源(Approach 1)。 + + 核心逻辑:匹配未回填源时,只有当前 CandidateSet 恰有一个源才回填; + 不从 OT 读取任务级库存源投影。 + """ + src = str(result.get('resolved_inventory_source_code') or '')[:64] or None + if src: + return src + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_codes = task_frozen_inventory_source_codes(task) + if len(source_codes) == 1: + return source_codes[0][:64] + return None + + def persist_line_inventory_match_facts( *, task: ShippingNotice, @@ -95,14 +100,15 @@ def persist_line_inventory_match_facts( """ 将 match_order_lines_across_candidates 结果持久化为当前事实。 - 核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current; + 核心逻辑:按冻结订单行项次解析 snapshot_line_id;同快照幂等更新;否则新增并切换 is_current; 无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。 """ case = resolve_review_case_for_task(task) - keys_by_index = _draft_line_keys_by_index(case) snap_id = inventory_snapshot_id - if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None: - snap_id = int(task.inventory_snapshot_id) + if snap_id is None: + from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts + + snap_id = active_inventory_runtime_facts(task).get('inventory_file_id') # 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的 # 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。 snapshot_file_no = None @@ -129,6 +135,12 @@ def persist_line_inventory_match_facts( int(row.line_no): row for row in get_active_candidate_lines(task) } + from app.models import ShippingOrderSnapshot + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None + snapshot_lines_by_no = { + int(line.line_no): line for line in (snapshot.lines if snapshot is not None else []) + if str(getattr(line, 'line_no', '') or '').isdigit() + } for result in line_results: try: @@ -136,15 +148,11 @@ def persist_line_inventory_match_facts( except (TypeError, ValueError): continue res = res_by_index.get(index) or {} - # Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底, - # 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。 - line_key = str( - keys_by_index.get(index) - or res.get('line_key') - or f'line-{index + 1}' - ).strip() - if not line_key: + line_no = index + 1 + snapshot_line = snapshot_lines_by_no.get(line_no) + if snapshot_line is None: continue + snapshot_line_id = int(snapshot_line.id) match_result, inventory_status = map_disposition_to_match_codes( disposition=str(result.get('disposition') or res.get('disposition') or ''), @@ -192,7 +200,8 @@ def persist_line_inventory_match_facts( ShippingNoticeLineInventoryMatch.query .filter_by( task_id=int(task.id), - line_key=line_key, + snapshot_line_id=snapshot_line_id, + line_no=line_no, inventory_snapshot_id=int(snap_id), ) .first() @@ -200,7 +209,7 @@ def persist_line_inventory_match_facts( if existing is None and snap_id is None: existing = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id), line_key=line_key, is_current=True) + .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) .filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None)) .first() ) @@ -208,18 +217,17 @@ def persist_line_inventory_match_facts( if existing is None: ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id), line_key=line_key, is_current=True) + .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) - # Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实, - # 避免同一订单行同时存在两个 current 投影。 + # 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。 ( ShippingNoticeLineInventoryMatch.query .filter_by(task_id=int(task.id), line_index=index, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) # [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number) - src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None + src_code = _line_resolved_source_code(task, result) file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref') try: @@ -249,7 +257,8 @@ def persist_line_inventory_match_facts( row = ShippingNoticeLineInventoryMatch( task_id=int(task.id), review_case_id=int(case.id) if case is not None else None, - line_key=line_key, + snapshot_line_id=snapshot_line_id, + line_no=line_no, line_index=index, candidate_set_id=( int(current_candidate_set.id) @@ -301,7 +310,7 @@ def persist_line_inventory_match_facts( written.append(row) else: # [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index - src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None + src_code = _line_resolved_source_code(task, result) file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref') try: @@ -374,14 +383,13 @@ def persist_line_inventory_match_facts( ShippingNoticeLineInventoryMatch.query .filter( ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.line_key == line_key, + ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id, ShippingNoticeLineInventoryMatch.id != int(existing.id), ShippingNoticeLineInventoryMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) - # Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键; - # 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。 + # 同一订单行更新时关闭旧事实,保证 current 投影唯一。 ( ShippingNoticeLineInventoryMatch.query .filter( diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py index 3fe1e59d..88d6a9af 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -2,11 +2,13 @@ services/shipping_notice/line_inventory_match_projection.py 用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。 -依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。 -逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用; +依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。 +逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用; ready+not_found→available=0;result_missing 不得转 0; inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮); - line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。 + line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail; + load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo, + 禁止按行重复查库。 """ from __future__ import annotations @@ -14,7 +16,11 @@ from __future__ import annotations from decimal import Decimal, InvalidOperation from typing import Any -from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch +from app.models import ( + ShippingInventoryFile, + ShippingNoticeLineInventoryMatch, + ShippingTaskInventoryRpaAttempt, +) MATCH_NOT_FOUND = 'not_found' @@ -414,24 +420,107 @@ def resolve_allowed_actions( return [*inv, *line] -def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]: - """加载 OT 当前行匹配事实,键为 line_key。""" +def inventory_rpa_is_running(task: Any) -> bool: + """ + 仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。 + + 核心逻辑:查 (task_no, status in queued|running) 是否存在;阶段推进 Job 的 + queued/running 不得冒充本结果。同一 HTTP 请求内按 task_no memo,供 Case 投影 + 与工作台 stage_context 共享,禁止逐行或重复入口各查一次。 + + Args: + task: 含 task_no 的正式 OT(或等价命名空间);无 task_no 时返回 False。 + + Returns: + True 表示存在活动库存 RPA Attempt。 + """ + task_no = str(getattr(task, 'task_no', None) or '').strip() + if not task_no: + return False + try: + from flask import g, has_app_context, has_request_context + if has_app_context() and has_request_context(): + cache = getattr(g, '_shipping_inventory_rpa_running_by_task_no', None) + if cache is None: + cache = {} + g._shipping_inventory_rpa_running_by_task_no = cache + if task_no in cache: + return bool(cache[task_no]) + else: + cache = None + except Exception: + cache = None + + try: + running = ( + ShippingTaskInventoryRpaAttempt.query + .filter( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + ) + .first() + is not None + ) + except Exception: # noqa: BLE001 + # 纯投影/无数据库测试对象不得把未知状态误判为运行中。 + running = False + if cache is not None: + cache[task_no] = running + return running + + +def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]: + """ + 加载 OT 当前行匹配事实,键为冻结订单行 ID。 + + 同一 HTTP 请求内按 task_id memo,避免 SUMMARY / ui_state / stage_context 重复查库。 + """ if task_id is None: return {} + key = int(task_id) + try: + from flask import g, has_app_context, has_request_context + if has_app_context() and has_request_context(): + cache = getattr(g, '_shipping_match_facts_by_task', None) + if cache is None: + cache = {} + g._shipping_match_facts_by_task = cache + cached = cache.get(key) + if cached is not None: + return cached + else: + cache = None + except Exception: + cache = None + rows = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task_id), is_current=True) + .filter_by(task_id=key, is_current=True) .all() ) - out: dict[str, dict[str, Any]] = {} + out: dict[int, dict[str, Any]] = {} for row in rows: - key = str(row.line_key or '').strip() - if not key: + if row.snapshot_line_id is None: continue - out[key] = serialize_match_fact(row) + out[int(row.snapshot_line_id)] = serialize_match_fact(row) + if cache is not None: + cache[key] = out return out +def aggregate_match_status_for_task(task_id: int | None) -> str | None: + """根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。""" + facts = list(load_current_match_facts_by_task(task_id).values()) + if not facts: + return None + blocked = any( + str(row.get('match_result') or '').strip().lower() != 'matched' + or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + for row in facts + ) + return 'unfulfillable' if blocked else 'fulfillable' + + def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]: """将 ORM 行序列化为投影输入。""" snapshot = ( @@ -442,7 +531,8 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'id': int(row.id), 'task_id': int(row.task_id), 'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None, - 'line_key': str(row.line_key), + 'snapshot_line_id': int(row.snapshot_line_id), + 'line_no': int(row.line_no), 'line_index': row.line_index, 'inventory_snapshot_id': ( int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None @@ -457,6 +547,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'unit': row.unit, 'matching_rule_version': row.matching_rule_version, 'inventory_source_code': row.inventory_source_code, + 'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_file_sha256': ( dict(row.detail_json or {}).get('file_sha256') diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py index ff274131..4f16a86c 100644 --- a/backend/app/services/shipping_notice/match.py +++ b/backend/app/services/shipping_notice/match.py @@ -15,7 +15,7 @@ def _norm(value: Any) -> str: return str(value or "").strip() -def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: +def _match_identity(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: """按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。""" values = tuple(_norm(row.get(field)).casefold() for field in fields) return values if values and all(values) else None @@ -27,7 +27,7 @@ def _aggregate_inventory( """按用户配置的库存匹配字段组合汇总唯一数量字段。""" totals: dict[tuple[str, ...], float] = {} for row in inventory_lines: - key = _line_key(row, match_fields) + key = _match_identity(row, match_fields) if key is None: continue try: @@ -70,7 +70,7 @@ def match_notice_lines( # [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。 total_lines = len(notice_lines) for index, line in enumerate(notice_lines, start=1): - order_key = _line_key(line, order_fields) + order_key = _match_identity(line, order_fields) try: required = float(line.get("__required_qty") or 0) except (TypeError, ValueError): diff --git a/backend/app/services/shipping_notice/notice_line_constants.py b/backend/app/services/shipping_notice/notice_line_constants.py index 721e14bf..4d81c8e1 100644 --- a/backend/app/services/shipping_notice/notice_line_constants.py +++ b/backend/app/services/shipping_notice/notice_line_constants.py @@ -9,36 +9,26 @@ services/shipping_notice/notice_line_constants.py from __future__ import annotations NOTICE_LINE_FIELDS = ( - "line_no", "part_number", "qty", "unit_price", - "amount", - "currency", + "line_amount_with_tax", "reservation_id", "required_date", "customer_part_number", - "aws_part_number", "uom", "line_remark", - "po_number", - "allocation_id", "inventory_source_hint", ) NOTICE_FIELD_LABELS = { - "line_no": "项次 / Item / Line No", "part_number": "内部料号 / Part Number", "qty": "需求数量", "unit_price": "单价", - "amount": "金额", - "currency": "币种", + "line_amount_with_tax": "含税金额 / Amount", "reservation_id": "Reservation ID(常见纯数字,如 1000140351)", "required_date": "要求交期 / 交货日期", "customer_part_number": "客户料号 / Customer Part Number", - "aws_part_number": "AWS 料号 / AWS Part Number", - "po_number": "PO Number", - "allocation_id": "Allocation ID", "inventory_source_hint": "库存来源提示 / Hub Code", "line_remark": "行备注", } diff --git a/backend/app/services/shipping_notice/notice_line_service.py b/backend/app/services/shipping_notice/notice_line_service.py index f52632cf..7dcdf147 100644 --- a/backend/app/services/shipping_notice/notice_line_service.py +++ b/backend/app/services/shipping_notice/notice_line_service.py @@ -9,6 +9,7 @@ backend/app/services/shipping_notice/notice_line_service.py from __future__ import annotations from datetime import datetime +from typing import Any from app import db from app.models import ShippingNoticeLine, ShippingOrderSnapshot @@ -19,6 +20,7 @@ def replace_notice_lines_from_snapshot( notice_id: int, snapshot: ShippingOrderSnapshot, snapshot_line_ids: set[int] | None = None, + inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None, ) -> int: """ 用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。 @@ -35,18 +37,26 @@ def replace_notice_lines_from_snapshot( now = datetime.utcnow() rows: list[ShippingNoticeLine] = [] selected_ids = {int(item) for item in (snapshot_line_ids or set())} + inventory_facts_by_snapshot_line_id = inventory_facts_by_snapshot_line_id or {} + notice_position = 0 for line in list(snapshot.lines or []): if selected_ids and int(line.id) not in selected_ids: continue + notice_position += 1 + inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {}) rows.append( ShippingNoticeLine( notice_id=int(notice_id), snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None, - position=int(line.position), - line_key=str(getattr(line, 'line_no', None) or '').strip() or None, + position=notice_position - 1, + # 发货通知项次按当前通知单重新从 1 编排。 + line_no=notice_position, part_number=getattr(line, 'part_number', None), reservation_id=getattr(line, 'reservation_id', None), required_qty=getattr(line, 'qty', None), + inventory_source_code=inventory_facts.get('inventory_source_code'), + inventory_file_id=inventory_facts.get('inventory_file_id'), + inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'), field_values_json=dict(getattr(line, 'field_values_json', None) or {}), created_at=now, ) diff --git a/backend/app/services/shipping_notice/notice_line_table.py b/backend/app/services/shipping_notice/notice_line_table.py index ae73cc24..8b98a9a2 100644 --- a/backend/app/services/shipping_notice/notice_line_table.py +++ b/backend/app/services/shipping_notice/notice_line_table.py @@ -86,14 +86,6 @@ def parse_notice_row( if idx_qty is not None: skip_indices.add(idx_qty) - idx_line_no = columns.get("line_no") - if idx_line_no is not None: - config = contract.fields_by_code.get('line_no') - line_no = _normalized_cell(row, idx_line_no, config) - skip_indices.add(idx_line_no) - if line_no is not None: - parsed["line_no"] = str(line_no) - idx_res = columns.get("reservation_id") reservation_id = "" if idx_res is not None: @@ -119,18 +111,22 @@ def parse_notice_row( if value is not None: parsed["unit_price"] = float(value) - idx_amount = columns.get("amount") + # 冻结契约的表头字段码已从旧版 `amount` 迁移为 `line_amount_with_tax`(见 + # table_contract.TABLE_FIELD_CODES / order_freeze_service.LINE_FIELD_PROJECTIONS)。 + # 表格列以 `line_amount_with_tax` 识别,但订单行输出沿用通知层的 `amount` 表示键, + # 供 normalize_notice_line / validate_notice_lines 等下游统一消费。 + idx_amount = columns.get("line_amount_with_tax") amount_cell = None if idx_amount is not None: amount_cell = cell(row, idx_amount) - config = contract.fields_by_code.get('amount') + config = contract.fields_by_code.get('line_amount_with_tax') value = _normalized_cell(row, idx_amount, config, numeric=True) if value is not None: parsed["amount"] = float(value) for field in ( 'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint', - 'customer_part_number', 'aws_part_number', 'line_remark', + 'customer_part_number', 'line_remark', ): idx = columns.get(field) if idx is None: @@ -145,7 +141,7 @@ def parse_notice_row( if currency: parsed['currency'] = currency - amount_config = contract.fields_by_code.get('amount') + amount_config = contract.fields_by_code.get('line_amount_with_tax') if amount_config is not None and "amount" not in parsed and "unit_price" in parsed: computed = round(parsed["unit_price"] * float(qty), 4) normalized = _normalized_cell([computed], 0, amount_config, numeric=True) @@ -170,7 +166,7 @@ def score_notice_header_row(cells: list[Any], contract: TableHeaderContract | No score += 30 if "reservation_id" in mapped: score += 10 - if "unit_price" in mapped or "amount" in mapped: + if "unit_price" in mapped or "line_amount_with_tax" in mapped or "amount" in mapped: score += 5 return score diff --git a/backend/app/services/shipping_notice/notice_lines.py b/backend/app/services/shipping_notice/notice_lines.py index 15eb0146..88066841 100644 --- a/backend/app/services/shipping_notice/notice_lines.py +++ b/backend/app/services/shipping_notice/notice_lines.py @@ -20,7 +20,6 @@ from app.services.shipping_notice.notice_line_values import ( map_notice_header, norm_header, normalize_currency, - normalize_line_no, normalize_required_date, parse_number, ) @@ -201,10 +200,6 @@ def normalize_notice_line( if raw_uom and field_enabled("uom"): line["uom"] = raw_uom - line_no = normalize_line_no(raw.get("line_no")) - if line_no and field_enabled("line_no"): - line["line_no"] = line_no - reservation_id = extract_reservation_id(raw.get("reservation_id")) if reservation_id and field_enabled("reservation_id"): line["reservation_id"] = reservation_id @@ -217,9 +212,10 @@ def normalize_notice_line( line["unit_price"] = unit_price amount = parse_number(raw.get("amount")) - if amount is not None and field_enabled("amount"): + # Schema 使用 canonical line_amount_with_tax;内部通知行仍保留 amount 键供下游消费。 + if amount is not None and field_enabled("line_amount_with_tax"): line["amount"] = amount - elif unit_price is not None and field_enabled("amount"): + elif unit_price is not None and field_enabled("line_amount_with_tax"): line["amount"] = round(unit_price * qty, 4) currency = normalize_currency(raw.get("currency")) diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index f2bb3f97..fbdac2cb 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -51,7 +51,7 @@ def _post_op( "200": { "description": ( "Tool response (status: ok|running|needs_human|failed). " - "May include checkpoint; business buttons are exposed only by ui_state.actions." + "May include position; business buttons are exposed only by ui_state.actions." ), "content": { "application/json": { @@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "paths": { "/tools/get_task_status": _post_op( "get_task_status", - "查询任务当前状态;响应含库存连接器独立字段与候选结构", + "查询任务当前状态;响应含库存源状态与候选结构", { "task_id": task_id, "conversation_id": _str_prop("Dify 会话 ID"), @@ -94,8 +94,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["task_id", "shipping_chat_capability_token"], description=( - "返回 inventory_source_code、inventory_connector_type、" - "inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|" + "返回 inventory_source_code、inventory_warehouse_id、" + "inventory_source_status(unresolved|ambiguous|resolved|" "candidates_frozen|invalid|conflicted)、inventory_source_method、" "inventory_source_config_version、inventory_routing_fingerprint、" "以及 step_payload.inventory_source_resolution.candidates。" diff --git a/backend/app/services/shipping_notice/order_auto_freeze_policy.py b/backend/app/services/shipping_notice/order_auto_freeze_policy.py index 910c41f8..81cc97d9 100644 --- a/backend/app/services/shipping_notice/order_auto_freeze_policy.py +++ b/backend/app/services/shipping_notice/order_auto_freeze_policy.py @@ -17,7 +17,8 @@ from typing import Any from app.models import ( ShippingDocumentProfileAutoFreezeQualification, - ShippingOrderCustomerMatch, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderRouteDecision, @@ -321,19 +322,19 @@ def _qualification_for_route( def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]: - """读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。""" + """读取本轮正式识别结果中的已确认客户;跨订单多客户时维持 fail-closed。""" rows = ( - ShippingOrderCustomerMatch.query - .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) + ShippingCustomerShadowResolution.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.id == ShippingCustomerShadowResolution.candidate_id) + .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCandidate.order_extraction_id) .filter( ShippingOrderExtraction.run_id == int(run.id), - ShippingOrderCustomerMatch.role == 'bill_to', - ShippingOrderCustomerMatch.status == 'confirmed', - ShippingOrderCustomerMatch.customer_id.isnot(None), + ShippingCustomerShadowResolution.status == 'confirmed', + ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None), ) .all() ) - return sorted({int(row.customer_id) for row in rows if row.customer_id is not None}) + return sorted({int(row.confirmed_customer_id) for row in rows if row.confirmed_customer_id is not None}) def _evaluate_customer_scope( diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index dc682699..52cdb840 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -7,7 +7,7 @@ services/shipping_notice/order_build_eligibility_service.py inventory_routing_engine、inventory_source_repository、 ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、 ShippingInventorySource、process_gate_contract(原因唯一归属)。 -逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断; +逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费); 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选, 并写入稳定 unavailable_reasons(码表见 error_explainability_contract); @@ -473,7 +473,7 @@ def assess_order_build_eligibility( fields: Schema field_id → 配置。 header_by_code: Header field_code → 值。 lines: 行 field_code → 值列表(与 line_metas 对齐)。 - line_metas: Draft 行原始对象(含 line_key / inventory_routing)。 + line_metas: Draft 行原始对象(含 draft_line_id / inventory_routing)。 customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。 candidate / unit / run: 可选门禁上下文(自动建单检查)。 @@ -515,7 +515,7 @@ def assess_order_build_eligibility( line_meta=meta, ) projection = { - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'effective_reservation_id': effective, 'inventory_source_hint': raw_line.get('inventory_source_hint'), @@ -526,7 +526,7 @@ def assess_order_build_eligibility( if not effective: issues.append({ 'code': 'effective_reservation_missing', - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', 'owning_gate_code': 'reservation_validation', @@ -534,7 +534,7 @@ def assess_order_build_eligibility( if not routing.get('can_build'): issues.append({ 'code': str(routing.get('block_reason') or 'inventory_source_unresolved'), - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', 'owning_gate_code': 'inventory_source_routing', @@ -573,11 +573,16 @@ def assess_order_build_eligibility( 'owning_gate_code': 'reservation_validation', }) + # 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。 + build_blocking_issues = [ + item for item in issues + if str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + ] can_build = ( bool(customer_resolved) and bool(assessment.get('can_create_task')) - and not issues - and all(item.get('can_build') and item.get('effective_reservation_id') for item in line_projections) + and not build_blocking_issues + and all(item.get('effective_reservation_id') for item in line_projections) and bool(line_projections) ) fields_complete = ( diff --git a/backend/app/services/shipping_notice/order_candidate_builder.py b/backend/app/services/shipping_notice/order_candidate_builder.py index bb282d09..2f314362 100644 --- a/backend/app/services/shipping_notice/order_candidate_builder.py +++ b/backend/app/services/shipping_notice/order_candidate_builder.py @@ -12,8 +12,17 @@ import re from decimal import Decimal, InvalidOperation from typing import Any -from app.services.shipping_notice.notice_line_table import parse_notice_table_text -from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract +from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text +from app.services.shipping_notice.notice_line_table import ( + find_notice_header_row_index, + parse_notice_row, + parse_notice_table_text, +) +from app.services.shipping_notice.notice_line_values import resolve_notice_columns +from app.services.shipping_notice.order_schema.table_contract import ( + compile_table_header_contract, + normalize_table_header, +) from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id @@ -33,11 +42,49 @@ def _comparable_value(field: str, value: Any) -> str: return str(value or "").strip().upper() +def _scan_email_po_aws_header( + header: list[str], schema_definition: dict[str, Any], +) -> tuple[int | None, int | None]: + """ + 定位邮件正文表头中 PO 与 AWS SKU 的列索引。 + + 背景:`po_number` 为 header 作用域、`aws_part_number` 不在 TABLE_FIELD_CODES 内,两者都不会被 + compile_table_header_contract 编入契约,故 `parse_notice_row` 永远不会产出这两个字段。正文订单索引行 + 需要额外保留它们,才能在按 PO 融合附件时回填正文分配字段(如 inventory_source_hint / customer_part_number + 等)。为不移除共享表头契约(守约严格性),这里只做独立的表头列扫描。 + + Returns: + 返回 (po_idx, aws_idx);对应列不在表头时结果为 None。 + """ + # 仅从本次预处理选择的 Schema 定义派生候选表头(field_code + display_name + aliases),避免硬编码漂移。 + aliases: dict[str, set[str]] = {"po_number": set(), "aws_part_number": set()} + for raw in schema_definition.get("fields") or []: + code = str(raw.get("field_code") or "").strip() + if code not in aliases: + continue + for candidate in (code, raw.get("display_name"), *(raw.get("aliases") or [])): + normalized = normalize_table_header(candidate) + if normalized: + aliases[code].add(normalized) + + po_idx = None + aws_idx = None + for i, cell_text in enumerate(header): + normalized = normalize_table_header(cell_text) + if normalized and normalized in aliases["po_number"]: + po_idx = i + if normalized and normalized in aliases["aws_part_number"]: + aws_idx = i + return po_idx, aws_idx + + def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]: """ 从邮件正文表格提取订单索引行。 - 核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。 + 核心逻辑:复用统一订单表格解析器抽标准明细字段,并额外按正文原始表头回填 `po_number` 与 + `aws_part_number`(两者因作用域/字段表不在共享契约中,parse_notice_row 不产出),供按 PO 融合 + 附件时补正文分配字段。最后只保留具备 PO 或 Reservation 的有效订单行。 Args: body_text: 邮件正文纯文本。 schema_definition: 本次预处理明确选择的订单 Schema 定义。 @@ -45,7 +92,44 @@ def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any] 正文订单索引列表。 """ contract = compile_table_header_contract(schema_definition) - rows = parse_notice_table_text(str(body_text or ""), contract=contract) + text = str(body_text or "") + + # 先用共享解析器判空;无有效行时直接退化为共享结果,避免空文本重复自建解析。 + if not parse_notice_table_text(text, contract=contract): + return [] + + raw_rows = _rows_from_table_text(text) + if not raw_rows: + return [] + header_idx = find_notice_header_row_index(raw_rows, contract=contract) + header = [str(c or "").strip() for c in raw_rows[header_idx]] + po_idx, aws_idx = _scan_email_po_aws_header(header, schema_definition) + + columns = resolve_notice_columns(header, contract) + if columns.get("_ambiguous_fields"): + return [] + idx_res = columns.get("reservation_id") + if idx_res is not None and idx_res < len(header): + columns["_reservation_id_header"] = str(header[idx_res] or "").strip() + + rows: list[dict[str, Any]] = [] + for raw_row in raw_rows[header_idx + 1:]: + if not raw_row: + continue + parsed = parse_notice_row(list(raw_row), columns, contract=contract) + if parsed is None: + continue + # 回填共享解析器不产出的 PO / AWS SKU,保证正文行与原始表列强对齐。 + if po_idx is not None and po_idx < len(raw_row): + po_number = str(raw_row[po_idx] or "").strip() + if po_number: + parsed["po_number"] = po_number + if aws_idx is not None and aws_idx < len(raw_row): + aws_part_number = str(raw_row[aws_idx] or "").strip() + if aws_part_number: + parsed["aws_part_number"] = aws_part_number + rows.append(parsed) + return [ row for row in rows if normalize_po_number(row.get("po_number")) diff --git a/backend/app/services/shipping_notice/order_customer_matching.py b/backend/app/services/shipping_notice/order_customer_matching.py deleted file mode 100644 index 2e4f32fc..00000000 --- a/backend/app/services/shipping_notice/order_customer_matching.py +++ /dev/null @@ -1,289 +0,0 @@ -""" -backend/app/services/shipping_notice/order_customer_matching.py - -用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。 -依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。 -逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。 -""" - -from __future__ import annotations - -import hashlib -import json -from datetime import datetime -from typing import Any - -from app import db -from app.core.errors import NotFoundError, ValidationError -from app.models import ( - ShippingCustomer, - ShippingCustomerExternalRef, - ShippingCustomerIdentifier, - ShippingCustomerSite, - ShippingCustomerSiteIdentifier, - ShippingOrderCustomerMatch, - ShippingOrderExtraction, -) -from app.services.shipping_notice.customer_normalization import normalize_customer_name - -ROLE_FIELDS = { - 'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'}, - 'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'}, -} -IDENTITY_RULE_VERSION = 'order-customer-fingerprint.v1' - - -def _normalized_code(value: Any) -> str: - """规范外部客户/站点编码,保留业务符号并统一大小写。""" - return str(value or '').strip().upper() - - -def _identity_fingerprint(*, role: str, raw_name: str, external_code: str, source_system: str) -> tuple[str, dict[str, str]]: - """用订单原文标准化值和固定规则版本生成稳定身份指纹,不写回或替换原始字段。""" - components = { - 'role': role, - 'normalized_name': normalize_customer_name(raw_name) if raw_name else '', - 'external_code': _normalized_code(external_code), - 'source_system': _normalized_code(source_system), - } - encoded = json.dumps( - {'rule_version': IDENTITY_RULE_VERSION, 'components': components}, - ensure_ascii=True, sort_keys=True, separators=(',', ':'), - ).encode('utf-8') - return hashlib.sha256(encoded).hexdigest(), components - - -def _customer_candidates(raw_name: str) -> list[dict[str, Any]]: - """按标准名称和 approved 名称别名返回稳定去重的启用客户候选。""" - normalized = normalize_customer_name(raw_name) - if not normalized: - return [] - customers = db.session.query(ShippingCustomer).filter_by(status='active').all() - matched: dict[int, dict[str, Any]] = {} - for customer in customers: - if normalize_customer_name(customer.standard_name) == normalized: - matched[customer.id] = { - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'matched_by': ['standard_name'], - } - aliases = db.session.query(ShippingCustomerIdentifier).filter_by( - identifier_type='name_alias', normalized_value=normalized, status='approved', - ).all() - active_by_id = {customer.id: customer for customer in customers} - for alias in aliases: - customer = active_by_id.get(int(alias.customer_id)) - if customer is None: - continue - candidate = matched.setdefault(customer.id, { - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'matched_by': [], - }) - if 'name_alias' not in candidate['matched_by']: - candidate['matched_by'].append('name_alias') - return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id'])) - - -def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: - """优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。""" - code = _normalized_code(external_code) - source = _normalized_code(source_system) - if code and source: - refs = db.session.query(ShippingCustomerExternalRef).filter_by( - source_system=source, legacy_customer_key=code, - ).all() - candidates = [] - for ref in refs: - customer = db.session.get(ShippingCustomer, int(ref.customer_id)) - if customer and customer.status == 'active': - candidates.append({ - 'customer_id': customer.id, 'standard_name': customer.standard_name, - 'short_code': customer.short_code, 'site_id': None, 'site_name': None, - 'site_code': None, 'matched_by': ['external_customer_code'], - }) - if candidates: - return candidates - return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)] - - -def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: - """优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。""" - code = _normalized_code(external_code) - source = _normalized_code(source_system) - sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all() - matched: dict[int, dict[str, Any]] = {} - matched_site_ids: dict[int, str] = {} - if code: - identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( - identifier_type='external_code', source_system=source, normalized_value=code, status='approved', - ).all() - for identifier in identifiers: - matched_site_ids[int(identifier.site_id)] = 'external_site_code' - for site in sites: - if _normalized_code(site.site_code) == code: - matched_site_ids[site.id] = 'site_code' - if not matched_site_ids: - normalized = normalize_customer_name(raw_name) if raw_name else '' - for site in sites: - if normalized and normalize_customer_name(site.site_name) == normalized: - matched_site_ids[site.id] = 'site_name' - if normalized: - identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( - identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved', - ).all() - for identifier in identifiers: - matched_site_ids[int(identifier.site_id)] = 'site_name_alias' - by_id = {site.id: site for site in sites} - for site_id, matched_by in matched_site_ids.items(): - site = by_id.get(site_id) - customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None - if site is None or customer is None or customer.status != 'active': - continue - matched[site.id] = { - 'customer_id': customer.id, 'standard_name': customer.standard_name, - 'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name, - 'site_code': site.site_code, 'matched_by': [matched_by], - } - return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id'])) - - -def refresh_order_customer_matches( - extraction: ShippingOrderExtraction, - header: dict[str, Any], -) -> list[dict[str, Any]]: - """ - 根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。 - - Args: - extraction: 已持久化的动态订单解析记录。 - header: 已通过证据裁决的订单头字段投影。 - Returns: - 两种角色的匹配摘要;客户简称只来自客户主数据快照。 - """ - results: list[dict[str, Any]] = [] - for role, fields in ROLE_FIELDS.items(): - raw_name = str(header.get(fields['name']) or '').strip() - external_code = _normalized_code(header.get(fields['code'])) - source_system = _normalized_code(header.get(fields['source'])) - fingerprint, components = _identity_fingerprint( - role=role, raw_name=raw_name, external_code=external_code, source_system=source_system, - ) - candidates = ( - _bill_to_candidates(raw_name, external_code, source_system) - if role == 'bill_to' - else _ship_to_candidates(raw_name, external_code, source_system) - ) - row = db.session.query(ShippingOrderCustomerMatch).filter_by( - extraction_id=extraction.id, role=role, - ).one_or_none() - if row is None: - row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role) - db.session.add(row) - row.raw_name = raw_name or None - row.normalized_name = normalize_customer_name(raw_name) if raw_name else None - row.source_system = source_system or None - row.external_code = external_code or None - row.identity_fingerprint = fingerprint - row.identity_rule_version = IDENTITY_RULE_VERSION - row.identity_components_json = components - row.candidates_json = candidates - if len(candidates) == 1: - candidate = candidates[0] - row.status = 'unique_candidate' - row.customer_id = int(candidate['customer_id']) - row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None - row.customer_name_snapshot = str(candidate['standard_name']) - row.customer_short_code_snapshot = str(candidate['short_code']) - row.resolution_method = str(candidate['matched_by'][0]) - else: - row.status = 'ambiguous' if candidates else 'unmatched' - row.customer_id = None - row.site_id = None - row.customer_name_snapshot = None - row.customer_short_code_snapshot = None - row.resolution_method = None - row.confirmed_by_id = None - row.confirmed_at = None - row.confirmation_reason = None - row.updated_at = datetime.utcnow() - db.session.flush() - results.append(serialize_order_customer_match(row)) - return results - - -def confirm_order_customer_match( - extraction_id: int, - *, - role: str, - customer_id: int, - site_id: int | None = None, - actor_id: int | None, - reason: str, - commit: bool = True, -) -> dict[str, Any]: - """ - 人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。 - - Args: - commit: True 时立即 db.session.commit();False 时仅 flush,由调用方统一控制事务 - (用于同事务内追加 reconcile / Job 入队等后续步骤)。 - """ - if role not in ROLE_FIELDS: - raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID') - row = db.session.query(ShippingOrderCustomerMatch).filter_by( - extraction_id=extraction_id, role=role, - ).one_or_none() - if row is None: - raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND') - reason_value = str(reason or '').strip() - if not reason_value: - raise ValidationError('Customer confirmation reason is required', code='SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED') - customer = db.session.get(ShippingCustomer, int(customer_id)) - if customer is None: - raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') - if customer.status != 'active': - raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE') - selected_site = None - if role == 'ship_to': - selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None - if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active': - raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID') - row.status = 'confirmed' - row.customer_id = customer.id - row.site_id = selected_site.id if selected_site else None - row.customer_name_snapshot = customer.standard_name - row.customer_short_code_snapshot = customer.short_code - row.resolution_method = 'manual' - row.confirmation_reason = reason_value - row.confirmed_by_id = actor_id - row.confirmed_at = datetime.utcnow() - if commit: - db.session.commit() - else: - db.session.flush() - return serialize_order_customer_match(row) - - -def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]: - """输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。""" - return { - 'id': row.id, - 'extraction_id': row.extraction_id, - 'role': row.role, - 'raw_name': row.raw_name, - 'status': row.status, - 'customer_id': row.customer_id, - 'site_id': row.site_id, - 'source_system': row.source_system, - 'external_code': row.external_code, - 'identity_fingerprint': row.identity_fingerprint, - 'identity_rule_version': row.identity_rule_version, - 'standard_name': row.customer_name_snapshot, - 'short_code': row.customer_short_code_snapshot, - 'candidates': list(row.candidates_json or []), - 'resolution_method': row.resolution_method, - 'confirmation_reason': row.confirmation_reason, - } diff --git a/backend/app/services/shipping_notice/order_document_profile_creation_service.py b/backend/app/services/shipping_notice/order_document_profile_creation_service.py index 9de2fa43..8257e0fe 100644 --- a/backend/app/services/shipping_notice/order_document_profile_creation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_creation_service.py @@ -178,6 +178,8 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, sample_role=sample_role, created_by_id=actor_id, )) db.session.flush() + if document.asset_id: + profile_service._retain_profile_sample_assets(profile_id, asset_ids={int(document.asset_id)}) profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id)) revision_no = int(saved['draft_revision']['revision_no']) profile_service._audit( diff --git a/backend/app/services/shipping_notice/order_document_profile_preview_service.py b/backend/app/services/shipping_notice/order_document_profile_preview_service.py index 5cbdbbc1..67000c67 100644 --- a/backend/app/services/shipping_notice/order_document_profile_preview_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_preview_service.py @@ -153,6 +153,7 @@ def _frozen_sample_context( 'Frozen sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', ) + profile_service._repair_bound_sample_asset(document) asset = db.session.get(FileAsset, int(document.asset_id)) if asset is None: raise ValidationError( @@ -239,6 +240,39 @@ def _render_pdf_pages(asset: FileAsset) -> list[Any]: ) from exc +def _frozen_physical_page_count( + *, layout_version: ShippingDocumentLayoutVersion, document: ShippingOrderDocument, +) -> int | None: + """ + 从冻结 Layout 的完整页证据读取原 PDF 物理页数,供历史错误快照的只读兼容校验。 + + 核心逻辑:持久化 Layout 可把坐标证据外置到受控 FileAsset,本函数只加载该冻结引用; + 仅页面元数据可证明物理页数,绝不以业务表格页数作为回退。 + + Args: + layout_version: 已通过冻结 checksum 校验的 Layout 版本。 + document: 与 Layout 绑定且已通过内容 hash 校验的样本文档。 + + Returns: + 完整页证据可用时返回物理页数;证据缺失或结构无效时返回 None。 + """ + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence + + payload = _hydrate_coordinate_evidence( + payload=dict(layout_version.payload_json or {}), document=document, + ) + pages = payload.get('pages') + if isinstance(pages, list): + count = len([item for item in pages if isinstance(item, dict)]) + if count: + return count + evidence = payload.get('coordinate_evidence') + evidence_pages = evidence.get('pages') if isinstance(evidence, dict) else None + if isinstance(evidence_pages, dict) and evidence_pages: + return len(evidence_pages) + return None + + def authorize_frozen_sample_preview_pages( profile_id: int, *, @@ -258,15 +292,18 @@ def authorize_frozen_sample_preview_pages( profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') - _, sample, document, _layout_version, asset = _frozen_sample_context( + _, sample, document, layout_version, asset = _frozen_sample_context( profile_id=int(profile_id), sample_binding_id=int(sample_binding_id), ) pages = _render_pdf_pages(asset) if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot): - raise ValidationError( - 'Frozen page count no longer matches the published evidence', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', - ) + # [STEP 1] 兼容修复上线前把外置证据退化为表格页数的历史冻结记录; + # 只有同一冻结 Layout 的完整页证据与当前原 PDF 一致时才允许预览。 + if _frozen_physical_page_count(layout_version=layout_version, document=document) != len(pages): + raise ValidationError( + 'Frozen page count no longer matches the published evidence', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', + ) store = _preview_grant_store() preview_pages: list[dict[str, Any]] = [] for page in pages: 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 88ccac5f..d5bbc3d8 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -1,10 +1,10 @@ """ backend/app/services/shipping_notice/order_document_profile_service.py -??????????? Profile ?????????? Run ????? -???ShippingOrderDocumentProfile?????????? Schema ???document_layout.order_profile ???? -??????????? field_code ???? field_id?????????? Schema ?????????? - ???????????????????????? CASCADE ???? 500? + Profile Run +ShippingOrderDocumentProfile Schema document_layout.order_profile + field_code field_id Schema + CASCADE 500? """ from __future__ import annotations @@ -85,7 +85,7 @@ PDF_PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-pdf-preview:' def _definition_hash(definition: dict[str, Any]) -> str: - """?? v2 ??????????????????????? 7 ?????""" + """ v2 7 """ encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() return hashlib.sha256(encoded).hexdigest() @@ -102,7 +102,7 @@ def _profile_template_mode(profile: ShippingOrderDocumentProfile) -> str: def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool: - """???????????????????????????????????""" + """""" required = ( sample.layout_version_id, sample.source_content_hash, @@ -116,7 +116,7 @@ def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]: - """????????????????????????""" + """""" return { 'id': sample.id, 'document_id': sample.document_id, @@ -139,7 +139,7 @@ def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any def _profile_frozen_evidence_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: - """???????????????????????????????""" + """""" samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() total_count = len(samples) ready_count = sum(1 for item in samples if _sample_frozen_evidence_ready(item)) @@ -200,16 +200,16 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]: def _normalize_profile_customer_scope(customer_ids: Any) -> list[int] | None: """ - ????????????????????????????????? + Args: - customer_ids: ????????????????? + customer_ids: Returns: - ???????? ID ????????? None? + ID None? Raises: - ValidationError: ?? ID ??????? + ValidationError: ID """ if customer_ids is None: return None @@ -248,7 +248,7 @@ def _audit( revision_no: int | None = None, detail: dict[str, Any] | None = None, ) -> None: - """?? Profile ?????detail ???????????? checksum ???????""" + """ Profile detail checksum """ db.session.add(ShippingOrderDocumentProfileAudit( profile_id=profile_id, document_id=document_id, event_type=event_type, actor_id=actor_id, request_id=str(request_id or '').strip() or None, @@ -259,14 +259,14 @@ def _audit( def _refresh_training_sample_count(profile: ShippingOrderDocumentProfile) -> None: - """?? Profile ????????????????????????""" + """ Profile """ profile.training_sample_count = ShippingOrderDocumentProfileSample.query.filter_by( profile_id=profile.id, sample_role='training', ).count() def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: - """??????????????????????????????????""" + """""" adapter_summary = get_value_adapter(definition).definition_audit_summary(definition) if adapter_summary is not None: return adapter_summary @@ -300,7 +300,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDocument: - """?????? Profile ???????????? ID ???????""" + """ Profile ID """ sample = ShippingOrderDocumentProfileSample.query.filter_by( profile_id=int(profile_id), document_id=int(document_id), ).first() @@ -309,16 +309,65 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDo document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + _repair_bound_sample_asset(document) return document +def _repair_bound_sample_asset(document: ShippingOrderDocument) -> None: + """补偿历史样本资产引用,避免已绑定的标注样本按临时 TTL 过期。""" + if not document.asset_id: + return + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is None: + return + if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0: + from app.services.file_assets.service import mark_asset_referenced + + mark_asset_referenced(asset) + + +def _retain_profile_sample_assets(profile_id: int, *, asset_ids: set[int] | None = None) -> int: + """为新增 Profile 样本引用的每个唯一文件资产建立一份引用。""" + from app.services.file_assets.service import mark_asset_referenced + + ids = set(asset_ids or ()) + for asset_id in sorted(ids): + asset = db.session.get(FileAsset, asset_id) + if asset is not None: + mark_asset_referenced(asset) + return len(ids) + + +def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id: int) -> None: + """删除样本绑定后,仅当该 Profile 不再引用文件时释放资产引用。""" + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None or not document.asset_id: + return + still_bound = ( + db.session.query(ShippingOrderDocumentProfileSample) + .join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderDocumentProfileSample.document_id) + .filter( + ShippingOrderDocumentProfileSample.profile_id == int(profile_id), + ShippingOrderDocument.asset_id == int(document.asset_id), + ) + .first() + ) + if still_bound is not None: + return + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is not None and int(asset.reference_count or 0) > 0: + from app.services.file_assets.service import release_asset_reference + + release_asset_reference(asset) + + def _preview_grant_store() -> Any: - """?????????????? Redis????????????????""" + """ Redis""" return preview_grant_store() def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]: - """???? Schema ????????????????? field_code?""" + """ Schema field_code?""" definition = version.definition_json if isinstance(version.definition_json, dict) else {} result: dict[str, dict[str, Any]] = {} for raw in definition.get('fields') or []: @@ -336,7 +385,7 @@ def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, A def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[str, str], dict[str, Any]]: - """? ``(scope, field_code)`` ?? Profile ???????????????????""" + """? ``(scope, field_code)`` Profile """ definition = version.definition_json if isinstance(version.definition_json, dict) else {} result: dict[str, dict[str, Any]] = {} for index, raw in enumerate(definition.get('fields') or []): @@ -376,7 +425,7 @@ def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[st def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion: - """????? published/retired Schema??????? Profile ?????""" + """ published/retired Schema Profile """ try: version_id = int(raw_id) except (TypeError, ValueError) as exc: @@ -400,13 +449,13 @@ def _normalize_definition( preferred_template_mode: str | None = None, ) -> dict[str, Any]: """ - ?? v2 ????????? ID???? HTML ??/?????? + v2 ID HTML / Args: - raw: ???????????????????????????? - schema_version: ????????????????? + raw: + schema_version: Returns: - ????? v2 ????????????? Schema ???????? + v2 Schema """ if not isinstance(raw, dict): raise ValidationError( @@ -751,7 +800,7 @@ def _normalize_visual_definition_for_preview( def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordinateProfile: - """???????????????? v1 ???? Profile ??????? v2?""" + """ v1 Profile v2?""" definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} return OrderCoordinateProfile( profile_code=profile.profile_code, @@ -766,7 +815,7 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: - """????????? Profile ?? DTO?""" + """ Profile DTO?""" schema = profile.schema_version source_profile = profile.source_profile compatibility = None @@ -825,7 +874,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: def list_profiles() -> list[dict[str, Any]]: - """?????????????? Profile?""" + """ Profile?""" return [payload(item) for item in ShippingOrderDocumentProfile.query.order_by( ShippingOrderDocumentProfile.profile_code.asc(), ShippingOrderDocumentProfile.version.desc(), @@ -833,7 +882,7 @@ def list_profiles() -> list[dict[str, Any]]: def list_profile_samples(profile_id: int) -> list[dict[str, Any]]: - """??????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -843,7 +892,7 @@ def list_profile_samples(profile_id: int) -> list[dict[str, Any]]: def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample) -> str: - """???????????????????????????????????""" + """""" explicit = str(sample.table_id or '').strip() if explicit: return explicit @@ -871,7 +920,7 @@ def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sampl def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]: - """???????????????????????? token?????????""" + """ token""" if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -916,9 +965,13 @@ def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | Non def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> bytes: - """?????????????? PNG????? PDF?HTML?????????""" + """按页返回受控 PNG;令牌在 TTL 内可重复使用,以支持标注画布翻页回访。 + + 核心逻辑:校验 Redis 中的短时 grant(不 getdel);token 仍绑定 profile/document/actor/page。 + 标注编辑需要在多页间来回切换,一次性消费会导致每次翻页都「画布不可用」。 + """ store = _preview_grant_store() - raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}') + raw_grant = store.get(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}') try: grant = json.loads(raw_grant) if raw_grant else None except (TypeError, json.JSONDecodeError): @@ -1007,7 +1060,7 @@ def read_pdf_preview(*, token: str, actor_id: int | None) -> bytes: def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, actor_id: int | None) -> dict[str, Any]: - """???????????????? bbox?token ID?HTML ????????""" + """ bbox?token ID?HTML """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1036,15 +1089,15 @@ def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, act def read_preview_page_region_text( profile_id: int, *, data: dict[str, Any], page_no: int, actor_id: int | None, ) -> dict[str, Any]: - """????????????????????????-?????? + """- Args: - profile_id: ?????????????????? - data: ??? document_id ????? region??????????????? - page_no: ????????? - actor_id: ?????????????????? + profile_id: + data: document_id region + page_no: + actor_id: Returns: - ????????????????????????????????? + """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') @@ -1133,7 +1186,7 @@ def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str: def preview_profile_region( profile_id: int, *, data: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: - """?????????? v2 ?????????????????????""" + """ v2 """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1239,7 +1292,7 @@ def preview_profile_region( ) if not isinstance(region_characters, list): continue - # ??????????????????????????? Schema ??? + # Schema for line_layout in sorted(table_region.line_layouts, key=lambda item: item.row_offset): for field_region in line_layout.field_regions: ordered_codes = [field_region.field_code] + [ @@ -1262,16 +1315,16 @@ def preview_profile_region( termination_rules=[item.model_dump() for item in table_region.termination_rules], exclusion_regions=reconstruction_exclusions, dynamic_exclusion_regions=reconstruction_exclusions, - # ????????????????????????????????? + # include_deleted=not strict, line_start_field_code=table_region.line_start_field_code, schema_field_metadata=schema_field_metadata, ) rows.extend(reconstructed_rows) - # ?????????????????????????????? + # if strict: rows = [row for row in rows if not getattr(row, 'issues', None)] - # ?????????????? target_fields ??????????????? + # target_fields for row in rows: for field_code in row.fields: if field_code not in seen_field_codes: @@ -1279,12 +1332,12 @@ def preview_profile_region( involved_field_codes.append(field_code) schema_field_codes = list(_schema_fields(profile.schema_version)) field_codes = [code for code in schema_field_codes if code in seen_field_codes] - # ??????????? Schema ?????????????? Schema ????? + # Schema Schema field_codes.extend(code for code in involved_field_codes if code not in schema_field_codes) result = { 'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0), 'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows], - # ???????????????????????? rows ????? + # rows 'field_codes': field_codes, 'row_roles': (['header'] if field_codes else []) + [row.role for row in rows], 'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows], @@ -1301,10 +1354,10 @@ def suggest_profile_header( profile_id: int, *, data: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: """ - ??????????????????????????????? Schema ????? + Schema - ????????????????? Profile?????????????????? - ?? Profile ?? Schema ?????? PDF/OCR ???????? + Profile + Profile Schema PDF/OCR """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') @@ -1373,7 +1426,7 @@ def suggest_profile_header( def generate_profile_ocr_evidence( profile_id: int, *, document_id: Any, table_id: Any, actor_id: int | None, ) -> dict[str, Any]: - """??????? PDF ??? OCR ?????????????????????""" + """ PDF OCR """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1393,9 +1446,9 @@ def generate_profile_ocr_evidence( def _matching_signature_status(profile: ShippingOrderDocumentProfile) -> str: """ - ?????????missing / valid / stale? + missing / valid / stale? - ? run_id ? checksum ?? missing???????? valid ? missing? + ? run_id ? checksum missing valid ? missing? """ if not profile.matching_signature_run_id or not profile.matching_signature_checksum: return 'missing' @@ -1410,16 +1463,16 @@ def clear_matching_signature_refs( reason: str = 'definition_or_sample_changed', ) -> bool: """ - ?? Profile ?????????? ValidationRun ??? + Profile ValidationRun Args: - profile: ?? Profile ??? - actor_id: ?????? - operation_id: ????? ID? - reason: ?????? + profile: Profile + actor_id: + operation_id: ID? + reason: Returns: - ?????????? + """ if not profile.matching_signature_run_id and not profile.matching_signature_checksum: return False @@ -1444,7 +1497,7 @@ def clear_matching_signature_refs( def add_profile_sample( profile_id: int, *, document_id: Any, table_id: Any, sample_role: Any, actor_id: int | None, ) -> list[dict[str, Any]]: - """????????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -1461,6 +1514,11 @@ def add_profile_sample( if document is None: raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') _document_layout(document) + existing_asset_ids = { + int(existing_document.asset_id) + for existing in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() + if (existing_document := db.session.get(ShippingOrderDocument, int(existing.document_id))) is not None and existing_document.asset_id + } sample = ShippingOrderDocumentProfileSample( profile_id=profile.id, document_id=document.id, table_id=str(table_id).strip() or None, sample_role=role, created_by_id=actor_id, @@ -1472,6 +1530,8 @@ def add_profile_sample( db.session.rollback() raise ConflictError('Profile sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_CONFLICT') from exc _refresh_training_sample_count(profile) + if document.asset_id and int(document.asset_id) not in existing_asset_ids: + _retain_profile_sample_assets(profile.id, asset_ids={int(document.asset_id)}) clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_added') _audit(profile_id=profile.id, document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ 'sample_role': role, 'has_table_binding': sample.table_id is not None, @@ -1481,7 +1541,7 @@ def add_profile_sample( def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | None) -> list[dict[str, Any]]: - """?????????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -1494,6 +1554,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No sample_role = sample.sample_role db.session.delete(sample) db.session.flush() + _release_profile_sample_asset_if_unreferenced(profile.id, document_id) _refresh_training_sample_count(profile) clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_removed') _audit(profile_id=profile.id, document_id=document_id, event_type='profile_sample_removed', actor_id=actor_id, detail={ @@ -1504,7 +1565,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]: - """?????? Profile ? ready MinerU ??????????/??????""" + """ Profile ? ready MinerU /""" from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot layout = current_layout_snapshot(document) or {} @@ -1542,7 +1603,7 @@ def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]: def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion: - """????????? ready Layout ???????????????????????""" + """ ready Layout """ version = document.current_layout_version if ( version is None @@ -1668,7 +1729,9 @@ def refresh_profile_sample_readiness( # not merely a repeated read of the same frozen sample. sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at sample.source_filename_snapshot = str(document.filename or '').strip() or None - sample.page_count_snapshot = _layout_page_count(version.payload_json or {}) + # [STEP 1] 页数必须来自已加载的完整坐标证据;持久化 payload 可能仅保留外置证据引用, + # 不能退化为“有业务表格的页数”。 + sample.page_count_snapshot = _layout_page_count(layout) sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id) if changed: _audit( @@ -1717,7 +1780,7 @@ def require_profile_sample_automark_ready( def _layout_page_count(payload: dict[str, Any]) -> int | None: - """????????????? payload ?? pages?????????????""" + """ payload pages""" pages = payload.get('pages') if isinstance(pages, list) and pages: return len([item for item in pages if isinstance(item, dict)]) @@ -1733,7 +1796,7 @@ def _layout_page_count(payload: dict[str, Any]) -> int | None: def _layout_table_identity_snapshot(payload: dict[str, Any], table_id: str | None) -> dict[str, Any] | None: - """???????????????????????????????""" + """""" safe_table_id = str(table_id or '').strip() if not safe_table_id: return None @@ -1760,7 +1823,7 @@ def _profile_sample_coordinate_pages( profile: ShippingOrderDocumentProfile, *, sample: ShippingOrderDocumentProfileSample, layout_payload: dict[str, Any], ) -> set[int]: - """????? definition ????????????""" + """ definition """ definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} pages: set[int] = set() for anchor in (definition.get('document_match') or {}).get('required_anchors') or []: @@ -1776,7 +1839,7 @@ def _profile_sample_coordinate_pages( def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: set[int]) -> bool: - """?? layout ??????????????? table glyph??""" + """ layout table glyph""" evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} @@ -1791,7 +1854,7 @@ def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: s def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen_at: datetime) -> int: - """????????????? Layout/Schema/Parser ??????????????""" + """ Layout/Schema/Parser """ from app.services.shipping_notice.document_layout.lifecycle import ( canonical_layout_payload, ensure_inline_xfa_structure_analysis_identity, @@ -1860,7 +1923,8 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr sample.parser_version = str(layout_version.parser_version or '').strip() or None sample.evidence_frozen_at = frozen_at sample.source_filename_snapshot = str(document.filename or '').strip() or None - sample.page_count_snapshot = _layout_page_count(layout_version.payload_json or {}) + # [STEP 1] 发布冻结使用已加载的外置坐标证据,保证页数与原 PDF 物理页一致。 + sample.page_count_snapshot = _layout_page_count(hydrated_layout) sample.table_identity_snapshot = _layout_table_identity_snapshot( layout_version.payload_json or {}, sample.table_id, ) @@ -1895,9 +1959,9 @@ def _freeze_value_adapter_evidence( def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int: """ - ???????????????? TTL ????? + TTL - ? PDF ??? annotation/training ???? mark_asset_referenced? + ? PDF annotation/training mark_asset_referenced? """ from app.services.file_assets.service import mark_asset_referenced @@ -1914,13 +1978,14 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int: 'Profile sample file asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - mark_asset_referenced(asset) + if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0: + mark_asset_referenced(asset) retained_asset_ids.add(asset_id) return len(retained_asset_ids) def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]: - """????????????????????????????????????""" + """""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} characters = tables.get(table_id) if isinstance(tables.get(table_id), list) else [] @@ -1928,7 +1993,7 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]: - """??????????????????????????????????""" + """""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no)) source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no)) @@ -2029,7 +2094,7 @@ def _read_page_ocr_coordinate_evidence( def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]: - """??????????????????????????????""" + """""" rows: list[list[dict[str, Any]]] = [] for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))): bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None @@ -2070,14 +2135,14 @@ def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, def _anchor_text_key(value: str) -> str: - """???????????????????????????""" + """""" return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold() def _inline_anchor_and_value_regions( *, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float, ) -> tuple[dict[str, float], dict[str, float], str]: - """??? bbox ?????????????????????????""" + """ bbox """ label_key = _anchor_text_key(label) consumed: list[dict[str, Any]] = [] consumed_start = 0 @@ -2157,7 +2222,7 @@ def _inline_anchor_and_value_regions( def _inline_value_text(*, text: str, label: str) -> str: - """????????????????????????????? PDF?""" + """ PDF?""" start = text.casefold().find(label.casefold()) suffix = text[start + len(label):] if start >= 0 else '' suffix = suffix.lstrip(':? ').strip() @@ -2169,10 +2234,10 @@ def _generic_order_label_candidates( *, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float, table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str, ) -> list[dict[str, Any]]: - """????? Schema ??? ``LABEL: value`` ????????????""" + """ Schema ``LABEL: value`` """ candidates: list[dict[str, Any]] = [] for line_index, (text, bbox, glyphs) in enumerate(lines): - # ?????????????????? QUALITY/SHIPMENT ??????????? + # QUALITY/SHIPMENT if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18: continue match = re.match(r'^\s*([^:?]{2,42}?)[?:]', text) @@ -2198,14 +2263,14 @@ def _generic_order_label_candidates( def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """ - ??????? v2 ?????????????????? + v2 Args: - data: ???????Schema?????????? ``page_nos``?????????? ``page_no``? - actor_id: ????? ID???????????????????????? + data: Schema ``page_nos`` ``page_no``? + actor_id: ID Returns: - ??????????????????????????????????? needs_review? + needs_review? """ try: document_id = int(data.get('document_id')) @@ -2241,7 +2306,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} known_pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} page_nos = sorted(set(page_nos) | {int(item) for item in known_pages if str(item).isdigit() and int(item) > 0}) - # [STEP 1] ???????????????????????????????????? + # [STEP 1] selected_layouts = [ item for item in profile.order_field_layouts if any( @@ -2252,7 +2317,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> ) ] selected_profile = profile.model_copy(update={'order_field_layouts': selected_layouts}) - # [STEP 2] ?????????????? all_pages ?????????????????? + # [STEP 2] all_pages for selected_page in page_nos: layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=selected_page) fields_by_id = { @@ -2418,10 +2483,10 @@ def suggest_order_field_layouts( record_audit: bool = True, ) -> dict[str, Any]: """ - ??? Schema ? Header ??????????????????????? + Schema ? Header + + PDF/OCR Schema - ????? PDF/OCR ??????????????? Schema ?????????? - ?????????????? """ try: document_id = int(data.get('document_id')) @@ -2504,18 +2569,18 @@ def generate_ocr_coordinate_evidence( persist: bool = True, ) -> dict[str, Any]: """ - ??? PDF ?????????????????????????????? OCR? + PDF OCR? Args: - document_id: ?????? ID????????? PDF ??? - table_id: ??????? MinerU ?? ID????????? - actor_id: ???????? ID????????? + document_id: ID PDF + table_id: MinerU ID + actor_id: ID force_ocr: True 时即使表内存在部分原生字符也重读渲染外观层;仅用于 视觉行/字段证据不足的受控回退,结果仍标为 ocr_coordinate 且 needs_review。 persist: False 时仅返回内存快照,供统一 automark 的多证据融合;禁止改变 Document 当前 Layout 或令冻结样本失效。 Returns: - ??????? ID?source ? pdf ? ocr??????????? + ID?source ? pdf ? ocr """ document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): @@ -2594,13 +2659,13 @@ def generate_ocr_coordinate_evidence( def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]: """ - ??????????????? PDF ???????????????? + PDF Args: - characters: PDFium ??????????? - table_bbox: MinerU ???????????? + characters: PDFium + table_bbox: MinerU Returns: - ??????????????????????????? OCR ??? + OCR """ try: x0, y0 = float(table_bbox['x0']), float(table_bbox['y0']) @@ -2620,7 +2685,7 @@ def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str, def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]: - """? OCR ??????????????????OCR ????????????""" + """? OCR OCR """ bbox = table_bbox result: list[dict[str, Any]] = [] source_index = 0 @@ -2642,7 +2707,7 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]: - """? OCR ????????????????????????? cell ?????""" + """? OCR cell """ result: list[dict[str, Any]] = [] source_index = 0 for line in lines: @@ -2663,7 +2728,7 @@ def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]: def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict[str, Any]]: - """??????????????????????????????""" + """""" if actor_id is None: return [] safe_limit = max(1, min(int(limit), 100)) @@ -2687,7 +2752,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict if layout.get('status') != 'ready' or not tables: continue content_hash = str(document.content_hash or '').strip().lower() - # ??????????????????/??????????? + # / if content_hash and content_hash in seen_content_hashes: continue intake = db.session.get(ShippingOrderIntake, document.intake_id) @@ -2724,7 +2789,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None: - """???????????????????????????????????""" + """""" if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') intake = ShippingOrderIntake.query.filter_by( @@ -2787,7 +2852,7 @@ def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None: def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]: - """?????????? PDF/EML ?????? Intake???????????""" + """ PDF/EML Intake""" if actor_id is None: raise ValidationError( 'Profile sample requires an administrator identity', @@ -2805,7 +2870,7 @@ def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, An def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[str, Any]: - """?????????????Intake ???????????????""" + """Intake """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') intake = ShippingOrderIntake.query.filter_by( @@ -2852,7 +2917,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st status = 'parsed' error_code = None else: - # ???? PDF Document??????? EML / Layout? + # PDF Document EML / Layout? status = 'parsing' error_code = None ready_values = [bool(item.get('automark_ready')) for item in readiness] @@ -2882,7 +2947,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st def get_sample_tables(document_id: int) -> dict[str, Any]: - """?????????????????? cell ?????? bbox?????? HTML?""" + """ cell bbox HTML?""" document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError( @@ -3003,13 +3068,13 @@ def suggest_coordinate_reconstruction( data: dict[str, Any], *, actor_id: int | None, layout_snapshot: dict[str, Any] | None = None, ) -> dict[str, Any]: """ - ??????????????????????????? + Args: - data: document_id?table_id???????? row_offset??? row_offset ??????? - actor_id: ????? ID???????????????? + data: document_id?table_id row_offset row_offset + actor_id: ID Returns: - ???????????????????????????????????? + """ try: document_id = int(data.get('document_id')) @@ -3179,9 +3244,9 @@ def create_draft_from_sample( operation_id: str | None = None, enforce_lease: bool = False, ) -> dict[str, Any]: """ - ??????? v2 ?????? Profile ??? + v2 Profile - ?????????????????????? HTML??????????? + HTML """ try: document_id = int(data.get('document_id')) @@ -3198,7 +3263,7 @@ def create_draft_from_sample( layout = _document_layout(document) if not isinstance(data.get('definition'), dict): raise ValidationError('Coordinate template definition is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') - # ???????????????????? table/document ??????????? + # table/document if not any(isinstance(item, dict) for item in layout.get('tables') or []): raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') saved = save_draft({ @@ -3217,9 +3282,12 @@ def create_draft_from_sample( profile_id=saved['id'], document_id=document.id, table_id=None, sample_role='annotation', created_by_id=actor_id, )) + db.session.flush() _audit(profile_id=saved['id'], document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ 'sample_role': 'annotation', 'has_table_binding': False, }) + if document.asset_id: + _retain_profile_sample_assets(saved['id'], asset_ids={int(document.asset_id)}) db.session.commit() return saved @@ -3231,21 +3299,21 @@ def save_draft( enforce_lease: bool = False, commit: bool = True, ) -> dict[str, Any]: """ - ?????????????????????? Revision? + Revision? Args: - data: ????????? Profile ????????? - actor_id: ???????? - profile_id: ?????????????? - browser_session_id: ?????????????????? - lease_token: ????????????????? - operation_id: ????? Revision ???????? - change_source: ????????????? restore? - enforce_lease: ? True ??????????????? - commit: ? False ??????????????????????????? + data: Profile + actor_id: + profile_id: + browser_session_id: + lease_token: + operation_id: Revision + change_source: restore? + enforce_lease: ? True + commit: ? False Returns: - ??????????? Profile DTO????? Revision ??? + Profile DTO Revision """ operation = str(operation_id or secrets.token_hex(16)).strip() profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None @@ -3457,7 +3525,7 @@ def save_draft( ) db.session.add(profile) else: - # ?????????????????????? Revision??????????????? + # Revision if ( profile.structure_fingerprint != definition_checksum or previous_display_name != next_display_name @@ -3505,6 +3573,8 @@ def save_draft( # readiness audit records sample_id; assign it within this outer save transaction # before the shared evidence-freeze service is invoked. db.session.flush() + if annotation_document.asset_id: + _retain_profile_sample_assets(profile.id, asset_ids={int(annotation_document.asset_id)}) layout = _document_layout(annotation_document) if not any( isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id @@ -3553,7 +3623,7 @@ def save_draft( profile_id=profile.id, definition_checksum=profile.structure_fingerprint, ).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first() revision = retry_revision - # ?????????????????????? Revision??????????????? + # Revision has_effective_change = ( previous_definition is None or previous_definition != definition @@ -3562,7 +3632,7 @@ def save_draft( or change_source == 'restore' or latest_revision is None ) - # definition ????????????? ValidationRun ?? stale + # definition ValidationRun stale if previous_definition is not None and previous_definition != definition: clear_matching_signature_refs( profile, actor_id=actor_id, operation_id=operation, reason='definition_changed', @@ -3589,7 +3659,7 @@ def save_draft( elif revision is None: revision = latest_revision if revision is None: - # ?????????????????????????????? + # raise ValidationError('Draft revision could not be created', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') _audit(profile_id=profile.id, event_type='draft_saved', actor_id=actor_id, operation_id=operation, browser_session_id=str(browser_session_id or '').strip() or None, revision_no=revision.revision_no, detail={ @@ -3617,17 +3687,17 @@ def _resolve_annotation_document( required: bool, ) -> ShippingOrderDocument | None: """ - ?? XFA ???????/????? + XFA / Args: - profile: ???? Profile? - data: ?????? sample_document_id? + profile: Profile? + data: sample_document_id? Returns: - ShippingOrderDocument ??? + ShippingOrderDocument Raises: - NotFoundError / ValidationError: ????????? Profile? + NotFoundError / ValidationError: Profile? """ document_id = data.get('sample_document_id') if document_id not in (None, ''): @@ -3670,7 +3740,7 @@ def _resolve_annotation_document( def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: - """??????????????????????????????????????""" + """""" source = db.session.get(ShippingOrderDocumentProfile, profile_id) if source is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -3707,7 +3777,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: profile_id=source.id, sample_role='annotation', ).all() for sample in annotation_samples: - # ??????? annotation ???? PDF?????????????????????? + # annotation PDF db.session.add(ShippingOrderDocumentProfileSample( profile_id=clone.id, document_id=sample.document_id, @@ -3748,7 +3818,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: def create_schema_migration_draft( profile_id: int, *, target_schema_version_id: int, resolutions: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: - """???? Profile ???????????????????????""" + """ Profile """ source = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if source is None or source.status != 'published': raise ValidationError( @@ -3945,6 +4015,9 @@ def create_schema_migration_draft( ) db.session.add(clone) db.session.flush() + # 迁移草稿会随源 Profile 拷贝标注/训练样本;新样本引用同一批文档资产, + # 必须为这些资产建立引用,避免它们被临时清理回收。 + copied_asset_ids: set[int] = set() for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=source.id).all(): if sample.sample_role not in {'annotation', 'training'}: continue @@ -3955,6 +4028,11 @@ def create_schema_migration_draft( sample_role=sample.sample_role, created_by_id=actor_id, )) + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is not None and document.asset_id: + copied_asset_ids.add(int(document.asset_id)) + db.session.flush() + _retain_profile_sample_assets(clone.id, asset_ids=copied_asset_ids) _refresh_training_sample_count(clone) # A migration is a new editable baseline, not a continuation of the source's revisions. # This keeps restore and publish-check workflows scoped to the target Schema snapshot. @@ -3989,7 +4067,7 @@ def create_schema_migration_draft( def publish( profile_id: int, *, actor_id: int | None, expected_lock_version: Any, commit: bool = True, ) -> dict[str, Any]: - """????????????????commit=False ???????????????""" + """commit=False """ try: profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: @@ -4025,7 +4103,7 @@ def publish( 'All draft order field layouts must be bound before publish', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - # ?????????/????????????????? manual_confirmation ??? + # / manual_confirmation from app.services.shipping_notice.document_profile_quality_service import ( assert_profile_publishable, ensure_manual_confirmation_qualification, @@ -4095,6 +4173,7 @@ def publish( profile=profile, draft_checksum=draft_checksum, published_checksum=str(profile.checksum or ''), + actor_id=actor_id, ) profile.status = 'published' profile.published_by_id = actor_id @@ -4120,7 +4199,7 @@ def publish( def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]: - """????????????? Run ??????????""" + """ Run """ profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -4138,10 +4217,10 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]: def delete_draft(profile_id: int) -> None: """ - ???????????????/??????????/??????????? + // - ?????checksum ?????? profile ???? suites?? suites/auto_freeze - ? profile_id ?? DB CASCADE??????????????? IntegrityError 500? + checksum profile suites suites/auto_freeze + ? profile_id DB CASCADE IntegrityError 500? """ profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: @@ -4151,23 +4230,35 @@ def delete_draft(profile_id: int) -> None: 'Only draft order document profile can be deleted', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED', ) - # [STEP 1] ?????????quality_suite_id ? CASCADE???? suite ??? + # [STEP 1] quality_suite_id ? CASCADE suite ShippingDocumentProfileAutoFreezeQualification.query.filter_by( profile_id=profile.id, ).delete(synchronize_session=False) - # [STEP 2] ??? Profile ????????? superseded??samples/runs ? ORM cascade + # [STEP 2] Profile supersededsamples/runs ? ORM cascade suites = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).all() for suite in suites: db.session.delete(suite) if suites: db.session.flush() - # [STEP 3] ???? Profile ????????? DB CASCADE? + # [STEP 3] 删除 Profile 前释放其样本资产引用;同一资产在本 Profile 内只释放一次。 + asset_ids = { + int(document.asset_id) + for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() + if (document := db.session.get(ShippingOrderDocument, int(sample.document_id))) is not None and document.asset_id + } + for asset_id in asset_ids: + asset = db.session.get(FileAsset, asset_id) + if asset is not None and int(asset.reference_count or 0) > 0: + from app.services.file_assets.service import release_asset_reference + + release_asset_reference(asset) + # [STEP 4] Profile DB CASCADE? db.session.delete(profile) db.session.commit() def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any]]: - """???? Schema ??? Profile ?????????? field_id ?????""" + """ Schema Profile field_id """ target_schema = db.session.get(ShippingOrderSchemaVersion, int(schema_version_id)) if target_schema is None or target_schema.status != 'published': return [] @@ -4247,7 +4338,7 @@ def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any def _require_sample_document(document_id: int) -> ShippingOrderDocument: - """? ID ??????????? NotFoundError?""" + """? ID NotFoundError?""" document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError( diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index b584ee46..1ca8cf97 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -1136,6 +1136,20 @@ def _published_representative_samples(profile_id: int) -> list[ShippingOrderDocu ).all() +def published_rival_snapshots_for_overlap(profile: ShippingOrderDocumentProfile) -> list[dict[str, Any]]: + """ + 跨模板唯一性候选:同 Schema 已发布快照,但排除本模板族。 + + 发布时同 profile_code 的旧 published 会被 retire,新草稿不必与自家旧版比唯一性; + 否则 clone 出的 v2 几乎必然与 v1 冲突。 + """ + code = str(profile.profile_code or '') + return [ + item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id) + if str(item.get('profile_code') or '') != code + ] + + def _build_coordinate_overlap_evidence( *, profile: ShippingOrderDocumentProfile, @@ -1152,11 +1166,7 @@ def _build_coordinate_overlap_evidence( definition = dict(profile.definition_json or {}) thresholds = _match_thresholds(definition) schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {} - published = [ - item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id) - if str(item.get('profile_code') or '') != profile.profile_code - or int(item.get('version') or 0) != int(profile.version) - ] + published = published_rival_snapshots_for_overlap(profile) candidates = [draft_snapshot, *published] sample_role_pollution = _detect_sample_role_pollution(profile) diff --git a/backend/app/services/shipping_notice/order_edit_window_service.py b/backend/app/services/shipping_notice/order_edit_window_service.py new file mode 100644 index 00000000..36268b77 --- /dev/null +++ b/backend/app/services/shipping_notice/order_edit_window_service.py @@ -0,0 +1,182 @@ +""" +services/shipping_notice/order_edit_window_service.py + +用途:确认后、Excel 生成前的订单编辑窗谓词(设计 D10 / §3.1)。集中判定哪些头字段/行字段允许编辑, + 前端 fail-closed 渲染,后端保存守卫复用同一谓词。 +依赖:ShippingNotice / ShippingExportArtifact / ShippingOrderReviewWaveLine / progress_workflow。 +逻辑(§3.1 矩阵): + header = 该订单**任一通知**无 Export Artifact 且无活动 Gate Attempt; + lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt; + 行未入波次 → 无活动 Attempt(不受首单 Excel 限制,D10)。 + 编辑窗谓词收敛在单一服务,避免「用户不修改原始订单」原则被扩大解释(D12)。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ShippingNotice, ShippingOrderTask +from app.models.shipping_excel_template import ShippingExportArtifact + + +# 导出产物一旦落库即视为 Excel 已生成(锁定边界 D7);上传中/已上传同属生成后。 +_ARTIFACT_LOCK_STATUSES = frozenset({'ready', 'uploading', 'uploaded', 'succeeded', 'success'}) + + +def _notice_has_export_artifact(notice: ShippingNotice) -> bool: + """该通知是否已生成导出产物(Excel)。""" + if getattr(notice, 'id', None) is None: + return False + row = ( + ShippingExportArtifact.query + .filter(ShippingExportArtifact.task_id == int(notice.id)) + .order_by(ShippingExportArtifact.id.desc()) + .first() + ) + return bool(row is not None and str(row.status or '') in _ARTIFACT_LOCK_STATUSES) + + +def _notice_has_active_attempt(notice: ShippingNotice) -> bool: + """该通知是否有活动 Gate Attempt(库存 RPA / 匹配 queued|running)。""" + from app.services.shipping_notice.progress_workflow import _has_active_gate_attempts + + task = db_session_get(ShippingOrderTask, int(notice.order_task_id)) if getattr(notice, 'order_task_id', None) else None + return bool(_has_active_gate_attempts(task)) if task is not None else False + + +def _order_notices(notice: ShippingNotice) -> list[ShippingNotice]: + """同一订单(同 order_task_id)下的全部通知(含波次);无 OT 指针时退回本通知。""" + order_task_id = getattr(notice, 'order_task_id', None) + if not order_task_id: + return [notice] + rows = list( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(order_task_id)) + .order_by(ShippingNotice.id.asc()) + .all() + ) + return rows or [notice] + + +def order_has_active_attempt(order_task: ShippingNotice) -> bool: + """订单级活动 Attempt 判定:该订单**任一通知**有活动 Gate Attempt(§3.1 header 谓词)。""" + return any(_notice_has_active_attempt(n) for n in _order_notices(order_task)) + + +def _review_case_id_for_notice(notice: ShippingNotice) -> int | None: + """回读该通知所属复核 Case(经 ConfirmedRevision);无则 None。""" + from app.models import ShippingOrderReviewConfirmedRevision, ShippingOrderTask + + task_id = getattr(notice, 'order_task_id', None) + if task_id is None: + return None + row = ( + ShippingOrderReviewConfirmedRevision.query + .filter(ShippingOrderReviewConfirmedRevision.task_id == int(task_id)) + .order_by(ShippingOrderReviewConfirmedRevision.id.desc()) + .first() + ) + return int(row.case_id) if row is not None else None + + +def _wave_line_to_notice_map(review_case_id: int | None) -> dict[str, int]: + """复核 Case 下的 snapshot_line_id -> 波次通知 task_id 映射。""" + if review_case_id is None: + return {} + from app.models import ShippingOrderReviewWaveLine + + rows = ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(review_case_id)).all() + return { + str(row.snapshot_line_id): int(row.task_id) + for row in rows + if row.snapshot_line_id is not None + } + + +def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]: + """该订单可编辑范围内的全部冻结行身份(以 Snapshot 行为准,波次行并入)。""" + from app.models.shipping_notice_line import ShippingNoticeLine + + notice_id = getattr(notice, 'id', None) + if notice_id is None: + return [] + keys: list[str] = [] + for item in ( + ShippingNoticeLine.query + .filter(ShippingNoticeLine.notice_id == int(notice_id)) + .order_by(ShippingNoticeLine.position.asc()) + .all() + ): + key = str(getattr(item, 'snapshot_line_id', '') or '').strip() + if key: + keys.append(key) + review_case_id = _review_case_id_for_notice(notice) + if review_case_id is not None: + for key in _wave_line_to_notice_map(review_case_id): + if key not in keys: + keys.append(key) + return sorted(set(keys), key=lambda value: int(value)) + + +def editable_scope(order_task: ShippingNotice) -> dict[str, Any]: + """ + 计算确认后订单的编辑窗矩阵(D10 / §3.1)。 + + header = 该订单全部通知(含波次)无 Export Artifact 且无活动 Gate Attempt。 + lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt; + 行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。 + + Args: + order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。 + + Returns: + dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。 + """ + notices = _order_notices(order_task) + order_busy = any(_notice_has_active_attempt(n) for n in notices) + header_has_excel = any(_notice_has_export_artifact(n) for n in notices) + + header = (not header_has_excel) and (not order_busy) + + wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task)) + lines: dict[str, bool] = {} + for snapshot_line_id in _order_snapshot_line_ids(order_task): + wave_task_id = wave_notice_map.get(snapshot_line_id) + if wave_task_id is None: + # 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。 + lines[snapshot_line_id] = not order_busy + continue + wave_notice = next((n for n in notices if int(getattr(n, 'id', 0)) == int(wave_task_id)), None) + wave_notice = wave_notice or db_session_get(ShippingNotice, int(wave_task_id)) + lines[snapshot_line_id] = ( + (not _notice_has_export_artifact(wave_notice)) and (not order_busy) + if wave_notice is not None else False + ) + + return {'header': header, 'lines': lines} + + +def db_session_get(model: Any, pk: int) -> Any: + """最小 Session get 封装,避免模块顶部导入 db 形成循环。""" + from app import db + + return db.session.get(model, int(pk)) + + +def assert_field_editable(scope: dict[str, Any], *, field: dict[str, Any], snapshot_line_id: str | None = None) -> bool: + """ + 保存守卫辅助:按谓词判断单个头字段/行字段是否可编辑。 + + Args: + scope: editable_scope 结果。 + field: 目标字段描述(含 scope='header' 或 scope='line')。 + snapshot_line_id: line 作用域时必填;None 视为 header。 + + Returns: + bool:可编辑返回 True;应被 SHIPPING.EDIT_WINDOW_FIELD_LOCKED 拒绝时返回 False。 + """ + if str((field or {}).get('scope') or '').strip() == 'line': + if not snapshot_line_id: + return False + return bool(scope.get('lines', {}).get(snapshot_line_id)) + return bool(scope.get('header')) diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index b64338ad..d6af1881 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -49,7 +49,6 @@ from app.models import ( ShippingOrderDocument, ShippingOrderIntake, ShippingOrderTask, - ShippingNotice, ShippingOrderExtraction, ) from app.services.shipping_notice.business_fingerprint import ( @@ -503,9 +502,7 @@ def persist_order_extraction_result( if str(item.get('reason') or '') != 'layout_table_needs_review' ]) summary = {**dynamic['header'], 'lines': dynamic['lines']} - # Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。 - if summary.get('bill_to_customer'): - summary['customer_name'] = summary['bill_to_customer'] + # Bill-to 仅保留为订单原文/识别证据,不复制为通用客户名称。 if dynamic['blocked_fields']: blocked_set = { str(code).strip() @@ -659,7 +656,6 @@ def persist_order_extraction_result( 'findings': list(dynamic.get('findings') or []), 'diagnostic_findings': diagnostic_findings, }, - 'customer_matches': dynamic['customer_matches'], 'missing_required_fields': assessment['missing_required_fields'], 'missing_process_fields': assessment['missing_process_fields'], 'process_issues': assessment['process_issues'], @@ -933,7 +929,7 @@ def persist_order_extraction_result( if not target_no: continue target = ( - db.session.query(ShippingNotice) + db.session.query(ShippingOrderTask) .filter_by(task_no=target_no, user_id=int(session.user_id)) .with_for_update() .first() @@ -1107,7 +1103,7 @@ def submit_order_extraction_run_result( } task_nos = sorted({ str(task.task_no) - for task in ShippingNotice.query.filter(ShippingNotice.id.in_(consumed_task_ids)).all() + for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(consumed_task_ids)).all() }) if consumed_task_ids else [] pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None] result = { @@ -1348,8 +1344,8 @@ def submit_order_extraction_unit_result( if consumed: task_nos = sorted({ str(task.task_no) - for task in ShippingNotice.query.filter( - ShippingNotice.id.in_([int(row.consumed_task_id) for row in consumed]) + for task in ShippingOrderTask.query.filter( + ShippingOrderTask.id.in_([int(row.consumed_task_id) for row in consumed]) ).all() }) result = { diff --git a/backend/app/services/shipping_notice/order_extraction_merge.py b/backend/app/services/shipping_notice/order_extraction_merge.py index bd8b4bca..275fefda 100644 --- a/backend/app/services/shipping_notice/order_extraction_merge.py +++ b/backend/app/services/shipping_notice/order_extraction_merge.py @@ -4,7 +4,7 @@ services/shipping_notice/order_extraction_merge.py 用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。 依赖:Run 冻结动态 Schema field_id/field_code 映射。 逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并; - 跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。 + 跨文档 Reservation 补全优先使用 part_number / customer_po_line_no。 阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id (多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。 """ @@ -52,7 +52,7 @@ def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> st def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]: """读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。""" anchors: dict[str, str] = {} - for field_code in ('part_number', 'customer_po_line_no', 'line_no'): + for field_code in ('part_number', 'customer_po_line_no'): values = _field_values(line.get('fields'), field_code, codes) if len(values) == 1: anchors[field_code] = next(iter(values)) @@ -104,11 +104,11 @@ def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[s for value in _field_values(order.get('header_fields'), field_code, codes) if (normalized := normalize_atomic_po_number(value).upper()) } - line_keys = { + line_identities = { identity for line in order.get('lines') or [] if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None } - return po_numbers, line_keys + return po_numbers, line_identities def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None: @@ -196,7 +196,7 @@ def merge_unit_orders( order = copy.deepcopy(raw) intake_no = str(order.get('source_intake_no') or '').strip().upper() primary_document_id = order.get('primary_document_id') - po_numbers, line_keys = _order_identity(order, codes) + po_numbers, line_identities = _order_identity(order, codes) match = None matched_by_po = False for candidate in merged: @@ -212,7 +212,7 @@ def merge_unit_orders( continue candidate_pos, candidate_lines = _order_identity(candidate, codes) matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos - if matched_by_po or bool(line_keys & candidate_lines): + if matched_by_po or bool(line_identities & candidate_lines): match = candidate break if match is None: 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 65fa9f46..3b5b081b 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -3306,6 +3306,8 @@ def list_order_extraction_run_summaries( 核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体; `input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。 + 会话短列表(非分页)优先返回带 client_submission_id 的 submission primary, + 避免一次多 Intake 拆出的 sibling 因 created_at 更新被误选为恢复锚点。 Args: user_id: 当前用户主键。 @@ -3341,8 +3343,19 @@ def list_order_extraction_run_summaries( ShippingOrderProcessingRun.last_activity_at, ShippingOrderProcessingRun.created_at, ShippingOrderProcessingRun.updated_at, + ShippingOrderProcessingRun.client_submission_id, ) - statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc()) + # [STEP] 会话恢复短列表:primary(有 client_submission_id)排前,再按创建时间倒序。 + # 分页任务中心仍按纯时间序,避免 sibling 被隐藏。 + if conversation_id and page is None and page_size is None: + statement = select(*columns).where(*filters).order_by( + ShippingOrderProcessingRun.client_submission_id.isnot(None).desc(), + ShippingOrderProcessingRun.created_at.desc(), + ) + else: + statement = select(*columns).where(*filters).order_by( + ShippingOrderProcessingRun.created_at.desc(), + ) if page is None and page_size is None: return list(db.session.execute( statement.limit(min(max(int(limit or 50), 1), 100)), @@ -3613,6 +3626,8 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str, if isinstance(run.input_snapshot_json, dict) else None ), + # 仅 submission primary 有值;sibling Run 为空。聊天恢复必须锚定 primary,禁止用 sibling 再建卡。 + 'client_submission_id': str(run.client_submission_id or '').strip() or None, 'schema_version_id': run.schema_version_id, 'schema_version': schema_snapshot.get('version'), 'schema_checksum': schema_snapshot.get('checksum'), @@ -3662,6 +3677,9 @@ def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]: 'conversation_id': row['conversation_id'], 'status': str(row['status'] or 'queued'), 'phase': str(row['phase'] or row['status'] or 'queued'), + 'client_submission_id': ( + str(row.get('client_submission_id') or '').strip() or None + ), 'summary': { 'total_documents': int(progress_summary.get('total_documents') or 0), 'pending_documents': int(progress_summary.get('pending_documents') or 0), @@ -4506,12 +4524,18 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None: Args: job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。 """ + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first() if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'cancelled'}: return 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', 'processing'}: + elif ( + project_job_status_outcome(getattr(job, 'status', None)) == 'failed' + or str(getattr(job, 'status', None) or '').strip().lower() == 'cancelled' + ) and run.status in {'queued', 'processing'}: if run.status == 'queued': transition_order_extraction_run(run, target_status='processing', phase='timeout_failing') transition_order_extraction_run( diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index d3a1a077..dff2cfd3 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -372,7 +372,7 @@ def _coordinate_profile_rows( return None rows: list[dict[str, Any]] = [] runtime_region_ids = set(select_runtime_region_ids( - table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no, + table_regions=[_coordinate_object_mapping(region) for region in profile.table_regions], page_no=page_no, )) for region in profile.table_regions: # 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页 @@ -385,7 +385,11 @@ def _coordinate_profile_rows( relative_region = _coordinate_region_mapping(region.region) if relative_region is None: return None - reference_page_frame = profile.reference_page_frames.get(page_no) + reference_page_frames = getattr(profile, 'reference_page_frames', {}) + reference_page_frame = ( + reference_page_frames.get(page_no) + if isinstance(reference_page_frames, dict) else None + ) reconstruction_page_bbox = ( { 'x0': 0, 'y0': 0, @@ -395,9 +399,10 @@ def _coordinate_profile_rows( ) raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None characters, _candidate_page_bbox = coordinate_profile_character_candidates( - table_region=region.region.model_dump(), page_size=page_size, + table_region=_coordinate_object_mapping(region.region), page_size=page_size, reference_page_frame=( - reference_page_frame.model_dump() if reference_page_frame is not None else None + _coordinate_object_mapping(reference_page_frame) + if reference_page_frame is not None else None ), page_characters=page_characters if isinstance(page_characters, list) else None, table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None, @@ -410,11 +415,11 @@ def _coordinate_profile_rows( carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {} for reconstructed in reconstruct_coordinate_profile_rows( characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox, - line_layouts=[item.model_dump() for item in region.line_layouts], + line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts], table_region=relative_region, - termination_rules=[item.model_dump() for item in region.termination_rules], + termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules], exclusion_regions=reconstruction_exclusion_regions( - region.model_dump(), + _coordinate_object_mapping(region), ), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), line_start_field_code=region.line_start_field_code, @@ -514,12 +519,7 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: Returns: 包含 x0/y0/x1/y1 的合法浮点坐标;缺字段、非数值或区域退化时返回 None。 """ - if isinstance(value, dict): - raw = value - elif callable(getattr(value, 'model_dump', None)): - raw = value.model_dump() - else: - raw = {key: getattr(value, key, None) for key in ('x0', 'y0', 'x1', 'y1')} + raw = _coordinate_object_mapping(value) if not isinstance(raw, dict): return None try: @@ -531,6 +531,22 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: return region +def _coordinate_object_mapping(value: Any) -> dict[str, Any]: + """将冻结坐标契约对象转换为字典,兼容 Pydantic 与测试使用的轻量对象。 + + 生产 Profile 使用 Pydantic ``model_dump``;运行时和回归测试也允许同字段的 + 轻量对象。转换失败返回空字典,后续既有坐标校验按证据不足处理,不扩大匹配范围。 + """ + if isinstance(value, dict): + return value + dump = getattr(value, 'model_dump', None) + if callable(dump): + raw = dump() + return raw if isinstance(raw, dict) else {} + raw = getattr(value, '__dict__', None) + return dict(raw) if isinstance(raw, dict) else {} + + def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool: """判断两个 PDF 绝对坐标区域是否有面积交集;无效坐标按不相交处理。""" try: @@ -549,11 +565,23 @@ def _physical_table_targets_profile_region( reference_page_frame: dict[str, Any] | None = None, coordinate_transform: dict[str, Any] | None = None, ) -> bool: - """判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。 + """ + 判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。 - 同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建 - 而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退, - 避免表检测遗漏被错误跳过。 + 核心逻辑:同页页脚/签章等非目标 MinerU 表不得因重建失败阻断已成功目标表。 + 当前页已配置专属表区但全部没有 ``line_layouts``(仅表头壳)时明确跳过, + 避免空重建产出 ``PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION`` 污染整单。 + 虚拟页、缺失 bbox 或页尺寸异常时仍 fail-open,避免表检测遗漏被错误跳过。 + + Args: + raw_table: 物理表身份、页码与 bbox。 + table_regions: 冻结 Profile 的表区列表(含 page_scope / line_layouts)。 + page_size: 当前页宽高;缺失时保守保留候选。 + reference_page_frame: 可选参考页框,用于相对坐标投影。 + coordinate_transform: matcher 已确认的平移;可为 None。 + + Returns: + True 表示应进入坐标行重建;False 表示跳过该物理表。 """ page_no = int(raw_table.get('page_no') or 1) if str(raw_table.get('table_id') or '') == f'page-{page_no}': @@ -572,15 +600,23 @@ def _physical_table_targets_profile_region( active_region_ids = set(select_runtime_region_ids( table_regions=table_regions, page_no=page_no, )) - active_regions = [ + # [STEP 1] 当前页被选中的表区(不论是否含明细子行) + page_regions = [ region for region in table_regions if isinstance(region, dict) and str(region.get('region_id') or '') in active_region_ids and isinstance(region.get('region'), dict) - and region.get('line_layouts') + ] + if not page_regions: + # 本页无模板表区配置:保守保留,供虚拟页/漏检回退。 + return True + # [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。 + active_regions = [ + region for region in page_regions + if region.get('line_layouts') ] if not active_regions: - return True + return False for region in active_regions: projected = apply_coordinate_transform_to_region( region['region'], coordinate_transform=coordinate_transform, @@ -881,20 +917,24 @@ def _profile_table_candidates( profile_match=profile_match, raw_profile=raw_profile, ) profile_table_regions = [ - item.model_dump() for item in profile.table_regions - if callable(getattr(item, 'model_dump', None)) + _coordinate_object_mapping(item) for item in profile.table_regions ] evidence_pages = ( (layout.get('coordinate_evidence') or {}).get('pages') or {} ) page_size = evidence_pages.get(str(raw_table.get('page_no') or 1)) - reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + reference_page_frames = getattr(profile, 'reference_page_frames', {}) + reference_page_frame = ( + reference_page_frames.get(int(raw_table.get('page_no') or 1)) + if isinstance(reference_page_frames, dict) else None + ) if not _physical_table_targets_profile_region( raw_table=raw_table, table_regions=profile_table_regions, page_size=page_size if isinstance(page_size, dict) else None, reference_page_frame=( - reference_page_frame.model_dump() if reference_page_frame is not None else None + _coordinate_object_mapping(reference_page_frame) + if reference_page_frame is not None else None ), coordinate_transform=coordinate_transform, ): @@ -934,14 +974,17 @@ def _profile_table_candidates( except (TypeError, ValueError): issues.append('order_profile_snapshot_invalid') continue - if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: - issues.append('order_profile_coordinate_reconstruction_unavailable') - continue + # 虚拟空页(无业务表)不能把已成功的目标表覆盖成失败;None 与空列表 + # 同样视为“无行”,且必须在该判断之前处理,否则空虚拟页会被 + # is None 分支误判为行重建失败而整单阻断。 if _virtual_page_without_rows_is_nonblocking( raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, dynamic_rows=dynamic_rows, ): continue + if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: + issues.append('order_profile_coordinate_reconstruction_unavailable') + continue strategy = resolve_runtime_parse_strategy( page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {}, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 3f9c4c96..6a6b6b50 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -1317,7 +1317,13 @@ def _unresolved_review_document_count( def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]: - """返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。""" + """返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。 + + 转瞬/未持久化 Run(id=None,如纯单元投影)不存在落库 Case,按空集处理, + 与 _duplicate_projection_by_document / _pending_order_facts 的 run.id 防空一致。 + """ + if getattr(run, 'id', None) is None: + return [] return ( db.session.query(ShippingOrderReviewCase) .join( diff --git a/backend/app/services/shipping_notice/order_field_purposes.py b/backend/app/services/shipping_notice/order_field_purposes.py index 7cae906b..6fcdf4b6 100644 --- a/backend/app/services/shipping_notice/order_field_purposes.py +++ b/backend/app/services/shipping_notice/order_field_purposes.py @@ -26,7 +26,10 @@ _PURPOSE_BY_CAPABILITY = { def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]: """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" source_notice = _source_notice_for_order_facts(task) - snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于履约的冻结订单快照') rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule') diff --git a/backend/app/services/shipping_notice/order_freeze_service.py b/backend/app/services/shipping_notice/order_freeze_service.py index 4165b0a9..6f7e371a 100644 --- a/backend/app/services/shipping_notice/order_freeze_service.py +++ b/backend/app/services/shipping_notice/order_freeze_service.py @@ -2,10 +2,10 @@ services/shipping_notice/order_freeze_service.py 用途:将已复核的动态订单解析冻结为强类型履约快照。 -依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingNotice、 +依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingOrderTask、 standard_field_registry(投影列)、audit_service、统一 AppError。 逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot; - 冻结时固化 derivation_rules 快照与 field_lineage;库存、导出和上传后续阶段只读取该快照。 + 冻结时固化字段血缘;库存、导出和上传后续阶段只读取该快照。 """ from __future__ import annotations @@ -22,11 +22,10 @@ from app.models import ( ShippingOrderFieldObservation, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderCustomerMatch, ShippingOrderReviewEvent, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNotice, + ShippingOrderTask, ShippingOrderDocument, ) from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -56,7 +55,7 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date' def freeze_order_snapshot( - task: ShippingNotice, + task: ShippingOrderTask, *, actor_id: int | None, expected_order_data_version: int, @@ -88,9 +87,9 @@ def freeze_order_snapshot( # query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端 # 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。 locked_task = ( - ShippingNotice.query + ShippingOrderTask.query .filter_by(id=task.id) - .with_for_update(of=ShippingNotice) + .with_for_update(of=ShippingOrderTask) .one() ) if locked_task.order_snapshot_id: @@ -110,7 +109,7 @@ def freeze_order_snapshot( ) extraction = _accepted_extraction(task) policy, configs = _policy_configs(extraction) - customer_match = _confirmed_ordering_customer(extraction) + customer_resolution = _confirmed_ordering_customer(task) from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness assert_freeze_readiness( task=task, @@ -127,23 +126,11 @@ def freeze_order_snapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=extraction.schema_version_id, - customer_id=customer_match.customer_id, - customer_short_code_snapshot=customer_match.customer_short_code_snapshot, + customer_id=customer_resolution.confirmed_customer_id, + customer_short_code_snapshot=_confirmed_customer_short_code(customer_resolution), order_data_version=actual_version, rule_versions_json={ **dict(rule_versions or {}), - 'derivation_rules_snapshot': list( - ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get('derivation_rules') - or [] - ), - 'derivation_rules_checksum': ( - ((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get( - 'derivation_rules_checksum' - ) - or ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get( - 'derivation_rules_checksum' - ) - ), 'fulfillment_rule': { 'code': policy['rule_code'], 'checksum': _fixed_rule_checksum(), @@ -151,12 +138,12 @@ def freeze_order_snapshot( 'required_field_ids': {code: config['field_id'] for code, config in configs.items()}, }, 'ordering_customer': { - 'match_id': customer_match.id, - 'identity_fingerprint': customer_match.identity_fingerprint, - 'identity_rule_version': customer_match.identity_rule_version, - 'resolution_method': customer_match.resolution_method, - 'confirmed_by_id': customer_match.confirmed_by_id, - 'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None, + 'resolution_id': customer_resolution.id, + 'identity_rule_set_checksum': customer_resolution.identity_rule_set_checksum, + 'identity_rule_set_version': customer_resolution.identity_rule_set_version, + 'confirmation_method': customer_resolution.confirmation_method, + 'confirmed_by_id': customer_resolution.confirmed_by_id, + 'confirmed_at': customer_resolution.confirmed_at.isoformat() if customer_resolution.confirmed_at else None, }, }, source_manifest_json={ @@ -174,17 +161,19 @@ def freeze_order_snapshot( ) db.session.add(snapshot) db.session.flush() - for position, source in enumerate(line_values): + for position, source in enumerate(line_values, start=1): + # 订单项次是系统项次,不采信客户 PO 行号或解析派生值;冻结后按本订单固定为 1..N。 + source = dict(source) + source['line_no'] = position db.session.add(ShippingOrderSnapshotLine( snapshot_id=snapshot.id, - position=position, + position=position - 1, field_values_json=_field_id_values(source, configs), **_project_values(source, LINE_FIELD_PROJECTIONS), )) db.session.flush() - from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot - - replace_notice_lines_from_snapshot(notice_id=int(task.id), snapshot=snapshot) + # Snapshot 只是冻结订单事实;ShippingNoticeLine 属于正式发货通知, + # 必须在库存确认通过或人工放行后创建,不能在冻结阶段提前生成。 task.order_snapshot_id = snapshot.id ShippingOrderReviewEvent.query.filter_by( task_id=task.id, @@ -202,13 +191,11 @@ def freeze_order_snapshot( result='success', metadata={ 'snapshot_id': snapshot.id, - 'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'), 'schema_version_id': extraction.schema_version_id, }, after={ 'task_no': task.task_no, 'schema_version_id': extraction.schema_version_id, - 'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'), }, ) db.session.flush() @@ -270,13 +257,13 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic } -def assert_task_order_is_editable(task: ShippingNotice) -> None: +def assert_task_order_is_editable(task: ShippingOrderTask) -> None: """拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。""" if task.order_snapshot_id: raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN') -def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction: +def _accepted_extraction(task: ShippingOrderTask) -> ShippingOrderExtraction: """读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。""" extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None if extraction is None or extraction.status != 'accepted': @@ -284,12 +271,14 @@ def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction: return extraction -def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> ShippingOrderCustomerMatch: - """只接受已人工确认的 Bill-to 订购客户,禁止由冻结请求自由指定 customer_id。""" - row = ShippingOrderCustomerMatch.query.filter_by(extraction_id=extraction.id, role='bill_to').one_or_none() +def _confirmed_ordering_customer(task: ShippingOrderTask) -> Any: + """只接受正式客户识别结果,禁止由任一订单字段或冻结请求指定客户。""" + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + row = resolution_for_task(task) if ( - row is None or row.status != 'confirmed' or row.customer_id is None - or not row.customer_short_code_snapshot or not row.identity_fingerprint or not row.identity_rule_version + row is None or row.status != 'confirmed' or row.confirmed_customer_id is None + or not row.evidence_json or not row.identity_rule_set_checksum ): raise ValidationError( 'Ordering customer must be confirmed before freezing', @@ -298,6 +287,14 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin return row +def _confirmed_customer_short_code(resolution: Any) -> str: + """从已确认标准客户读取简称;订单原文和 bill_to 不得提供业务简称。""" + from app.models import ShippingCustomer + + customer = db.session.get(ShippingCustomer, int(resolution.confirmed_customer_id)) + return str(getattr(customer, 'short_code', None) or '') + + def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: """按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。""" from app.services.shipping_notice.fulfillment_policy_registry import ( diff --git a/backend/app/services/shipping_notice/order_line_no_resolver.py b/backend/app/services/shipping_notice/order_line_no_resolver.py index 927bd0b3..7f11b6d2 100644 --- a/backend/app/services/shipping_notice/order_line_no_resolver.py +++ b/backend/app/services/shipping_notice/order_line_no_resolver.py @@ -1,12 +1,9 @@ """ backend/app/services/shipping_notice/order_line_no_resolver.py -用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 → - 行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。 +用途:读取已经持久化的订单项次(line_no)。 依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。 -逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用 - 本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源, - 不得把内部行号伪装成业务项次。 +逻辑:line_no 由冻结/正式通知写路径按单据内顺序生成;本模块不执行派生、回退或来源推断。 """ from __future__ import annotations @@ -15,11 +12,6 @@ from typing import Any from app import db from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot -from app.services.shipping_notice.order_schema.field_rules import is_valid_line_no_value - -LINE_NO_SOURCE_FIELD = 'field' -LINE_NO_SOURCE_CUSTOMER_PO_LINE = 'customer_po_line_no' -LINE_NO_SOURCE_SEQUENCE = 'sequence' def field_id_by_code_from_definition( @@ -67,87 +59,67 @@ def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]: return {} -def _read_field( +def _read_persisted_line_no(field_values: dict[str, Any] | None) -> str | None: + """读取冻结行中按 ``line_no`` 规范持久化的项次值。 + + 核心逻辑:项次不是 Schema 字段值,也不是外部单据行号;写路径生成后直接 + 持久化到行事实中,读取层不得按 field_code、客户行号或展示位置猜测。 + """ + values = field_values if isinstance(field_values, dict) else {} + raw = values.get('line_no') + if raw in (None, ''): + return None + text = str(raw).strip() + return text or None + + +def read_field_by_id( field_values: dict[str, Any] | None, field_id_by_code: dict[str, str] | None, code: str, ) -> str | None: - """按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。 - - 核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。 - 任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。 - """ + """按 Schema field_id 读取普通业务字段;不参与系统项次解析。""" values = field_values if isinstance(field_values, dict) else {} - field_id = str(field_id_by_code.get(code) or '') if field_id_by_code else '' - if field_id and field_id in values: - raw = values[field_id] - if raw not in (None, ''): - text = str(raw).strip() - return text or None - if code in values: - raw = values[code] - if raw not in (None, ''): - text = str(raw).strip() - return text or None - return None + field_id = str((field_id_by_code or {}).get(code) or '').strip() + raw = values.get(field_id) if field_id else None + if raw in (None, ''): + return None + text = str(raw).strip() + return text or None def resolve_order_line_no( *, field_values: dict[str, Any] | None, - field_id_by_code: dict[str, str] | None, - fallback_sequence: int | None = None, + field_id_by_code: dict[str, str] | None = None, ) -> dict[str, Any]: """解析一行内部项次展示值(唯一权威入口)。 【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。 - 核心逻辑: - [STEP 1] line_no 字段真实值(须通过 is_valid_line_no_value 格式门禁)→ source=field; - [STEP 2] customer_po_line_no 字段真实值(同格式门禁)→ source=customer_po_line_no; - [STEP 3] 调用方提供的 1..N 行序号 → source=sequence(明确标注为展示序号); - [STEP 4] 全部缺失 → {'value': None, 'source': None}。 - - 与派生规则同门禁:非法项次格式(非 1–6 位数字)一律跳过,不得以序号冒充业务值。 + 核心逻辑:只读取 field_values 中已经持久化的 line_no;customer_po_line_no 和 + 展示序号都不能作为内部项次的替代来源。 Args: field_values: 行字段值 JSON(field_id 或 field_code 键均可)。 - field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。 - fallback_sequence: 1 基展示序号;None 表示无序号兜底。 + field_id_by_code: 已废弃参数,仅为调用方签名稳定保留;不会参与读取。 Returns: - {'value': 规范化字符串或 None, 'source': 'field'|'customer_po_line_no'|'sequence'|None}。 + {'value': 规范化字符串或 None, 'source': 'persisted'|None}。 """ - line_no = _read_field(field_values, field_id_by_code, 'line_no') - if line_no is not None and is_valid_line_no_value(line_no): - return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD} - - customer_line_no = _read_field(field_values, field_id_by_code, 'customer_po_line_no') - if customer_line_no is not None and is_valid_line_no_value(customer_line_no): - return {'value': customer_line_no, 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE} - - if fallback_sequence is not None and int(fallback_sequence) >= 1: - return {'value': str(int(fallback_sequence)), 'source': LINE_NO_SOURCE_SEQUENCE} - return {'value': None, 'source': None} + del field_id_by_code + line_no = _read_persisted_line_no(field_values) + return {'value': line_no, 'source': 'persisted' if line_no is not None else None} def resolve_order_line_no_projection( *, field_values: dict[str, Any] | None, - field_id_by_code: dict[str, str] | None, - fallback_sequence: int | None = None, + field_id_by_code: dict[str, str] | None = None, ) -> dict[str, Any]: - """与 resolve_order_line_no 同源的 UI/导出投影形(line_no / line_no_source 键)。 - - 核心逻辑:仅供展示层消费;把语义结果映射为前端契约键,避免各处手写 - {'line_no': result['value'], 'line_no_source': result['source']} 产生分叉。 - - Returns: - {'line_no': str|None, 'line_no_source': 'field'|'customer_po_line_no'|'sequence'|None}。 - """ + """读取不可变订单项次投影。""" resolved = resolve_order_line_no( field_values=field_values, field_id_by_code=field_id_by_code, - fallback_sequence=fallback_sequence, ) - return {'line_no': resolved['value'], 'line_no_source': resolved['source']} + return {'line_no': resolved['value']} diff --git a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py index a25bf053..f818d8de 100644 --- a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py +++ b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py @@ -1252,7 +1252,6 @@ def build_identity_snapshot(*, profile: Any, revision: Any, samples: list[Any]) def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples: list[Any], blind_samples: list[Any]) -> tuple[str, dict[str, Any], dict[str, Any]]: """复用共同视觉 overlap,并仅追加 datasets 值源身份冲突证据。""" from app.services.shipping_notice import order_document_profile_validation_service as validation_service - from app.services.shipping_notice import order_document_profile_service as profile_service # [STEP 1] 共同 matcher 负责样本、阈值、正反向命中和污染判定;datasets 不得重建该流程。 status, summary, snapshot = validation_service._build_coordinate_overlap_evidence( @@ -1266,12 +1265,11 @@ def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples snapshot = dict(snapshot or {}) # [STEP 2] datasets 仅在共同视觉结论后追加正式值源身份的 fail-closed 冲突。 + # 同 profile_code 旧版会在发布时 retire,不与自家模板比身份冲突。 source = (profile.definition_json or {}).get('source_contract') if isinstance((profile.definition_json or {}).get('source_contract'), dict) else {} template, fingerprint = str(source.get('template_packet_checksum') or '').strip(), str(source.get('dataset_structure_fingerprint') or '').strip() conflicts: list[dict[str, Any]] = [] - for item in profile_service.published_snapshots_for_schema(profile.schema_version_id): - if str(item.get('profile_code') or '') == profile.profile_code and int(item.get('version') or 0) == int(profile.version): - continue + for item in validation_service.published_rival_snapshots_for_overlap(profile): other = item.get('definition') if isinstance(item.get('definition'), dict) else {} other_source = other.get('source_contract') if isinstance(other.get('source_contract'), dict) else {} if template and fingerprint and str(other_source.get('template_packet_checksum') or '') == template and str(other_source.get('dataset_structure_fingerprint') or '') == fingerprint: diff --git a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py index 3e21cfdd..30dcc415 100644 --- a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py +++ b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py @@ -5,10 +5,10 @@ services/shipping_notice/order_review_auto_progress_coordinator.py 依赖:order_review_customer_service、order_review_draft_service(延迟)、 order_stp_auto_create_service(延迟)、candidate_qualification_service、 fulfillment_audit、ShippingCustomerShadowResolution / - ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。 + ShippingOrderReviewCase / ShippingOrderProcessingRun。 逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和 单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口; - 客户协调仅在 shadow.status=unique_candidate 且未 resolve 时自动确认 bill_to; + 客户协调仅在识别结果唯一命中且未确认时自动确认客户; 所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。 注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import, 避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。 @@ -23,19 +23,15 @@ from app import db from app.models import ( ShippingCustomerShadowResolution, ShippingOrderCandidate, - ShippingOrderCustomerMatch, ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewStream, ) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.order_review_customer_service import ( - _header_from_case, - _resolve_extraction_for_case, - confirm_order_customer_match, - refresh_order_customer_matches, resolve_review_case_customer_resolved, ) +from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref # 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import, @@ -73,7 +69,7 @@ def _customer_step_for_case( trigger: str, ) -> tuple[str, dict[str, Any] | None]: """ - 单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。 + 单 Case 客户协调内部步骤:识别结果唯一命中时自动确认客户。 Args: case: 复核 Case。 @@ -105,45 +101,20 @@ def _customer_step_for_case( if already_resolved: return 'skipped', {'reason': 'customer_already_resolved'} - # [STEP 1-3] 提取 order_extraction(Candidate 关联优先,否则 Run 内最新) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - return 'failed', {'reason': 'extraction_missing'} - - # [STEP 1-4] 若无 bill_to match 行,先按当前头字段刷新 - bill_to_exists = ( - ShippingOrderCustomerMatch.query - .filter_by(extraction_id=int(extraction.id), role='bill_to') - .first() - is not None - ) - if not bill_to_exists: - try: - refresh_order_customer_matches(extraction, _header_from_case(case)) - except Exception as exc: # noqa: BLE001 - _LOGGER.warning( - 'refresh_order_customer_matches failed case_no=%s err=%s', - case.case_no, str(exc)[:200], - ) - return 'failed', {'reason': 'refresh_matches_failed', 'error': str(exc)[:200]} - - # [STEP 1-5] 自动确认 bill_to 到 top_customer_id + # [STEP 1-3] 将唯一指纹候选确认到正式识别结果;不创建或读取订单角色投影。 top_customer_id = int(shadow.top_customer_id) confirm_reason = '抽取协调器-客户指纹唯一命中自动确认' try: - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + confirm_customer_resolution( + candidate, customer_id=top_customer_id, - site_id=None, actor_id=None, + method='auto_rule', reason=confirm_reason, - # 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。 - commit=False, ) except Exception as exc: # noqa: BLE001 _LOGGER.warning( - 'confirm_order_customer_match failed case_no=%s err=%s', + 'confirm_customer_resolution failed case_no=%s err=%s', case.case_no, str(exc)[:200], ) return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]} @@ -165,7 +136,7 @@ def _customer_step_for_case( 'candidate_id': int(candidate.id) if candidate is not None else None, 'shadow_status': 'unique_candidate', 'customer_id': top_customer_id, - 'extraction_id': int(extraction.id), + 'extraction_id': getattr(candidate, 'order_extraction_id', None), 'trigger': str(trigger)[:64], 'reason': confirm_reason, }, @@ -177,7 +148,7 @@ def _customer_step_for_case( return 'auto_confirmed', { 'customer_id': top_customer_id, - 'extraction_id': int(extraction.id), + 'extraction_id': getattr(candidate, 'order_extraction_id', None), } @@ -397,7 +368,7 @@ def reconcile_run_review_cases_for_auto_progress( }) continue - # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to + # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认标准客户 customer_status, customer_meta = _customer_step_for_case( case=case, trigger='run_reconcile', ) diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 7ce8d332..15f65e2a 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -3,21 +3,20 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py 用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。 依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、order_task_service、 - stp_inventory_freeze、progress_audit_contract.ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE、 candidate_qualification_service、customer_auto_resolution、fulfillment_audit、 order_review_progress_bridge、workflow_ledger_service、 queue_service.enqueue_shipping_notice_job、process_gate_bridge。 -逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与 - 可自动确认的客户;库存源未唯一确定时按硬门禁拒绝建单并回写 OT stage= - inventory_source_resolving;物化人工 Candidate 时先写入客户已确认事实再执行履约门禁; +逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,固化可自动确认的客户; + 物化人工 Candidate 时先写入客户已确认事实再执行履约门禁; 确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate; 已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate; 缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单; - 物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并 + 物化 accepted Extraction(保留字段 field_lineage);建单前再次校验客户确认并 持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照 - Task 推入库存/RPA; + Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的 + 正式 inventory_source_routing Gate 负责; 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), @@ -50,8 +49,7 @@ from app.models import ( ShippingOrderReviewConfirmedRevision, ShippingOrderReviewDraft, ShippingOrderReviewWaveLine, - ShippingOrderCustomerMatch, - ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, @@ -68,9 +66,6 @@ from app.services.shipping_notice.order_review_draft_service import ( build_confirmable_draft_summary, draft_has_unaccepted_llm_suggestions, ) -from app.services.shipping_notice.progress_audit_contract import ( - ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE, -) from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -221,13 +216,12 @@ def _json_value(value: Any) -> Any: def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]: """ - 读取机器解析 Extraction / Unit 上的派生血缘与规则校验和。 + 读取机器解析 Extraction / Unit 上的字段血缘。 核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json; 否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。 """ rows: list[dict[str, Any]] = [] - checksum: str | None = None candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None if extraction_id: @@ -236,17 +230,9 @@ def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict extraction.normalized_result_json, dict, ) else {} rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)] - raw_checksum = normalized.get('derivation_rules_checksum') - checksum = str(raw_checksum) if raw_checksum else None - if not checksum and extraction is not None and extraction.schema_version is not None: - definition = extraction.schema_version.definition_json or {} - if isinstance(definition, dict) and definition.get('derivation_rules_checksum'): - checksum = str(definition.get('derivation_rules_checksum')) if not rows and case.unit is not None and isinstance(case.unit.result_json, dict): rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)] - if not checksum and case.unit.result_json.get('derivation_rules_checksum'): - checksum = str(case.unit.result_json.get('derivation_rules_checksum')) - return rows, checksum + return rows, None def _confirmation_field_lineage( @@ -255,64 +241,38 @@ def _confirmation_field_lineage( summary_lines: list[dict[str, Any]], ) -> tuple[list[dict[str, Any]], str | None]: """ - 将源解析血缘按行位映射到确认后 Extraction 的 review-* line_key。 + 将源解析血缘按行位映射到确认后 Extraction 的 draft_line_id。 - 核心逻辑:按草稿行顺序对齐;若该行 line_no 已被人工覆盖,则改写为 manual_override 血缘。 + 核心逻辑:按草稿行顺序对齐字段血缘;系统项次不参与人工覆盖。 """ source_rows, checksum = _source_extraction_lineage(case) draft_lines = [ item for item in (case.current_draft.lines_json or []) if isinstance(item, dict) ] - line_no_field_id = None - run = case.run - definition = ( - (run.input_snapshot_json or {}).get('schema', {}).get('definition', {}) - if run is not None and isinstance(run.input_snapshot_json, dict) else {} - ) - for item in definition.get('fields') or []: - if ( - isinstance(item, dict) - and str(item.get('field_code') or '') == 'line_no' - and str(item.get('scope') or '') == 'line' - ): - line_no_field_id = str(item.get('field_id') or '') or None - break - by_key: dict[str, list[dict[str, Any]]] = {} for item in source_rows: - key = str(item.get('line_key') or '').strip() + key = str(item.get('draft_line_id') or '').strip() if key: by_key.setdefault(key, []).append(item) ordered_keys: list[str] = [] for item in source_rows: - key = str(item.get('line_key') or '').strip() + key = str(item.get('draft_line_id') or '').strip() if key and key not in ordered_keys: ordered_keys.append(key) remapped: list[dict[str, Any]] = [] for position, draft_line in enumerate(draft_lines): new_key = f'review-{position + 1}' - old_key = str(draft_line.get('line_key') or '').strip() + old_key = str(draft_line.get('draft_line_id') or '').strip() source_items = list(by_key.get(old_key) or []) if not source_items and position < len(ordered_keys): source_items = list(by_key.get(ordered_keys[position]) or []) - values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {} - override_entry = values.get(line_no_field_id) if line_no_field_id else None - line_no_overridden = ( - isinstance(override_entry, dict) - and str(override_entry.get('source') or '') == 'manual_override' - ) - summary_line = summary_lines[position] if position < len(summary_lines) else {} for item in source_items: row = dict(item) - row['line_key'] = new_key - if str(row.get('field_code') or '') == 'line_no' and line_no_overridden: - row['value_source'] = 'manual_override' - row['after_value'] = summary_line.get('line_no') - row['skip_reason'] = None + row['draft_line_id'] = new_key remapped.append(row) return remapped, checksum @@ -325,23 +285,16 @@ def _build_confirmation_normalized_result( """ 组装确认后 Extraction.normalized_result_json。 - 核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage 与派生规则校验和, - 供冻结快照写入可追溯项次派生来源。 + 核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage, + 供冻结快照写入可追溯字段来源。 """ header_values = {key: value for key, value in summary.items() if key != 'lines'} lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)] - lineage, checksum = _confirmation_field_lineage(case, summary_lines=lines) - if not checksum and case.current_draft is not None: - from app.models import ShippingOrderSchemaVersion - version = db.session.get(ShippingOrderSchemaVersion, int(case.current_draft.schema_version_id)) - definition = (version.definition_json or {}) if version is not None else {} - if isinstance(definition, dict) and definition.get('derivation_rules_checksum'): - checksum = str(definition.get('derivation_rules_checksum')) + lineage, _checksum = _confirmation_field_lineage(case, summary_lines=lines) return { 'header': header_values, 'lines': lines, 'field_lineage': lineage, - 'derivation_rules_checksum': checksum, } @@ -363,9 +316,9 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su for item in configs if str(item.get('scope') or '') == 'line' and item.get('field_code') } - # `line_key` is Draft-only identity used by wave selection and lineage remapping. + # `draft_line_id` is Draft-only identity used by wave selection and lineage remapping. # It is not a Schema business field and must never be materialized as one. - internal_line_fields = {'line_key'} + internal_line_fields = {'draft_line_id'} unknown_line_fields = sorted({ str(key) for line in summary.get('lines') or [] @@ -413,7 +366,12 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su **_field_value_columns(value, str(config.get('value_type') or 'string')), )) for position, values in enumerate(summary.get('lines') or []): - line = ShippingOrderLine(extraction_id=int(extraction.id), position=position, line_key=f'review-{position + 1}') + line = ShippingOrderLine( + extraction_id=int(extraction.id), + position=position, + line_no=position + 1, + draft_line_id=f'review-{position + 1}', + ) db.session.add(line) db.session.flush() for config in configs: @@ -433,59 +391,33 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id), **_field_value_columns(value, str(config.get('value_type') or 'string')), )) - _inherit_confirmed_customer_match(case=case, extraction=extraction) + _inherit_confirmed_customer_resolution(case=case, extraction=extraction) return extraction -def _inherit_confirmed_customer_match( +def _inherit_confirmed_customer_resolution( *, case: ShippingOrderReviewCase, extraction: ShippingOrderExtraction, ) -> None: """ - 把当前 Case 原 Extraction 已确认的 Bill-to 客户复制到人工确认 Extraction。 + 人工确认产生新 Extraction 时保留同一 Candidate 的正式客户识别确认事实。 - 核心逻辑:仅复制当前 PDF Candidate 的 confirmed Bill-to 行;没有确认事实时保持空, - 后续建单前客户门禁仍会 fail-closed。 + 核心逻辑:客户识别结果通过 Candidate 稳定关联,不复制或伪造 bill_to 角色行; + 新 Extraction 只改变订单字段版本,后续 Gate 继续读取该 Candidate 的确认结果。 Args: case: 当前复核 Case。 extraction: 新建的人工确认 Extraction。 """ + del extraction if not case.candidate_id: return - source_candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) - source_extraction_id = getattr(source_candidate, 'order_extraction_id', None) if source_candidate else None - if source_extraction_id is None: + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + resolution = resolution_for_task(db.session.get(ShippingOrderCandidate, int(case.candidate_id))) + if resolution is not None and resolution.status == 'confirmed': return - source = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(source_extraction_id), - role='bill_to', - status='confirmed', - ).first() - if source is None or source.customer_id is None: - return - db.session.add(ShippingOrderCustomerMatch( - extraction_id=int(extraction.id), - role='bill_to', - raw_name=source.raw_name, - normalized_name=source.normalized_name, - source_system=source.source_system, - external_code=source.external_code, - identity_fingerprint=source.identity_fingerprint, - identity_rule_version=source.identity_rule_version, - identity_components_json=copy.deepcopy(source.identity_components_json or {}), - status='confirmed', - customer_id=int(source.customer_id), - site_id=int(source.site_id) if source.site_id is not None else None, - customer_name_snapshot=source.customer_name_snapshot, - customer_short_code_snapshot=source.customer_short_code_snapshot, - candidates_json=copy.deepcopy(source.candidates_json or []), - resolution_method=source.resolution_method or 'review_case_inherited', - confirmation_reason=source.confirmation_reason, - confirmed_by_id=source.confirmed_by_id, - confirmed_at=source.confirmed_at or datetime.utcnow(), - )) def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]: @@ -729,6 +661,59 @@ def _audit_idempotent_confirmation_replay( ) +def _inherit_confirmed_customer_resolution_onto_candidate( + candidate: ShippingOrderCandidate, + case: ShippingOrderReviewCase, +) -> None: + """review_case 人工确认时,把源机器 Candidate 的正式客户确认事实挂到新确认候选上。 + + review_case 确认会新建独立 ShippingOrderCandidate(candidate_key=review-confirm-*), + 但客户识别结果按 Candidate 关联稳定存放;新候选若不继承源候选的 confirmed resolution, + 后续 assert_customer_confirmed_before_task_create / resolve_confirmed_customer_id 按 + 新 candidate_id 查表为空,会误拒"已确认客户"无法建单。 + """ + if not case.candidate_id: + return + source = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + source_resolution = resolution_for_task(source) if source is not None else None + if ( + source_resolution is None + or source_resolution.status != 'confirmed' + or source_resolution.confirmed_customer_id is None + ): + return + from app.models import ShippingCustomerShadowResolution + + row = db.session.query(ShippingCustomerShadowResolution).filter_by( + candidate_id=int(candidate.id), + ).one_or_none() + if row is None: + row = ShippingCustomerShadowResolution( + candidate_id=int(candidate.id), intake_id=int(candidate.intake_id), + ) + db.session.add(row) + row.identity_rule_set_id = source_resolution.identity_rule_set_id + row.identity_rule_set_version = source_resolution.identity_rule_set_version + row.identity_rule_set_checksum = source_resolution.identity_rule_set_checksum + row.order_schema_version_id = source_resolution.order_schema_version_id + row.resolution_version = source_resolution.resolution_version + row.status = 'confirmed' + # [STEP] 完整复制源候选的正式识别证据与候选匹配快照:review_case 确认的新候选 + # 必须携带可审计的客户识别事实,否则 freeze(_confirmed_ordering_customer 要求 + # evidence_json 非空)会把"已确认客户"误判为未确认而冻结失败。 + row.evidence_json = list(source_resolution.evidence_json or []) + row.candidate_matches_json = list(source_resolution.candidate_matches_json or []) + row.resolution_context_json = dict(source_resolution.resolution_context_json or {}) + row.confirmed_customer_id = source_resolution.confirmed_customer_id + row.confirmation_method = source_resolution.confirmation_method or 'review_case_confirmed' + row.confirmed_by_id = int(candidate.accepted_by_id) if candidate.accepted_by_id is not None else None + row.confirmed_at = datetime.utcnow() + row.top_customer_id = source_resolution.top_customer_id + row.top_score = source_resolution.top_score + + def _create_review_candidate( *, case: ShippingOrderReviewCase, @@ -786,6 +771,11 @@ def _create_review_candidate( ) db.session.add(candidate) db.session.flush() + # [STEP] review_case 人工确认:把继承的正式客户确认事实落到 resolution 表, + # 否则按新 candidate_id 查表为空,assert_customer_confirmed_before_task_create / + # resolve_confirmed_customer_id 会误拒"已确认客户"无法建单。 + if customer_confirmed: + _inherit_confirmed_customer_resolution_onto_candidate(candidate, case) asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None # [STEP] 同 Case 既有波次不参与 Candidate 级 exact_file / 指纹阻断。 prior_wave_task_ids = _prior_wave_task_ids_for_case(case) @@ -872,8 +862,8 @@ def _prior_wave_task_ids_for_case(case: ShippingOrderReviewCase) -> set[int]: def _persist_wave_lines_for_task( *, case: ShippingOrderReviewCase, - task: ShippingNotice, - line_keys: list[str], + task: ShippingOrderTask, + snapshot_line_ids: list[int], wave_no: int, revision_id: int | None, ) -> None: @@ -882,8 +872,8 @@ def _persist_wave_lines_for_task( Args: case: 复核 Case。 - task: 本波次新建的 Notice。 - line_keys: 本波次完整行键。 + task: 本波次复核确认生成的 OT。 + snapshot_line_ids: 本波次冻结订单行 ID。 wave_no: 波次序号(从 1 起)。 revision_id: 可选确认修订 ID。 @@ -892,10 +882,10 @@ def _persist_wave_lines_for_task( """ from sqlalchemy.exc import IntegrityError - for key in line_keys: + for snapshot_line_id in snapshot_line_ids: db.session.add(ShippingOrderReviewWaveLine( review_case_id=int(case.id), - line_key=str(key), + snapshot_line_id=int(snapshot_line_id), task_id=int(task.id), wave_no=int(wave_no), confirmed_revision_id=int(revision_id) if revision_id is not None else None, @@ -906,31 +896,20 @@ def _persist_wave_lines_for_task( raise ConflictError( 'Line already belongs to another fulfillment wave', code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_keys': list(line_keys)}, + details={'snapshot_line_ids': [int(item) for item in snapshot_line_ids]}, ) from exc -def _order_task_no_for_notice(notice: ShippingNotice | None) -> str | None: - """ - 从已建 Notice 解析挂接的 OT 编号(幂等回放用)。 +def _order_task_no_for_notice(notice: ShippingOrderTask | None) -> str | None: + """返回 OT 自身编号(保留函数名仅用于本模块内部整理)。 Args: - notice: 发货 Notice;None 时返回 None。 + notice: OT;None 时返回 None。 Returns: order_task.task_no;未挂接时 None。 """ - if notice is None: - return None - order_task_id = getattr(notice, 'order_task_id', None) - if order_task_id is None: - return None - from app.models import ShippingOrderTask - - order_task = db.session.get(ShippingOrderTask, int(order_task_id)) - if order_task is None: - return None - return str(order_task.task_no or '').strip() or None + return str(getattr(notice, 'task_no', None) or '').strip() or None if notice is not None else None def _confirmation_result_payload( @@ -958,7 +937,7 @@ def _confirmation_result_payload( """ payload: dict[str, Any] = { 'task_no': task_no, - 'shipping_notice_no': task_no, + 'shipping_notice_no': None, 'order_task_no': order_task_no, 'idempotent_replay': idempotent_replay, 'case': serialize_review_case(case), @@ -969,7 +948,7 @@ def _confirmation_result_payload( return payload -def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None, line_keys: list[str] | None = None) -> dict[str, Any]: +def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None) -> dict[str, Any]: """ 确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。 @@ -979,7 +958,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A 幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。 版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。 锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。 - 可选 line_keys:仅冻结选中的完整明细行(履约波次);若 Case 仍有开放行则保持 ready 不终态确认。 + 确认订单恒为整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。 Args: user_id: Case 属主用户 ID。 @@ -988,7 +967,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotency_key: 建单幂等键。 warning_acknowledgements: 警告确认列表。 confirm_note: 可选确认备注,写入审计 metadata。 - line_keys: 可选履约波次行键;None 表示整单草稿行。 Returns: 含 shipping_notice_no / task_no / order_task_no / case / workflow_id / trigger_auto_progress 的确认结果。 @@ -1028,7 +1006,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ), idempotency_key=key, ) - task = db.session.get(ShippingNotice, int(replay.task_id)) + task = db.session.get(ShippingOrderTask, int(replay.task_id)) task_no = task.task_no if task else None _audit_idempotent_confirmation_replay( user_id=user_id, @@ -1044,9 +1022,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotent_replay=True, ) case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key) - # 整单已终态确认时幂等回放;履约波次在 Case 仍为 ready 时可继续建后续 Task。 - if case.status == 'confirmed' and case.confirmed_task_id and not line_keys: - task = db.session.get(ShippingNotice, int(case.confirmed_task_id)) + # 整单已终态确认时幂等回放(确认订单恒为整单,不存在按行波次的中间态)。 + if case.status == 'confirmed' and case.confirmed_task_id: + task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) task_no = task.task_no if task else None _audit_idempotent_confirmation_replay( user_id=user_id, @@ -1073,76 +1051,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotency_key=key, metadata={'expected_draft_version': expected}, ) - wave_keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] or None - # [STEP] 波次行唯一归属:在建 Task 前 fail-closed,避免 IntegrityError 半成品。 - if wave_keys is not None: - already = ( - ShippingOrderReviewWaveLine.query - .filter( - ShippingOrderReviewWaveLine.review_case_id == int(case.id), - ShippingOrderReviewWaveLine.line_key.in_(list(wave_keys)), - ) - .all() - ) - if already: - _reject_confirmation( - case, - actor_id=int(user_id), - error=ConflictError( - 'Line already belongs to another fulfillment wave', - code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_keys': [str(row.line_key) for row in already]}, - ), - idempotency_key=key, - case_no=str(case_no), - owner_user_id=int(user_id), - ) - summary, validation = build_confirmable_draft_summary(case, line_keys=wave_keys) - # [STEP] 建单硬门禁:库存源未唯一确定时禁止创建正式订单,并回写 OT stage。 - if ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE: - inventory_issues = [ - item - for item in (validation.get('issues') or []) - if isinstance(item, dict) - and str(item.get('owning_gate_code') or '') == 'inventory_source_routing' - and str(item.get('severity') or '') == 'blocking' - ] - if inventory_issues: - from app.services.shipping_notice.order_task_service import ( - resolve_order_task_for_candidate, - sync_order_task_processing_state, - ) - - blocked_ot = resolve_order_task_for_candidate( - int(case.candidate_id) if case.candidate_id else None - ) - if blocked_ot is not None: - sync_order_task_processing_state( - blocked_ot, - stage='inventory_source_resolving', - status='blocked', - ) - primary = inventory_issues[0] - _reject_confirmation( - case, - actor_id=int(user_id), - error=ConflictError( - 'Inventory source must be uniquely resolved before creating a formal order', - code='SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED', - details={ - 'issues': inventory_issues, - 'blocking_reason_code': str( - primary.get('code') or 'no_inventory_source_candidates' - ), - 'owning_gate_code': 'inventory_source_routing', - }, - ), - idempotency_key=key, - metadata={ - 'validation_status': str(validation.get('status') or '')[:32] or None, - 'gate_code': 'inventory_source_routing', - }, - ) + # [STEP] 确认订单恒为整单:build_confirmable_draft_summary 不接受 draft_line_ids, + # 确认时要求整单全部行通过校验(业务规则:确认订单不可分行)。 + summary, validation = build_confirmable_draft_summary(case) + # [STEP] 硬门禁已移除:确认流程只确认订单信息(订单字段/客户/订单快照)。 + # 库存源候选的裁决/冻结由确认后 OT 进入的正式 inventory_source_routing Gate 负责, + # 不再要求确认时库存源已唯一确定。 if draft_has_unaccepted_llm_suggestions(case): _reject_confirmation( case, @@ -1204,7 +1118,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A before_snap = {'status': previous_status, 'disposition': previous_disposition} # [BE-01/BE-02] 人工 Candidate 物化前锁定 Case 原 Candidate 对应 OT,禁止事后落到 Run 根号。 from app.services.shipping_notice.order_task_service import ( - link_notice_to_order_task, replace_order_task_candidate_after_review, resolve_order_task_for_candidate, upsert_order_task_from_run, @@ -1230,17 +1143,19 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) try: assert_case_is_current_workflow_version(case=case) - # [STEP] 建单前再次校验客户确认(相对 Draft 校验时刻防并发回退)。 + # [STEP] 建单前解析唯一客户(读机器候选 resolution,一次完成门户校验 + 取主键)。 + # 机器候选是客户识别事实的权威来源:没有唯一已确认主键即拒绝建单。 from app.services.shipping_notice.candidate_qualification_service import ( recalculate_candidate_qualification, - resolve_review_case_customer_resolved, + resolve_confirmed_customer_id, ) pre_candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None ) - if not resolve_review_case_customer_resolved(case=case, candidate=pre_candidate): + bind_customer_id = resolve_confirmed_customer_id(candidate=pre_candidate) + if bind_customer_id is None: raise ConflictError( 'Customer is not confirmed', code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED', @@ -1287,7 +1202,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。 try: - if locked_order_task is not None and locked_order_task.shipping_notice_id is None: + if locked_order_task is not None: order_task = replace_order_task_candidate_after_review( order_task=locked_order_task, previous_candidate_id=source_candidate_id, @@ -1356,69 +1271,34 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。 try: - task = ShippingNotice( - task_no=generate_task_no(), user_id=int(user_id), - conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename, - source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash, - source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id), - business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version, - content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version, - document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text, - customer_resolution_status='pending', current_order_extraction_id=int(extraction.id), - ) + task = order_task + task.current_order_extraction_id = int(extraction.id) + task.order_data_version = int(getattr(task, 'order_data_version', None) or 1) db.session.add(task) db.session.flush() - link_notice_to_order_task( - order_task_no=order_task_no, - notice_id=int(task.id), - ) extraction.task_id = int(task.id) candidate.consumed_task_id = int(task.id) candidate.updated_at = datetime.utcnow() # The review Case is the explicit human confirmation for this PDF. Do not - # recreate a low-confidence parse checkpoint on the newly materialized Task. - apply_task_transition(task, TaskTransition.CONFIRM_PARSE) - # [STEP] 冻结建单资格中的行级库存源候选;单源 resolved,多源 candidates_frozen。 - from app.services.shipping_notice.stp_inventory_freeze import freeze_stp_inventory_candidates_on_task - - freeze_stp_inventory_candidates_on_task( - task, - line_projections=list(validation.get('line_projections') or []), - ) - # [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存, - # 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。 - from app.services.shipping_notice.order_task_service import sync_order_task_processing_state - - sync_order_task_processing_state( - order_task, - stage='inventory_fetching', - status='processing', - reason_code='inventory_candidates_frozen_after_confirm', - ) - # [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。 - from app.services.shipping_notice.candidate_qualification_service import ( - resolve_confirmed_bill_to_customer_id, - ) - from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer + # recreate a low-confidence parse_review disposition on the newly materialized Task. + # [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结 + # 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内 + # 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。 + # [STEP] 建单前已从机器候选解析唯一客户主键(bind_customer_id,见上方门禁)。 + # 此处直接用该主键绑定标准客户,禁止落入 customer_review,不再二次查表。 from app.services.shipping_notice.customer_identity_gate import confirm_task_customer - bind_customer_id = resolve_confirmed_bill_to_customer_id( - candidate=candidate, - extraction_id=int(extraction.id), + confirm_task_customer( + task, + customer_id=int(bind_customer_id), + actor_id=int(user_id), + resolution_method='review_case_confirmed', + commit=False, ) - if bind_customer_id is not None: - confirm_task_customer( - task, - customer_id=int(bind_customer_id), - actor_id=int(user_id), - resolution_method='review_case_confirmed', - commit=False, - ) - else: - try_auto_confirm_task_customer(task) # [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。 # 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。 from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + from app.models import ShippingOrderSnapshot freeze_order_snapshot( task, @@ -1426,6 +1306,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A expected_order_data_version=int(task.order_data_version or 1), freeze_mode='manual', ) + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if snapshot is None: + raise ConflictError( + 'Confirmed order snapshot is required for wave assignment', + code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING', + ) except AppError as err: _reject_confirmation( case, @@ -1435,14 +1321,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A before=before_snap, needs_rollback=True, ) + # [STEP] 确认订单只做整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。 + # 因此 revision 记录整单草稿行,不按 draft_line_ids 过滤。 revision_lines = copy.deepcopy(case.current_draft.lines_json or []) - if wave_keys is not None: - wanted = set(wave_keys) - revision_lines = [ - item for idx, item in enumerate(revision_lines) - if isinstance(item, dict) - and (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') in wanted - ] revision = ShippingOrderReviewConfirmedRevision( case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version), schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}), @@ -1451,12 +1332,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) db.session.add(revision) db.session.flush() - # [STEP] 行级唯一归属:本波次(或整单)行写入不可变 wave_lines,防并发重复入波次。 - wave_line_keys = list(wave_keys) if wave_keys is not None else [ - (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') - for idx, item in enumerate(case.current_draft.lines_json or []) - if isinstance(item, dict) - ] + # [STEP] 行级归属记录:确认订单整单写入 snapshot 全部行(防并发重复入波次)。 + wave_line_ids = [int(line.id) for line in snapshot.lines] from sqlalchemy import func max_wave = ( @@ -1469,7 +1346,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A _persist_wave_lines_for_task( case=case, task=task, - line_keys=wave_line_keys, + snapshot_line_ids=wave_line_ids, wave_no=next_wave_no, revision_id=int(revision.id), ) @@ -1484,47 +1361,14 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A case_no=str(case_no), owner_user_id=int(user_id), ) - # [STEP] 履约波次:若仍有未入 Task/未关闭的草稿行,Case 保持 ready 以支持后续波次。 - has_remaining_open = False - if wave_keys is not None: - from app.services.shipping_notice.order_review_fulfillment_decision_service import ( - project_review_case_line_decisions, - ) - terminal = {'task_created', 'fulfilled', 'closed_unfulfillable'} - projected = project_review_case_line_decisions(case) - draft_all_keys = { - (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') - for idx, item in enumerate(case.current_draft.lines_json or []) - if isinstance(item, dict) - } - assigned = { - str(row.line_key) - for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all() - } - for key in draft_all_keys: - if key in assigned: - continue - matched = next( - (item for item in (projected.get('lines') or []) if str(item.get('line_key') or '') == key), - None, - ) - # 未入波次且未关闭的行保留 Case 可继续确认。 - if matched is None or matched.get('line_status') not in terminal: - has_remaining_open = True - break - if has_remaining_open: - case.status = 'ready' - case.confirmed_task_id = int(task.id) - # 保留首次确认时间;首波未终态时写入当前时间供追溯。 - if case.confirmed_at is None: - case.confirmed_at = datetime.utcnow() - else: - case.status = 'confirmed' - case.confirmed_task_id = int(task.id) - case.confirmed_at = datetime.utcnow() - # [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。 - from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed - mark_review_stream_confirmed(case=case) + # [STEP] 确认订单恒为整单终态确认(业务规则:确认订单不可分行,整单全过才确认)。 + # 不再有“仍有开放行则保持 ready 支持后续波次”的中间态。 + case.status = 'confirmed' + case.confirmed_task_id = int(task.id) + case.confirmed_at = datetime.utcnow() + # [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。 + from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed + mark_review_stream_confirmed(case=case) db.session.add(ShippingOrderReviewCaseEvent( case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version), actor_user_id=int(user_id), operation_json={ @@ -1532,8 +1376,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A 'idempotency_key': key, 'warning_acknowledgements': acknowledgements, 'confirm_note': str(confirm_note or '').strip()[:1024] or None, - 'line_keys': wave_keys, - 'partial_wave': bool(has_remaining_open), }, )) # Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。 @@ -1576,7 +1418,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) -def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: +def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bool: """ 判断确认建单后的任务是否仍需自动推进。 @@ -1593,16 +1435,18 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: return False if not getattr(task, 'current_order_extraction_id', None): return False - inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None) - inventory_lines = getattr(task, 'inventory_lines_json', None) - match_status = getattr(task, 'match_status', None) - export_file_path = getattr(task, 'export_file_path', None) - upload_status = getattr(task, 'upload_status', None) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + export_file_path = getattr(latest_export_artifact(task), 'file_path', None) + upload_status = getattr(latest_upload_attempt(task), 'status', None) # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 - has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool) - has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) - has_match = isinstance(match_status, str) and bool(match_status.strip()) + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_for_task, + has_ready_inventory_file_for_task, + ) + + has_inventory = has_ready_inventory_file_for_task(task) + has_match = bool(current_inventory_matches_for_task(task)) has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) has_upload = isinstance(upload_status, str) and bool(upload_status.strip()) return not (has_inventory or has_match or has_export or has_upload) @@ -1661,7 +1505,7 @@ def schedule_auto_progress_after_review_confirm( if not normalized: return None - task = db.session.query(ShippingNotice).filter(ShippingNotice.task_no == normalized).first() + task = db.session.query(ShippingOrderTask).filter(ShippingOrderTask.task_no == normalized).first() # [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。 if not _task_needs_post_confirm_auto_progress(task): return None diff --git a/backend/app/services/shipping_notice/order_review_customer_service.py b/backend/app/services/shipping_notice/order_review_customer_service.py index 3ccdc1c6..b832f703 100644 --- a/backend/app/services/shipping_notice/order_review_customer_service.py +++ b/backend/app/services/shipping_notice/order_review_customer_service.py @@ -2,8 +2,8 @@ services/shipping_notice/order_review_customer_service.py 用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。 -依赖:order_review_draft_service、order_customer_matching、candidate_qualification_service、 - ShippingOrderReviewCase / ShippingOrderCustomerMatch。 +依赖:order_review_draft_service、candidate_qualification_service、客户识别结果服务、 + ShippingOrderReviewCase / ShippingCustomerShadowResolution。 逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格; 不创建 Task、不重新解析 PDF。 """ @@ -17,18 +17,13 @@ from app.core.errors import ConflictError, NotFoundError from app.models import ( ShippingOrderCandidate, ShippingCustomerShadowResolution, - ShippingOrderCustomerMatch, ShippingOrderExtraction, ShippingOrderReviewCase, ) from app.services.shipping_notice.candidate_qualification_service import ( resolve_review_case_customer_resolved, ) -from app.services.shipping_notice.order_customer_matching import ( - confirm_order_customer_match, - refresh_order_customer_matches, - serialize_order_customer_match, -) +from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) @@ -78,42 +73,6 @@ def _resolve_extraction_for_case(case: ShippingOrderReviewCase) -> ShippingOrder ) -def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]: - """从 Draft / Candidate 业务摘要投影客户匹配所需的头字段。""" - header: dict[str, Any] = {} - draft = case.current_draft - if draft is not None and isinstance(draft.header_values_json, dict): - # Draft 以 field_id 存值;客户匹配需要 bill_to_* 业务码,尽量从 Candidate 摘要补齐。 - for key, value in draft.header_values_json.items(): - if isinstance(key, str) and value is not None: - header[str(key)] = value - candidate = ( - db.session.get(ShippingOrderCandidate, int(case.candidate_id)) - if case.candidate_id - else None - ) - structured = candidate.structured_result_json if candidate is not None else None - summary = ( - structured.get('business_summary') - if isinstance(structured, dict) and isinstance(structured.get('business_summary'), dict) - else {} - ) - for key in ( - 'bill_to_customer', - 'bill_to_customer_code', - 'bill_to_source_system', - 'ship_to_customer', - 'ship_to_code', - 'ship_to_source_system', - 'customer_name', - ): - if key not in header and summary.get(key) is not None: - header[key] = summary.get(key) - if 'bill_to_customer' not in header and header.get('customer_name'): - header['bill_to_customer'] = header.get('customer_name') - return header - - def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。 @@ -138,25 +97,16 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di if candidate is not None else None ) - match = None - if extraction is not None: - match = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(extraction.id), - role='bill_to', - ).first() - match_payload = serialize_order_customer_match(match) if match is not None else None shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else [] top_shadow = shadow_matches[0] if shadow_matches else {} status = 'confirmed' if resolved else str( (shadow.status if shadow is not None else None) - or (match_payload or {}).get('status') or 'unmatched' ) - # [STEP 1] 客户识别展示以已发布规则集生成的指纹候选为准;旧 CustomerMatch 仅作为确认状态兼容投影。 - display_match = match_payload or {} + # [STEP 1] 客户识别展示和确认均以已发布规则集生成的证据快照为准。 + display_match: dict[str, Any] = {} if top_shadow: display_match = { - **display_match, 'customer_id': top_shadow.get('customer_id'), 'standard_name': top_shadow.get('standard_name'), 'short_code': top_shadow.get('short_code'), @@ -216,7 +166,7 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di 'role': 'customer', 'extraction_id': int(extraction.id) if extraction is not None else None, 'raw_name': None, - 'customer_id': display_match.get('customer_id'), + 'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'), 'standard_name': display_match.get('standard_name'), 'short_code': display_match.get('short_code'), 'candidates': list(display_match.get('candidates') or []), @@ -236,7 +186,7 @@ def confirm_review_case_customer( """ 在复核工作台确认标准客户,并刷新建单资格。 - 核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。 + 核心逻辑:确认正式客户识别结果 → 统一协调器推进 → 返回最新 Case。 """ from app.services.shipping_notice.order_review_auto_progress_coordinator import ( reconcile_single_case_for_auto_progress, @@ -244,25 +194,15 @@ def confirm_review_case_customer( from app.services.shipping_notice.order_review_projection import serialize_review_case case = _load_writable_case(user_id=user_id, case_no=case_no) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - raise ConflictError( - 'Order extraction is required before confirming customer', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - # [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。 - if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None: - refresh_order_customer_matches(extraction, _header_from_case(case)) - # [STEP P1-8] confirm_order_customer_match 保留调用,传 commit=False 以便 - # 后续 reconcile(校验+STP 入队)在同一事务提交,保证变更与推进原子可见。 - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None + if candidate is None: + raise ConflictError('Candidate is required before confirming customer', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED') + confirm_customer_resolution( + candidate, customer_id=int(customer_id), - site_id=None, actor_id=int(user_id), + method='manual', reason=str(reason or '复核工作台人工确认标准客户').strip(), - commit=False, ) # [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+ # Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。 @@ -306,7 +246,7 @@ def retry_review_case_customer_resolution( case_no: str, ) -> dict[str, Any]: """ - 重新识别客户(不重解析 PDF):按当前 Draft/摘要刷新 CustomerMatch。 + 重新识别客户(不重解析 PDF):刷新规则驱动的客户识别快照。 【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。 """ @@ -316,13 +256,7 @@ def retry_review_case_customer_resolution( from app.services.shipping_notice.order_review_projection import serialize_review_case case = _load_writable_case(user_id=user_id, case_no=case_no) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - raise ConflictError( - 'Order extraction is required before retrying customer resolution', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - matches = refresh_order_customer_matches(extraction, _header_from_case(case)) + matches: list[dict[str, Any]] = [] if case.candidate_id: from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) @@ -334,16 +268,14 @@ def retry_review_case_customer_resolution( and shadow.top_customer_id and not resolve_review_case_customer_resolved(case=case, candidate=candidate) ): - # [STEP P1-8] 传 commit=False,保证与后续 reconcile 同事务提交。 - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + confirm_customer_resolution( + candidate, customer_id=int(shadow.top_customer_id), - site_id=None, actor_id=None, + method='auto_rule', reason='客户识别指纹唯一命中自动确认', - commit=False, ) + matches = list(shadow.candidate_matches_json or []) # [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed # 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。 reconcile_result = reconcile_single_case_for_auto_progress( diff --git a/backend/app/services/shipping_notice/order_review_disposition_service.py b/backend/app/services/shipping_notice/order_review_disposition_service.py index 8bc567fa..e3e5f3a5 100644 --- a/backend/app/services/shipping_notice/order_review_disposition_service.py +++ b/backend/app/services/shipping_notice/order_review_disposition_service.py @@ -1074,6 +1074,11 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo 因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用 客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。 + 终态闭环不变式:后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream, + 或旧版 Case 已恢复为可编辑状态。绝不允许旧 Case 停留在 ``reparse_pending`` + 而新版被孤儿化:该状态下工作台会永久卡在历史版本,且任何 API 都无法再次 + 触达新版或重新发起重识别。 + Args: run: 已到终态的重解析后继 Run。 succeeded: 新版 Run 是否成功到达可复核终态。 @@ -1095,21 +1100,24 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo ).with_for_update().first() ) if source_case is None or source_case.status != 'reparse_pending': + # 并发分支已裁决(被另一失败后继恢复、或已确认走另一分支): + # Stream 现状即权威,此处回改只会制造第二真相源。 return - if succeeded: - replacement_case = ShippingOrderReviewCase.query.filter_by( + replacement_case = ( + ShippingOrderReviewCase.query.filter_by( run_id=int(run.id), document_id=document_id, ).with_for_update().first() - if replacement_case is None: - # Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 - return + if succeeded + else None + ) + if replacement_case is not None: from app.services.shipping_notice.review_stream_service import activate_review_case stream = activate_review_case( case=replacement_case, trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', ) - # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或 - # 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。 + # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进并宣告成功; + # 激活被并发确认或晚到分支拒绝时,禁止记录 succeeded 审计(与事实不符)。 if int(stream.current_case_id or 0) == int(replacement_case.id): from app.services.shipping_notice.order_review_auto_progress_coordinator import ( reconcile_single_case_for_auto_progress, @@ -1119,11 +1127,17 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo trigger='document_reparse_succeeded', refresh_validation=True, ) - _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ - 'successor_run_no': run.run_no, - 'replacement_case_no': replacement_case.case_no, - }) - return + _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ + 'successor_run_no': run.run_no, + 'replacement_case_no': replacement_case.case_no, + }) + return + finalize_failure_reason = 'stream_activation_rejected' + else: + finalize_failure_reason = 'replacement_case_missing' + # [C1] 终态闭环:成功终态但新版 Case 缺失、或激活被拒绝时,禁止静默返回 —— + # 否则旧 Case 永久停留在 reparse_pending(编辑/确认全被禁且无法再触发重识别), + # 工作台只能卡在历史版本。转入既有失败恢复链把旧 Case 恢复为可编辑状态。 previous = 'quality_issue' event = ShippingOrderReviewCaseEvent.query.filter( ShippingOrderReviewCaseEvent.case_id == int(source_case.id), @@ -1136,6 +1150,7 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo source_case.status = previous _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={ 'successor_run_no': run.run_no, 'restored_status': previous, + 'failure_reason': finalize_failure_reason, }) from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore mark_reparse_failed_and_restore( diff --git a/backend/app/services/shipping_notice/order_review_draft_service.py b/backend/app/services/shipping_notice/order_review_draft_service.py index f98455a8..d0893cec 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -10,7 +10,7 @@ services/shipping_notice/order_review_draft_service.py 追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流; Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计; 整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格; - 履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation; + 履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation; 库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定; 路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放; 显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。 @@ -47,7 +47,6 @@ from app.services.shipping_notice.order_build_eligibility_service import ( from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_schema.field_rules import ( - is_valid_line_no_value, normalize_order_field_value, validate_order_field_value, ) @@ -335,21 +334,21 @@ def _machine_value(machine_fields: list[Any], field_id: str) -> Any: def _find_line( case: ShippingOrderReviewCase, lines: list[dict[str, Any]], - line_key: str, + draft_line_id: str, *, actor_id: int, action: str, ) -> dict[str, Any]: - """按稳定 line_key 获取草稿行;不存在时写拒绝审计。""" + """按稳定 draft_line_id 获取草稿行;不存在时写拒绝审计。""" for item in lines: - if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''): + if isinstance(item, dict) and str(item.get('draft_line_id') or '') == str(draft_line_id or ''): return item _reject_draft_operation( case, actor_id=actor_id, action=action, error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), - metadata={'line_key': str(line_key or '')[:64] or None}, + metadata={'draft_line_id': str(draft_line_id or '')[:128] or None}, ) @@ -400,14 +399,6 @@ def draft_has_unaccepted_llm_suggestions(case: ShippingOrderReviewCase) -> bool: return False -LINE_NO_OVERRIDE_REASON_CODES = frozenset({ - 'recognition_error', - 'customer_line_exception', - 'business_correction', - 'other', -}) - - def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]: """写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。""" values = dict(container.get('values') or {}) @@ -476,9 +467,9 @@ def _validation( line[str(field.get('field_code') or field_id)] = value normalized = normalize_order_field_value(value, field) if field.get('required') and normalized in (None, ''): - issues.append({'code': 'required_field_missing', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) + issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'}) elif normalized is not None and not validate_order_field_value(normalized, field): - issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) + issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'}) lines.append(line) line_metas.append(raw_line) @@ -512,8 +503,13 @@ def _validation( if isinstance(item, dict): issues.append(dict(item)) # 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。 + # 库存源路由属于确认后由正式 inventory_source_routing Gate 处理的事实, + # 这里不得把 inventory_source_routing 的 blocking 项重新纳入(eligibility.can_build 已排除), + # 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。 can_build = bool(eligibility.get('can_build')) and not any( - str(item.get('severity') or '') == 'blocking' for item in issues + str(item.get('severity') or '') == 'blocking' + and str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + for item in issues ) # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 enriched_issues: list[dict[str, Any]] = [] @@ -563,14 +559,14 @@ def _validation( def build_confirmable_draft_summary( case: ShippingOrderReviewCase, *, - line_keys: list[str] | None = None, + draft_line_ids: list[str] | None = None, ) -> tuple[dict[str, Any], dict[str, Any]]: """ 从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。 Args: case: 复核 Case。 - line_keys: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。 + draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。 Returns: (summary, validation) 元组。 @@ -583,17 +579,17 @@ def build_confirmable_draft_summary( if str(field.get('scope') or '') == 'header' } raw_lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)] - if line_keys is not None: - wanted = {str(k).strip() for k in line_keys if str(k).strip()} + if draft_line_ids is not None: + wanted = {str(k).strip() for k in draft_line_ids if str(k).strip()} filtered: list[dict[str, Any]] = [] for idx, raw_line in enumerate(raw_lines): - key = str(raw_line.get('line_key') or '').strip() or f'line-{idx + 1}' + key = str(raw_line.get('draft_line_id') or '').strip() if key in wanted: filtered.append(raw_line) if len(filtered) != len(wanted): from app.core.errors import ValidationError raise ValidationError( - 'One or more line_keys not found in draft', + 'One or more draft_line_ids not found in draft', code='SHIPPING.REVIEW_LINE_NOT_FOUND', ) raw_lines = filtered @@ -605,11 +601,11 @@ def build_confirmable_draft_summary( } for raw_line in raw_lines ] - # 波次建单时保留草稿行键,供血缘与决定回写对齐。 + # 波次建单时保留草稿行身份,供血缘与决定回写对齐。 for idx, raw_line in enumerate(raw_lines): - key = str(raw_line.get('line_key') or '').strip() + key = str(raw_line.get('draft_line_id') or '').strip() if key and idx < len(lines): - lines[idx]['line_key'] = key + lines[idx]['draft_line_id'] = key # [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。 validation = _validation(case, raw_lines=raw_lines) return {**header, 'lines': lines}, validation @@ -719,11 +715,11 @@ def _record_change( operation_json=operation, )) changed_paths = [ - key for key in ('field_id', 'line_key', 'action') + key for key in ('field_id', 'draft_line_id', 'action') if key in operation and operation.get(key) is not None ] field_id = operation.get('field_id') - line_key = operation.get('line_key') + draft_line_id = operation.get('draft_line_id') previous_value = _audit_scalar(operation.get('previous_value')) new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value')) value_source = str(operation.get('source') or '')[:32] or None @@ -751,9 +747,9 @@ def _record_change( after_snapshot['new_value'] = new_value if value_source: after_snapshot['value_source'] = value_source - if line_key is not None: - before_snapshot['line_key'] = str(line_key)[:64] - after_snapshot['line_key'] = str(line_key)[:64] + if draft_line_id is not None: + before_snapshot['draft_line_id'] = str(draft_line_id)[:128] + after_snapshot['draft_line_id'] = str(draft_line_id)[:128] # [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。 if str(event_type or '').startswith('inventory_routing_'): before_raw = operation.get('previous_value') @@ -797,8 +793,8 @@ def _record_change( after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64] if operation.get('idempotency_key'): after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128] - if operation.get('line_keys') is not None: - after_snapshot['line_keys'] = [str(item)[:64] for item in list(operation.get('line_keys') or [])[:50]] + if operation.get('draft_line_ids') is not None: + after_snapshot['draft_line_ids'] = [str(item)[:128] for item in list(operation.get('draft_line_ids') or [])[:50]] # 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。 audit_event_type = ( 'review_field_restored_machine' @@ -887,139 +883,31 @@ def patch_line_field( *, user_id: int, case_no: str, - line_key: str, + draft_line_id: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False, - override_reason_code: str | None = None, - override_reason_text: str | None = None, ) -> dict[str, Any]: """ - 编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。 + 编辑或恢复一条明细字段;行由不可变 draft_line_id 定位并受同一草稿版本锁保护。 - 核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 覆盖须原因分类并锁定; - 恢复时清除 override,回退到草稿 machine_fields 中的识别/派生投影(不重新跑派生引擎), - 并写 LINE_NO_RESTORED。 + 核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 是系统项次,禁止覆盖或恢复。 """ action = 'line_field_changed' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) field = _require_field(case, field_id, 'line', actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, field_id) field_code = str(field.get('field_code') or '') - if field_code == 'line_no' and restore_machine: - prior_entry = (target.get('values') or {}).get(field_id) if isinstance(target.get('values'), dict) else None - prior_source = str((prior_entry or {}).get('source') or 'manual_override') - change = _set_value(target, field, value, restore_machine=True) - # 恢复后的展示值来自 machine_fields:初始化草稿时已含识别/派生投影,非二次派生。 - restored_source = 'machine_or_derived_projection' - case.current_draft.lines_json = lines - result = _record_change( - case, - actor_id=user_id, - event_type=action, - operation={ - 'line_key': line_key, - 'field_id': field_id, - 'field_code': field_code, - 'previous_value': previous_value, - 'restored_source': restored_source, - 'prior_value_source': prior_source, - **change, - }, + if field_code == 'line_no': + raise ValidationError( + 'line_no is system-generated and cannot be edited or restored', + code='SHIPPING.REVIEW_LINE_NO_IMMUTABLE', ) - append_shipping_audit_event( - event_type='LINE_NO_RESTORED', - aggregate_type='shipping_order_review_case', - aggregate_id=str(case.case_no), - actor_type='user', - actor_id=user_id, - review_case_no=str(case.case_no), - action='restore_line_no', - result='success', - metadata={ - 'line_key': line_key, - 'field_code': 'line_no', - 'restored_source': restored_source, - 'prior_value_source': prior_source, - }, - before={'previous_value': previous_value, 'value_source': prior_source}, - after={'new_value': change.get('value'), 'value_source': restored_source}, - ) - return result - - if field_code == 'line_no' and not restore_machine: - reason_code = str(override_reason_code or '').strip() - reason_text = str(override_reason_text or '').strip() - if reason_code not in LINE_NO_OVERRIDE_REASON_CODES: - raise ValidationError( - 'line_no override requires a valid reason code', - code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_REASON_REQUIRED', - ) - if reason_code == 'other' and not reason_text: - raise ValidationError( - 'line_no override reason text is required for other', - code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_TEXT_REQUIRED', - ) - if not is_valid_line_no_value(value): - raise ValidationError( - 'line_no must be 1-6 digits', - code='SHIPPING.REVIEW_LINE_NO_FORMAT_INVALID', - ) - change = _set_value(target, field, value, restore_machine=False) - values = dict(target.get('values') or {}) - values[str(field['field_id'])] = { - 'value': change['value'], - 'source': 'manual_override', - 'locked': True, - 'override_reason_code': reason_code, - 'override_reason_text': reason_text or None, - } - target['values'] = values - change = { - **change, - 'source': 'manual_override', - 'override_reason_code': reason_code, - 'override_reason_text': reason_text or None, - 'locked': True, - } - case.current_draft.lines_json = lines - result = _record_change( - case, - actor_id=user_id, - event_type=action, - operation={ - 'line_key': line_key, - 'field_id': field_id, - 'field_code': field_code, - 'previous_value': previous_value, - **change, - }, - ) - append_shipping_audit_event( - event_type='LINE_NO_OVERRIDDEN', - aggregate_type='shipping_order_review_case', - aggregate_id=str(case.case_no), - actor_type='user', - actor_id=user_id, - review_case_no=str(case.case_no), - action='override_line_no', - result='success', - reason_code=reason_code, - reason=reason_text or None, - metadata={ - 'line_key': line_key, - 'field_code': 'line_no', - 'override_reason_code': reason_code, - }, - before={'previous_value': previous_value, 'value_source': 'prior'}, - after={'new_value': change['value'], 'value_source': 'manual_override'}, - ) - return result change = _set_value(target, field, value, restore_machine=restore_machine) case.current_draft.lines_json = lines @@ -1028,7 +916,7 @@ def patch_line_field( actor_id=user_id, event_type=action, operation={ - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change, @@ -1042,34 +930,34 @@ def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - line_key = f'manual-{uuid.uuid4().hex[:16]}' - lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}}) + draft_line_id = str(uuid.uuid4()) + lines.append({'draft_line_id': draft_line_id, 'machine_fields': [], 'values': {}}) case.current_draft.lines_json = lines - return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) + return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id}) -def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: - """复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。""" +def copy_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]: + """复制明细为新 draft_line_id;复制后的 Reservation 重复会由全量校验显式阻断。""" action = 'line_copied' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - copied = copy.deepcopy(_find_line(case, lines, line_key, actor_id=user_id, action=action)) - copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}' + copied = copy.deepcopy(_find_line(case, lines, draft_line_id, actor_id=user_id, action=action)) + copied['draft_line_id'] = str(uuid.uuid4()) lines.append(copied) case.current_draft.lines_json = lines - return _record_change(case, actor_id=user_id, event_type=action, operation={'source_line_key': line_key, 'line_key': copied['line_key']}) + return _record_change(case, actor_id=user_id, event_type=action, operation={'source_draft_line_id': draft_line_id, 'draft_line_id': copied['draft_line_id']}) -def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: +def delete_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]: """删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。""" action = 'line_deleted' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - _find_line(case, lines, line_key, actor_id=user_id, action=action) - case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)] - return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) + _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) + case.current_draft.lines_json = [item for item in lines if str(item.get('draft_line_id') or '') != str(draft_line_id)] + return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id}) def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]: @@ -1102,7 +990,7 @@ def _routing_idempotency_entry_key(*, action: str, idempotency_key: str) -> str: 生成幂等历史条目键(动作 + 幂等键)。 Args: - action: 路由恢复动作(可含 line_key 后缀)。 + action: 路由恢复动作(可含 draft_line_id 后缀)。 idempotency_key: 已规范化的幂等键。 Returns: @@ -1166,7 +1054,7 @@ def _store_routing_recovery_idempotency( *, action: str, idempotency_key: str, - line_keys: list[str], + draft_line_ids: list[str], ) -> None: """ 将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。 @@ -1184,7 +1072,7 @@ def _store_routing_recovery_idempotency( record = { 'idempotency_key': key, 'action': action, - 'line_keys': [str(item)[:64] for item in line_keys[:50]], + 'draft_line_ids': [str(item)[:128] for item in draft_line_ids[:50]], 'draft_version_after': int(draft.draft_version) + 1, } entries[entry_key] = record @@ -1214,7 +1102,7 @@ def _line_routing_snapshot(line: dict[str, Any], fields: dict[str, dict[str, Any line_meta=line, ) return { - 'line_key': str(line.get('line_key') or '')[:64], + 'draft_line_id': str(line.get('draft_line_id') or '')[:128], 'selection_mode': projection.get('selection_mode'), 'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []), 'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []), @@ -1243,7 +1131,7 @@ def reroute_inventory_routing( case_no: str, expected_draft_version: Any, idempotency_key: str | None = None, - line_key: str | None = None, + draft_line_id: str | None = None, ) -> dict[str, Any]: """ 按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。 @@ -1256,7 +1144,7 @@ def reroute_inventory_routing( case_no: 复核 Case 编号。 expected_draft_version: 乐观锁版本。 idempotency_key: 可选幂等键。 - line_key: 可选,仅重算指定行;缺省整单。 + draft_line_id: 可选,仅重算指定行;缺省整单。 Returns: 序列化后的 Case 详情。 @@ -1271,7 +1159,7 @@ def reroute_inventory_routing( fields = _schema_fields(case) header_by_code = _header_by_code_for_case(case, fields) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target_key = str(line_key or '').strip() + target_key = str(draft_line_id or '').strip() before_rows: list[dict[str, Any]] = [] after_rows: list[dict[str, Any]] = [] touched_keys: list[str] = [] @@ -1279,7 +1167,7 @@ def reroute_inventory_routing( for raw in lines: if not isinstance(raw, dict): continue - current_key = str(raw.get('line_key') or '').strip() + current_key = str(raw.get('draft_line_id') or '').strip() if target_key and current_key != target_key: continue if not current_key: @@ -1305,7 +1193,7 @@ def reroute_inventory_routing( actor_id=user_id, action=action, error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), - metadata={'line_key': target_key[:64]}, + metadata={'draft_line_id': target_key[:128]}, ) case.current_draft.lines_json = lines @@ -1313,15 +1201,15 @@ def reroute_inventory_routing( case, action=action, idempotency_key=str(idempotency_key or ''), - line_keys=touched_keys, + draft_line_ids=touched_keys, ) return _record_change( case, actor_id=user_id, event_type=action, operation={ - 'line_key': target_key or None, - 'line_keys': touched_keys, + 'draft_line_id': target_key or None, + 'draft_line_ids': touched_keys, 'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None, 'previous_value': before_rows[:20], 'new_value': after_rows[:20], @@ -1386,7 +1274,7 @@ def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any] return { 'field_code': field_code, 'line_index': conflict.get('line_index'), - 'line_key': conflict.get('line_key'), + 'draft_line_id': conflict.get('draft_line_id'), } return {} @@ -1462,7 +1350,7 @@ def _sync_review_gates_safe( default_reason_code='field_conflict', details={ **base_details, - 'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'), + 'draft_line_id': primary_conflict.get('draft_line_id') or conflict_locator.get('draft_line_id'), 'line_index': primary_conflict.get('line_index') if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'), 'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'), @@ -1496,7 +1384,7 @@ def _sync_review_gates_safe( ) or default_reason sync_details = { **base_details, - 'line_key': primary.get('line_key'), + 'draft_line_id': primary.get('draft_line_id'), 'line_index': primary.get('line_index'), 'field_code': primary.get('field_code'), 'issue_codes': [ @@ -1517,12 +1405,8 @@ def _sync_review_gates_safe( inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing') if not inventory_issues: - sync_inventory_routing_gate_for_case( - case=case, - passed=True, - actor_id=int(user_id), - details=base_details, - ) + # 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task; + # 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。 return primary = inventory_issues[0] @@ -1558,7 +1442,7 @@ def _sync_review_gates_safe( 'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)), 'raw_rule_source_codes': list(dict.fromkeys(raw_codes)), 'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)), - 'line_key': primary.get('line_key'), + 'draft_line_id': primary.get('draft_line_id'), 'line_index': primary.get('line_index'), 'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []), }, @@ -1599,7 +1483,7 @@ def apply_llm_suggestion_prefill( user_id: int, case_no: str, field_id: str, - line_key: str | None, + draft_line_id: str | None, value: Any, suggestion_no: str, expected_draft_version: Any, @@ -1613,7 +1497,7 @@ def apply_llm_suggestion_prefill( user_id: 操作人。 case_no: Case 编号。 field_id: 字段 ID。 - line_key: 行键;表头为 None。 + draft_line_id: 草稿行身份;表头为 None。 value: 建议值。 suggestion_no: 关联建议编号。 expected_draft_version: 乐观锁版本。 @@ -1627,13 +1511,13 @@ def apply_llm_suggestion_prefill( field = _require_field( case, field_id, - 'line' if line_key else 'header', + 'line' if draft_line_id else 'header', actor_id=user_id, action=action, ) - if line_key: + if draft_line_id: lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, field_id) change = _set_llm_suggested_value(target, field, value, suggestion_no=suggestion_no) case.current_draft.lines_json = lines @@ -1641,7 +1525,7 @@ def apply_llm_suggestion_prefill( case, actor_id=user_id, event_type=action, - operation={'line_key': line_key, 'field_id': field_id, 'previous_value': previous_value, **change}, + operation={'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change}, ) header = dict(case.current_draft.header_values_json or {}) previous_value = _current_value(header, field_id) @@ -1692,10 +1576,10 @@ def adjudicate_llm_suggestion_on_draft( actor_id=user_id, action=action, ) - line_key = suggestion.line_key - if line_key: + draft_line_id = suggestion.draft_line_id + if draft_line_id: lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, suggestion.field_id) if decision == 'reject': values = dict(target.get('values') or {}) @@ -1731,7 +1615,7 @@ def adjudicate_llm_suggestion_on_draft( actor_id=user_id, event_type=action, operation={ - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'field_id': suggestion.field_id, 'suggestion_no': suggestion.suggestion_no, 'previous_value': previous_value, diff --git a/backend/app/services/shipping_notice/order_review_evidence_selector.py b/backend/app/services/shipping_notice/order_review_evidence_selector.py index 82d83d57..86796bc5 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_selector.py +++ b/backend/app/services/shipping_notice/order_review_evidence_selector.py @@ -3,7 +3,7 @@ services/shipping_notice/order_review_evidence_selector.py 用途:为订单复核 AI 建议选择最小证据包(字段→单元格→表格→页面)。 依赖:Run 冻结 layout_snapshot / layout_schema_candidates。 -逻辑:默认不超过 L3;明细必须绑定 line_key/行号;禁止写入 secret、临时签名 URL、完整请求头。 +逻辑:默认不超过 L3;明细必须绑定 draft_line_id/行号;禁止写入 secret、临时签名 URL、完整请求头。 """ from __future__ import annotations @@ -42,7 +42,7 @@ def select_review_evidence_pack( Args: document: 冻结 Document 快照。 - target_fields: 待建议字段定位信息(须含 field_id;明细须含 line_key)。 + target_fields: 待建议字段定位信息(须含 field_id;明细须含 draft_line_id)。 evidence_level: L1–L4。 allow_full_pdf: 仅管理员显式 True 时允许 L4。 @@ -84,16 +84,16 @@ def select_review_evidence_pack( hit_table_ids: set[str] = set() hit_page_nos: set[int] = set() - # [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 line_key 过滤。 + # [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 draft_line_id 过滤。 for target in target_fields: if not isinstance(target, dict): continue field_id = str(target.get('field_id') or '') - line_key = str(target.get('line_key') or '').strip() or None + draft_line_id = str(target.get('draft_line_id') or '').strip() or None snippets = _field_snippets( candidates, field_id=field_id, - line_key=line_key, + draft_line_id=draft_line_id, line_number=target.get('line_number'), ) for snippet in snippets: @@ -107,7 +107,7 @@ def select_review_evidence_pack( 'field_id': field_id, 'field_code': target.get('field_code'), 'scope': target.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': target.get('line_number'), 'snippets': snippets[:8], }) @@ -157,11 +157,11 @@ def _field_snippets( candidates: list[dict[str, Any]], *, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, line_number: Any = None, ) -> list[dict[str, Any]]: """ - 收集目标 field_id 的短引文;明细行必须绑定 line_key / 行号。 + 收集目标 field_id 的短引文;明细行必须绑定 draft_line_id / 行号。 核心逻辑:header 字段可跨行收集;line 字段仅保留匹配目标行的 cell,禁止串行。 """ @@ -170,7 +170,7 @@ def _field_snippets( for row in candidate.get('rows') or []: if not isinstance(row, dict): continue - if not _row_matches_line(row, line_key=line_key, line_number=line_number): + if not _row_matches_line(row, draft_line_id=draft_line_id, line_number=line_number): continue for field in row.get('fields') or []: if not isinstance(field, dict) or str(field.get('field_id') or '') != field_id: @@ -181,7 +181,7 @@ def _field_snippets( 'page_no': int(candidate.get('page_no') or field.get('page_no') or 1), 'table_id': str(candidate.get('table_id') or field.get('table_id') or ''), 'row_index': int(row.get('row_index') or 0), - 'line_key': str(row.get('line_key') or line_key or '') or None, + 'draft_line_id': str(row.get('draft_line_id') or draft_line_id or '') or None, 'cell_id': str(field.get('cell_id') or '') or None, 'quote': quote[:500], }) @@ -191,17 +191,17 @@ def _field_snippets( def _row_matches_line( row: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, line_number: Any, ) -> bool: - """判断布局行是否对应目标明细;无 line_key 时视为表头字段(允许任意行)。""" - if not line_key and line_number is None: + """判断布局行是否对应目标明细;无 draft_line_id 时视为表头字段(允许任意行)。""" + if not draft_line_id and line_number is None: return True - row_line_key = str(row.get('line_key') or '').strip() - # [STEP] 行上已有 line_key 时只做精确匹配,禁止再按 row_index 宽松回退。 - if line_key and row_line_key: - return row_line_key == line_key - target_index = _line_key_to_index(line_key) + row_draft_line_id = str(row.get('draft_line_id') or '').strip() + # [STEP] 行上已有 draft_line_id 时只做精确匹配,禁止再按 row_index 宽松回退。 + if draft_line_id and row_draft_line_id: + return row_draft_line_id == draft_line_id + target_index = _draft_line_id_to_index(draft_line_id) if target_index is None and line_number is not None: try: target_index = int(line_number) @@ -216,16 +216,16 @@ def _row_matches_line( return int(data_position) == target_index except (TypeError, ValueError): return False - # 兼容仅有 1-based row_index 的布局行(无 line_key)。 + # 布局行没有草稿身份时,仅按显式行号定位。 row_index = int(row.get('row_index') or -1) return row_index == target_index + 1 -def _line_key_to_index(line_key: str | None) -> int | None: - """将 machine-N 行键转换为 0-based 行序号。""" - if not line_key: +def _draft_line_id_to_index(draft_line_id: str | None) -> int | None: + """将 machine-N 草稿行身份转换为 0-based 行序号。""" + if not draft_line_id: return None - matched = _MACHINE_LINE_KEY.match(str(line_key).strip()) + matched = _MACHINE_LINE_KEY.match(str(draft_line_id).strip()) if not matched: return None return max(int(matched.group(1)) - 1, 0) @@ -275,7 +275,7 @@ def _strip_forbidden(value: Any) -> Any: _FIELD_CORE_PRIORITY = ( 'field_id', 'value', 'quote', 'evidence_ref', 'field_code', - 'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source', + 'scope', 'draft_line_id', 'llm_context_policy', 'mask_rule', 'value_source', ) @@ -322,8 +322,8 @@ def _serialize_field_view( if not strip_secondary_for_token: out['field_code'] = fc out['scope'] = fv.get('scope') - if fv.get('line_key'): - out['line_key'] = fv.get('line_key') + if fv.get('draft_line_id'): + out['draft_line_id'] = fv.get('draft_line_id') out['value'] = sent_value out['value_source'] = fv.get('value_source') or 'missing_both' if masked.get('policy') == 'masked': @@ -457,20 +457,20 @@ def _build_v2_field_entry( ) -> tuple[dict[str, Any], bool, bool]: """ 返回 (field_entry, context_truncated, target_core_trimmed)。 - field_entry 包含:field_id/field_code/scope/line_key + snippets[] + row_fields[] + + field_entry 包含:field_id/field_code/scope/draft_line_id + snippets[] + row_fields[] + table_headers[] + neighbor_rows[] + page_text[]。 """ from app.services.shipping_notice.order_review_evidence_view import get_field_view field_id = str(target.get('field_id') or '') - line_key = str(target.get('line_key') or '').strip() or None - target_fv = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + draft_line_id = str(target.get('draft_line_id') or '').strip() or None + target_fv = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if target_fv is None: target_fv = { 'field_id': field_id, 'field_code': target.get('field_code') or field_id, 'scope': target.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'llm_context_policy': 'allowed', 'value_source': 'missing_both', 'field_evidences': [], @@ -481,7 +481,7 @@ def _build_v2_field_entry( 'field_id': field_id, 'field_code': target.get('field_code') or target_fv.get('field_code'), 'scope': target.get('scope') or target_fv.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'snippets': [], } # snippets:摊平所有 field_evidences 的 quote/value/evidence_ref @@ -511,11 +511,11 @@ def _build_v2_field_entry( # [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤) if level == 'L2_row': - line_fields_map = evidence_view.get('line_fields') or {} if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = evidence_view.get('line_fields') or {} if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] target_idx = 0 - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue @@ -580,9 +580,9 @@ def _build_v2_field_entry( rows = matched_table.get('rows') or [] ridx = int(row_index) if isinstance(row_index, int) else None if ridx is None: - # 没找到 row_index:用 line_key 反查 + # 没找到 row_index:用 draft_line_id 反查 for ri, r in enumerate(rows): - if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''): + if isinstance(r, dict) and str(r.get('draft_line_id') or '') == str(draft_line_id or ''): ridx = ri break if ridx is not None: @@ -607,15 +607,15 @@ def _build_v2_field_entry( }) neighbor_rows.append({ 'row_index': pos, - 'line_key': r.get('line_key'), + 'draft_line_id': r.get('draft_line_id'), 'cells': cell_values, }) # 同行字段(复用 L2 逻辑,减少字符预算) - line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] target_idx = 0 - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue @@ -674,10 +674,10 @@ def _build_v2_field_entry( entry['page_blocks'] = page_blocks entry['page_no'] = page_no_final # 行字段保留(最小) - line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue diff --git a/backend/app/services/shipping_notice/order_review_evidence_service.py b/backend/app/services/shipping_notice/order_review_evidence_service.py index 6a9899b8..728588d8 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_service.py +++ b/backend/app/services/shipping_notice/order_review_evidence_service.py @@ -529,7 +529,7 @@ def build_minimal_evidence_pack_for_field( case: ShippingOrderReviewCase, *, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, evidence_level: str = 'L1_field', allow_full_pdf: bool = False, ) -> dict[str, Any]: @@ -541,7 +541,7 @@ def build_minimal_evidence_pack_for_field( Args: case: 已加载 run 的 Review Case。 field_id: 目标 field_id。 - line_key: 明细行键。 + draft_line_id: 草稿明细行身份。 evidence_level: L1_field–L4_pdf。 allow_full_pdf: 管理员显式 L4。 @@ -559,7 +559,7 @@ def build_minimal_evidence_pack_for_field( if isinstance(item, dict) and int(item.get('document_id') or 0) == int(case.document_id): document = dict(item) break - field_meta = {'field_id': str(field_id), 'scope': 'line' if line_key else 'header', 'line_key': line_key} + field_meta = {'field_id': str(field_id), 'scope': 'line' if draft_line_id else 'header', 'draft_line_id': draft_line_id} return select_review_evidence_pack( document=document, target_fields=[field_meta], diff --git a/backend/app/services/shipping_notice/order_review_evidence_view.py b/backend/app/services/shipping_notice/order_review_evidence_view.py index e15d6671..17e6018d 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_view.py +++ b/backend/app/services/shipping_notice/order_review_evidence_view.py @@ -83,7 +83,7 @@ def _normalize_observation( case_document_id: int, case_id: int, field_code: str | None = None, - line_key: str | None = None, + draft_line_id: str | None = None, derived_row_index: int | None = None, ) -> dict[str, Any]: """ @@ -118,7 +118,7 @@ def _normalize_observation( provenance_ref: str | None = None if source == 'draft_observation' or source == 'text_fallback': provenance_ref = build_provenance_ref( - case_id=case_id, line_key=line_key, field_code=field_code or '', + case_id=case_id, draft_line_id=draft_line_id, field_code=field_code or '', ) confidence_raw = raw.get('confidence') @@ -221,23 +221,22 @@ def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, di def _iter_unit_line_fields( order_result: dict[str, Any], ) -> list[tuple[str, int, str, dict[str, Any]]]: - """返回 [(line_key, row_position, field_id, field_obj)]""" + """返回 [(draft_line_id, row_position, field_id, field_obj)]""" out: list[tuple[str, int, str, dict[str, Any]]] = [] lines = order_result.get('lines') or [] for pos, line in enumerate(lines): if not isinstance(line, dict): continue - line_key = _safe_str(line.get('line_key')) - if not line_key: - index_match = _MACHINE_LINE_KEY_RE.match(f'machine-{pos + 1}') - line_key = index_match.group(0) if index_match else f'machine-{pos + 1}' + draft_line_id = _safe_str(line.get('draft_line_id')) + if not draft_line_id: + draft_line_id = f'machine-{pos + 1}' for field_obj in line.get('fields') or []: if not isinstance(field_obj, dict): continue fid = _safe_str(field_obj.get('field_id')) if not fid: continue - out.append((line_key, pos, fid, field_obj)) + out.append((draft_line_id, pos, fid, field_obj)) return out @@ -254,9 +253,9 @@ def _draft_line_list(draft) -> list[dict[str, Any]]: return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)] -def _find_draft_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any] | None: +def _find_draft_line(lines: list[dict[str, Any]], draft_line_id: str) -> dict[str, Any] | None: for ln in lines: - if _safe_str(ln.get('line_key')) == line_key: + if _safe_str(ln.get('draft_line_id')) == draft_line_id: return ln return None @@ -301,8 +300,8 @@ def _frozen_document_snapshot(case) -> dict[str, Any]: def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]: """ - 返回 [(line_key_or_header, field_id, row_index, table_id, raw_field_obj)]。 - header scope 行 line_key=None。 + 返回 [(draft_line_id_or_header, field_id, row_index, table_id, raw_field_obj)]。 + header scope 行 draft_line_id=None。 """ out: list[tuple[str, str, int | None, str, dict[str, Any]]] = [] candidates = [ @@ -315,7 +314,7 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st for row_idx, row in enumerate(rows): if not isinstance(row, dict): continue - line_key = _safe_str(row.get('line_key')) + draft_line_id = _safe_str(row.get('draft_line_id')) data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index')) for raw_field in row.get('fields') or []: if not isinstance(raw_field, dict): @@ -323,9 +322,9 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st fid = _safe_str(raw_field.get('field_id')) if not fid: continue - effective_line_key = line_key + effective_draft_line_id = draft_line_id out.append(( - effective_line_key, + effective_draft_line_id, fid, data_row_idx, table_id, @@ -358,7 +357,7 @@ def _schema_fields_map(case) -> dict[str, dict[str, Any]]: _FIELD_VIEW_KEYS = ( 'field_id', 'field_code', 'display_name', 'scope', 'data_type', 'llm_context_policy', - 'line_key', + 'draft_line_id', 'machine_value', 'current_draft_value', 'value_source', 'primary_evidence', 'field_evidences', ) @@ -375,7 +374,7 @@ def _build_field_view( field_id: str, field_metadata: dict[str, Any] | None, scope: Literal['header', 'line'], - line_key: str | None, + draft_line_id: str | None, case_id: int, case_document_id: int, ) -> dict[str, Any]: @@ -387,7 +386,7 @@ def _build_field_view( view['display_name'] = _safe_str(md.get('display_name')) or code view['scope'] = scope view['data_type'] = _safe_str(md.get('data_type')) - view['line_key'] = line_key + view['draft_line_id'] = draft_line_id policy = resolve_llm_context_policy( field_metadata=md, field_code=code, @@ -457,9 +456,9 @@ def build_review_evidence_view(case) -> dict[str, Any]: "diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] }, "header_fields": { [field_id]: field_view }, "line_fields": { - [line_key]: { [field_id]: field_view } + [draft_line_id]: { [field_id]: field_view } }, - "lines_order": [line_key...], + "lines_order": [draft_line_id...], "layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone "frozen_document_snapshot": dict, // 只读 } @@ -481,7 +480,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: def _ensure_field( fid: str, scope: Literal['header', 'line'], - line_key: str | None = None, + draft_line_id: str | None = None, ) -> dict[str, Any]: if scope == 'header': if fid not in header_fields: @@ -489,22 +488,22 @@ def build_review_evidence_view(case) -> dict[str, Any]: field_id=fid, field_metadata=schema_fields.get(fid), scope='header', - line_key=None, + draft_line_id=None, case_id=case_id, case_document_id=case_document_id, ) return header_fields[fid] - assert line_key - if line_key not in line_fields: - line_fields[line_key] = {} - lines_order.append(line_key) - line_map = line_fields[line_key] + assert draft_line_id + if draft_line_id not in line_fields: + line_fields[draft_line_id] = {} + lines_order.append(draft_line_id) + line_map = line_fields[draft_line_id] if fid not in line_map: line_map[fid] = _build_field_view( field_id=fid, field_metadata=schema_fields.get(fid), scope='line', - line_key=line_key, + draft_line_id=draft_line_id, case_id=case_id, case_document_id=case_document_id, ) @@ -540,8 +539,8 @@ def build_review_evidence_view(case) -> dict[str, Any]: if v is not None: fv['machine_value'] = v - for line_key, _pos, fid, raw_field in _iter_unit_line_fields(order): - fv = _ensure_field(fid, 'line', line_key=line_key) + for draft_line_id, _pos, fid, raw_field in _iter_unit_line_fields(order): + fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id) observations = raw_field.get('observations') or [] fc = _safe_str(raw_field.get('field_code')) or fv['field_code'] for raw_obs in observations: @@ -553,7 +552,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=fc, - line_key=line_key, + draft_line_id=draft_line_id, ) fv['field_evidences'].append(norm) if fv['machine_value'] is None: @@ -597,17 +596,17 @@ def build_review_evidence_view(case) -> dict[str, Any]: # Lines draft_lines = _draft_line_list(draft) for line in draft_lines: - line_key = _safe_str(line.get('line_key')) - if not line_key: + draft_line_id = _safe_str(line.get('draft_line_id')) + if not draft_line_id: continue - line_map = line_fields.setdefault(line_key, {}) - if line_key not in lines_order: - lines_order.append(line_key) + line_map = line_fields.setdefault(draft_line_id, {}) + if draft_line_id not in lines_order: + lines_order.append(draft_line_id) for fid in list(line_map.keys()) + list(schema_fields.keys()): md = schema_fields.get(fid) if md and _safe_str(md.get('scope')) == 'header': continue - fv = _ensure_field(fid, 'line', line_key=line_key) + fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id) obj = _machine_field_value(line, fid) if isinstance(obj, dict): for raw_obs in (obj.get('observations') or []): @@ -619,7 +618,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=_safe_str(obj.get('field_code')) or fv['field_code'], - line_key=line_key, + draft_line_id=draft_line_id, ) fv['field_evidences'].append(norm) if fv['machine_value'] is None and obj.get('value') is not None: @@ -630,7 +629,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: frozen_doc = _frozen_document_snapshot(case) for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc): scope = 'line' if lk else 'header' - fv = _ensure_field(fid, scope=scope, line_key=lk or None) + fv = _ensure_field(fid, scope=scope, draft_line_id=lk or None) wrapped = { 'value': raw_field.get('value') or raw_field.get('quote'), 'quote': raw_field.get('quote') or raw_field.get('value'), @@ -651,7 +650,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=fv['field_code'], - line_key=lk or None, + draft_line_id=lk or None, derived_row_index=ridx, ) fv['field_evidences'].append(norm) @@ -683,25 +682,25 @@ def get_field_view( view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, ) -> dict[str, Any] | None: fid = str(field_id or '').strip() if not fid: return None - if line_key: - lk = str(line_key).strip() + if draft_line_id: + lk = str(draft_line_id).strip() line_map = view.get('line_fields') or {} row = line_map.get(lk) or {} return row.get(fid) or None return (view.get('header_fields') or {}).get(fid) -def count_valid_row_fields(view: dict[str, Any], line_key: str) -> int: +def count_valid_row_fields(view: dict[str, Any], draft_line_id: str) -> int: """ 同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。 用于门禁:同行字段数 >= 2 才允许 L2_row。 """ - lk = str(line_key or '').strip() + lk = str(draft_line_id or '').strip() line_map = (view.get('line_fields') or {}).get(lk) or {} count = 0 for fv in line_map.values(): diff --git a/backend/app/services/shipping_notice/order_review_field_conflict_service.py b/backend/app/services/shipping_notice/order_review_field_conflict_service.py index 2e4d7a1d..6fd7a480 100644 --- a/backend/app/services/shipping_notice/order_review_field_conflict_service.py +++ b/backend/app/services/shipping_notice/order_review_field_conflict_service.py @@ -194,7 +194,7 @@ def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]: return options -def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: +def _draft_line_id_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: """按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。""" draft = case.current_draft if draft is None: @@ -206,12 +206,12 @@ def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | raw_idx = raw.get('line_index') try: if raw_idx is not None and int(raw_idx) == int(line_index): - key = str(raw.get('line_key') or '').strip() + key = str(raw.get('draft_line_id') or '').strip() return key or None except (TypeError, ValueError): pass if idx == int(line_index): - key = str(raw.get('line_key') or '').strip() + key = str(raw.get('draft_line_id') or '').strip() return key or None return None @@ -322,12 +322,12 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu ) for key in value_keys ] - line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None + draft_line_id = _draft_line_id_for_index(case, line_index) if line_index >= 0 else None finding = { 'conflict_key': _stored_conflict_key(item), 'field_code': field, 'line_index': line_index if line_index >= 0 else None, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)), 'severity': str(item.get('severity') or 'blocking'), 'reason': reason, @@ -473,10 +473,10 @@ def resolve_review_case_field_conflict( header = dict(case.current_draft.header_values_json or {}) change = _set_value(header, field, chosen_display, restore_machine=False) case.current_draft.header_values_json = header - line_key = None + draft_line_id = None else: - line_key = _line_key_for_index(case, line_index) - if not line_key: + draft_line_id = _draft_line_id_for_index(case, line_index) + if not draft_line_id: raise ConflictError( 'Conflict line is missing from draft', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', @@ -486,14 +486,14 @@ def resolve_review_case_field_conflict( lines = list(case.current_draft.lines_json or []) target_line = None for raw in lines: - if isinstance(raw, dict) and str(raw.get('line_key') or '') == line_key: + if isinstance(raw, dict) and str(raw.get('draft_line_id') or '') == draft_line_id: target_line = raw break if target_line is None: raise ConflictError( 'Conflict line is missing from draft', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', - details={'line_key': line_key}, + details={'draft_line_id': draft_line_id}, ) change = _set_value(target_line, field, chosen_display, restore_machine=False) case.current_draft.lines_json = lines @@ -514,7 +514,7 @@ def resolve_review_case_field_conflict( operation={ 'conflict_key': conflict_key, 'field_code': field_code, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'resolution': mode, 'option_index': option_index, 'chosen_value': chosen_display, diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index 916df1af..e5c9b155 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -27,6 +27,7 @@ from app.models import ( ShippingOrderReviewLineDecision, ShippingOrderReviewWaveLine, ShippingNotice, + ShippingOrderTask, ShippingTaskInventoryRpaAttempt, ) from app.services.shipping_notice.workflow_ledger_service import ( @@ -236,15 +237,16 @@ def _release_fact_identity(fact: dict[str, Any] | None) -> tuple[int | None, int def _resolve_shortage_release_inventory_source( *, fact_source_code: Any, - task_source_code: Any, snapshot_source_code: Any, + candidate_source_codes: set[str] | None = None, ) -> str | None: - """按行事实、OT、快照顺序恢复短缺放行所需的库存源。""" - for value in (fact_source_code, task_source_code, snapshot_source_code): + """按行事实、库存文件、唯一冻结候选源顺序恢复短缺放行所需的库存源。""" + for value in (fact_source_code, snapshot_source_code): normalized = str(value or '').strip().upper() if normalized: return normalized - return None + codes = candidate_source_codes or set() + return next(iter(codes)) if len(codes) == 1 else None def _is_shortage_match_fact(fact: Any) -> bool: @@ -285,9 +287,6 @@ def _has_terminal_inventory_rpa_failure( source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)} except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。 source_codes = set() - source_code = str(getattr(task, 'inventory_source_code', '') or '').strip().upper() - if source_code: - source_codes.add(source_code) rows = attempts if attempts is not None else ( ShippingTaskInventoryRpaAttempt.query .filter_by(task_no=task_no) @@ -326,15 +325,21 @@ def _shortage_release_required_fields( code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None - if inventory_snapshot_id is not None and (snapshot is None or not isinstance(snapshot.inventory_lines_json, list)): + if inventory_snapshot_id is not None and snapshot is None: raise ConflictError( 'Current inventory snapshot is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + resolved_source_code = _resolve_shortage_release_inventory_source( fact_source_code=inventory_source_code, - task_source_code=getattr(task, 'inventory_source_code', None), snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None, + candidate_source_codes={ + str(code or '').strip().upper() + for code in task_frozen_inventory_source_codes(task) + if str(code or '').strip() + }, ) if not resolved_source_code: raise ConflictError( @@ -366,7 +371,7 @@ def _shortage_release_required_fields( and str(item.get('source_key') or '').strip().isdigit() } labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {} - return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + _release_template_system_fields(mappings=mappings, warehouse_id=getattr(task, 'inventory_warehouse_id', None)) + return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else [] expected = [ @@ -378,9 +383,17 @@ def _shortage_release_required_fields( 'Inventory matching keys are unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) + from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + try: + inventory_lines, _column_meta = read_inventory_file_lines(snapshot) + except (OSError, ValueError, AppError) as exc: + raise ConflictError( + 'Current inventory snapshot is unavailable', + code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', + ) from exc candidates = [ - dict(row) for row in snapshot.inventory_lines_json if isinstance(row, dict) - and all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) + dict(row) for row in inventory_lines + if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) ] field_ids = { int(str(item.get('source_key') or '').strip()) @@ -398,9 +411,6 @@ def _shortage_release_required_fields( mappings=mappings, candidates=candidates, field_labels=labels, - ) + _release_template_system_fields( - mappings=mappings, - warehouse_id=getattr(task, 'inventory_warehouse_id', None), ) @@ -426,7 +436,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act task_id = getattr(case, 'confirmed_task_id', None) if task_id is None: return - task = db.session.get(ShippingNotice, int(task_id)) + task = db.session.get(ShippingOrderTask, int(task_id)) if task is None: return # [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态 @@ -556,7 +566,7 @@ def _assess_line_fulfill_complete( def _assert_line_can_fulfill_complete( *, - line_key: str, + draft_line_id: str, draft_line: dict[str, Any], proj: dict[str, Any], schema_fields: dict[str, dict[str, Any]] | None = None, @@ -576,13 +586,13 @@ def _assert_line_can_fulfill_complete( raise ConflictError( 'Line cannot fulfill complete quantity with current inventory', code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'), - details={'line_key': line_key}, + details={'draft_line_id': draft_line_id}, ) return req, avail def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]: - """line_key → 草稿行。""" + """draft_line_id → 草稿行。""" draft = case.current_draft if draft is None: return {} @@ -590,16 +600,16 @@ def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]: for idx, line in enumerate(list(draft.lines_json or [])): if not isinstance(line, dict): continue - key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}' + key = str(line.get('draft_line_id') or '').strip() or f'line-{idx + 1}' row = dict(line) row['_line_index'] = idx - row['_line_key'] = key + row['_draft_line_id'] = key out[key] = row return out def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]: - """line_key → eligibility line projection。""" + """draft_line_id → eligibility line projection。""" draft = case.current_draft if draft is None: return {} @@ -608,29 +618,29 @@ def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, A for idx, item in enumerate(list(validation.get('line_projections') or [])): if not isinstance(item, dict): continue - key = str(item.get('line_key') or '').strip() or f'line-{idx + 1}' + key = str(item.get('draft_line_id') or '').strip() or f'line-{idx + 1}' out[key] = dict(item) return out def _active_decision( case: ShippingOrderReviewCase, - line_key: str, + draft_line_id: str, ) -> ShippingOrderReviewLineDecision | None: """取某行当前活动决定。""" return ( ShippingOrderReviewLineDecision.query - .filter_by(review_case_id=int(case.id), line_key=str(line_key), is_active=True) + .filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id), is_active=True) .order_by(ShippingOrderReviewLineDecision.decision_version.desc()) .first() ) -def _next_version(case: ShippingOrderReviewCase, line_key: str) -> int: +def _next_version(case: ShippingOrderReviewCase, draft_line_id: str) -> int: """下一决定版本号。""" latest = ( ShippingOrderReviewLineDecision.query - .filter_by(review_case_id=int(case.id), line_key=str(line_key)) + .filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id)) .order_by(ShippingOrderReviewLineDecision.decision_version.desc()) .first() ) @@ -641,7 +651,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]: """用户态决定投影。""" return { 'id': int(row.id), - 'line_key': row.line_key, + 'draft_line_id': row.draft_line_id, 'line_index': row.line_index, 'decision_version': int(row.decision_version), 'decision_code': row.decision_code, @@ -766,44 +776,33 @@ def project_review_case_line_decisions( schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case) formal_ot = resolve_formal_ot(case) has_formal_ot = bool(formal_ot.get('has_formal_ot')) - task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None + task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingOrderTask) else None if task is None and getattr(case, 'confirmed_task_id', None) is not None: - task = db.session.get(ShippingNotice, int(case.confirmed_task_id)) + task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task)) - # [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示) - # 优先级:行级 inventory_source_code > Task resolved 正式源 > candidates_frozen > resolving + # [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。 from app.services.shipping_notice.stp_inventory_freeze import ( task_frozen_inventory_source_codes, ) fallback_inventory_source: dict[str, Any] | None = None if task is not None: - task_source_code = str(task.inventory_source_code or '').strip().upper() or None - task_source_status = str(task.inventory_source_status or '').strip() - if task_source_code and task_source_status == 'resolved': + frozen_codes = task_frozen_inventory_source_codes(task) + if len(frozen_codes) == 1: fallback_inventory_source = { - 'code': task_source_code, + 'code': frozen_codes[0], 'label': None, 'status': 'resolved', - 'source': 'task_inventory_source', + 'source': 'frozen_inventory_candidates', + } + elif frozen_codes: + fallback_inventory_source = { + 'code': None, + 'label': None, + 'status': 'candidates_frozen', + 'candidates': list(frozen_codes), + 'source': 'frozen_inventory_candidates', } - elif task_source_status == 'candidates_frozen': - frozen_codes = task_frozen_inventory_source_codes(task) - if frozen_codes: - fallback_inventory_source = { - 'code': None, - 'label': None, - 'status': 'candidates_frozen', - 'candidates': list(frozen_codes), - 'source': 'frozen_inventory_candidates', - } - else: - fallback_inventory_source = { - 'code': None, - 'label': None, - 'status': 'resolving', - 'source': 'inventory_source_clue', - } else: fallback_inventory_source = { 'code': None, @@ -825,10 +824,10 @@ def project_review_case_line_decisions( active_rows = ( ShippingOrderReviewLineDecision.query .filter_by(review_case_id=int(case.id), is_active=True) - .order_by(ShippingOrderReviewLineDecision.line_key.asc()) + .order_by(ShippingOrderReviewLineDecision.draft_line_id.asc()) .all() ) - by_key = {str(row.line_key): row for row in active_rows} + by_key = {str(row.draft_line_id): row for row in active_rows} lines_out: list[dict[str, Any]] = [] for key, draft_line in draft_lines.items(): @@ -909,8 +908,6 @@ def project_review_case_line_decisions( release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact) if release_line_index is None: release_line_index = draft_line.get('_line_index') - if not release_source_code: - release_source_code = getattr(task, 'inventory_source_code', None) release_template_fields = _shortage_release_required_fields( task=task, line_index=release_line_index, @@ -925,7 +922,7 @@ def project_review_case_line_decisions( available = inv_view.get('available_qty') shortage = inv_view.get('shortage_qty') lines_out.append({ - 'line_key': key, + 'draft_line_id': key, 'line_index': draft_line.get('_line_index'), 'reservation_id': _line_reservation_id(draft_line, proj), 'part_number': _line_part_number( @@ -1067,7 +1064,7 @@ def decide_review_line_fulfillment( *, user_id: int, case_no: str, - line_key: str, + draft_line_id: str, decision_code: str, reason: str | None = None, release_field_values: dict[str, Any] | None = None, @@ -1084,7 +1081,7 @@ def decide_review_line_fulfillment( Args: user_id: 操作人。 case_no: Case 编号。 - line_key: 草稿行键。 + draft_line_id: 草稿行键。 decision_code: 决定码。 reason: 关闭/重开/短缺放行必填原因。 release_field_values: 短缺放行时模板行级库存字段的人工补录值。 @@ -1118,7 +1115,7 @@ def decide_review_line_fulfillment( ) lines = _draft_line_map(case) - key = str(line_key or '').strip() + key = str(draft_line_id or '').strip() if key not in lines: raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') @@ -1128,20 +1125,20 @@ def decide_review_line_fulfillment( raise ConflictError( 'Line already fulfilled in a task wave', code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_key': key, 'line_status': current.line_status}, + details={'draft_line_id': key, 'line_status': current.line_status}, ) if code == DECISION_REOPEN: if current is None or current.line_status != 'closed_unfulfillable': raise ConflictError( 'Only closed_unfulfillable lines can be reopened', code='SHIPPING.REVIEW_LINE_REOPEN_NOT_ALLOWED', - details={'line_key': key}, + details={'draft_line_id': key}, ) if not actor_is_admin: raise ConflictError( 'Reopen requires admin', code='SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN', - details={'line_key': key}, + details={'draft_line_id': key}, ) elif current is not None and current.line_status == 'closed_unfulfillable': raise ConflictError( @@ -1161,7 +1158,7 @@ def decide_review_line_fulfillment( avail_qty = _parse_qty(proj.get('available_qty')) if code == DECISION_FULFILL: req_qty, avail_qty = _assert_line_can_fulfill_complete( - line_key=key, + draft_line_id=key, draft_line=draft_line, proj=proj, schema_fields=schema_fields, @@ -1170,10 +1167,10 @@ def decide_review_line_fulfillment( from app.models import ShippingNoticeLineInventoryMatch task_id = getattr(case, 'confirmed_task_id', None) - task = db.session.get(ShippingNotice, int(task_id)) if task_id is not None else None + task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None fact = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id), line_key=key, is_current=True) + .filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True) .first() if task is not None else None ) @@ -1182,25 +1179,20 @@ def decide_review_line_fulfillment( raise ConflictError( 'Only shortage lines can be released', code='SHIPPING.REVIEW_LINE_RELEASE_NOT_ALLOWED', - details={'line_key': key}, + details={'draft_line_id': key}, ) release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index') release_template_fields = _shortage_release_required_fields( task=task, line_index=release_line_index, inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None, - inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else getattr(task, 'inventory_source_code', None), + inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None, ) if task is not None else [] release_required_fields = _manual_required_release_fields(release_template_fields) release_values = _validate_inventory_shortage_release_fields( required_fields=release_required_fields, supplied_values=release_field_values or {}, ) - supplied_warehouse_id = str(release_values.get('system_fact:warehouse_id') or '').strip().upper() - if supplied_warehouse_id: - # Header Warehouse ID 是动态库存源导出的任务级系统事实;人工放行时必须 - # 显式固化,供后续 Excel 生成消费,并同时保留在决定快照中审计。 - task.inventory_warehouse_id = supplied_warehouse_id else: release_required_fields = [] release_values = {} @@ -1213,7 +1205,7 @@ def decide_review_line_fulfillment( status = _STATUS_BY_DECISION.get(code, 'pending_decision') row = ShippingOrderReviewLineDecision( review_case_id=int(case.id), - line_key=key, + draft_line_id=key, line_index=draft_line.get('_line_index'), decision_version=_next_version(case, key), decision_code=code, @@ -1237,7 +1229,7 @@ def decide_review_line_fulfillment( 'decision_source': 'user', 'required_qty': str(req_qty) if req_qty is not None else None, 'available_qty': str(avail_qty) if avail_qty is not None else None, - 'line_key': key, + 'draft_line_id': key, 'release_field_values': release_values, 'release_required_fields': release_required_fields, }, @@ -1262,7 +1254,7 @@ def decide_review_line_fulfillment( review_case_no=str(case.case_no), run_no=str(case.run.run_no) if case.run is not None else None, metadata={ - 'line_key': key, + 'draft_line_id': key, 'decision_code': code, 'decision_version': int(row.decision_version), 'line_status': status, @@ -1301,7 +1293,7 @@ def close_remaining_fulfillment( user_id: int, case_no: str, reason: str, - line_keys: list[str] | None = None, + draft_line_ids: list[str] | None = None, expected_draft_version: Any = None, actor_is_admin: bool = False, ) -> dict[str, Any]: @@ -1312,7 +1304,7 @@ def close_remaining_fulfillment( user_id: 操作人。 case_no: Case 编号。 reason: 强制原因。 - line_keys: 指定行;为空则关闭全部开放行。 + draft_line_ids: 指定行;为空则关闭全部开放行。 expected_draft_version: 可选草稿版本。 actor_is_admin: 透传给 decide(关闭本身不要求管理员)。 @@ -1326,10 +1318,10 @@ def close_remaining_fulfillment( ) case = _load_writable_case(user_id=user_id, case_no=case_no) projection = project_review_case_line_decisions(case) - targets = list(line_keys or []) + targets = list(draft_line_ids or []) if not targets: targets = [ - str(item['line_key']) + str(item['draft_line_id']) for item in projection.get('lines') or [] if item.get('line_status') not in _TERMINAL_ACTIVE ] @@ -1338,7 +1330,7 @@ def close_remaining_fulfillment( last = decide_review_line_fulfillment( user_id=user_id, case_no=case_no, - line_key=key, + draft_line_id=key, decision_code=DECISION_CLOSE, reason=reason, expected_draft_version=expected_draft_version, diff --git a/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py index a0ecd7cc..4221d559 100644 --- a/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py +++ b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py @@ -145,14 +145,14 @@ def _check_table_duplicate_value( evidence_view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, field_view_obj: dict[str, Any], ) -> bool: """ [Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。 Header scope:此检测跳过(不适用)。目标 value 为空时跳过。 """ - if not line_key: + if not draft_line_id: return False if not isinstance(evidence_view, dict): return False @@ -169,7 +169,7 @@ def _check_table_duplicate_value( return False same_table_hits = 0 for lk, lf_map in line_fields.items(): - if lk == str(line_key) or not isinstance(lf_map, dict): + if lk == str(draft_line_id) or not isinstance(lf_map, dict): continue fv = lf_map.get(str(field_id)) if not isinstance(fv, dict): @@ -206,16 +206,16 @@ def _check_manual_conflict(field_view: dict[str, Any]) -> bool: def _check_context_borderline( evidence_view: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, ) -> bool: """ [Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。 处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。 """ - if not line_key: + if not draft_line_id: return False try: - siblings = count_valid_row_fields(evidence_view, str(line_key)) + siblings = count_valid_row_fields(evidence_view, str(draft_line_id)) except Exception: return False return siblings == _BORDERLINE_SIBLING_COUNT @@ -224,20 +224,20 @@ def _check_context_borderline( def _check_context_identity_insufficient( evidence_view: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, field_view_obj: dict[str, Any], ) -> bool: """ [Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no), 或目标字段 primary_evidence.confidence 低于阈值。 """ - if not line_key: + if not draft_line_id: return False if not isinstance(evidence_view, dict): return False # 身份标识检测 line_fields = evidence_view.get('line_fields') or {} - lf = line_fields.get(str(line_key)) if isinstance(line_fields, dict) else None + lf = line_fields.get(str(draft_line_id)) if isinstance(line_fields, dict) else None has_identity = False if isinstance(lf, dict): for fid, fv in lf.items(): @@ -276,7 +276,7 @@ def resolve_auto_upgrade_level( *, evidence_view: dict[str, Any], field_id: str, - line_key: str | None, + draft_line_id: str | None, requested_level: EvidenceLevelV2, schema_field_meta: dict[str, Any] | None = None, issue_code: str | None = None, @@ -287,7 +287,7 @@ def resolve_auto_upgrade_level( Args: evidence_view: build_review_evidence_view() 的返回。 field_id: 目标字段 ID。 - line_key: 目标行键;None 表示 header scope。 + draft_line_id: 目标草稿行身份;None 表示 header scope。 requested_level: 用户/前端请求的等级(默认 L2_row)。 schema_field_meta: schema.definition_json.fields[] 中的原始元数据。 issue_code: 前端透传的冲突 issue_code(触发 P1)。 @@ -301,7 +301,7 @@ def resolve_auto_upgrade_level( if not isinstance(evidence_view, dict): return requested_level, None, [] - field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if field_view is None: return requested_level, None, [] @@ -313,7 +313,7 @@ def resolve_auto_upgrade_level( if str(requested_level) not in {'L1_field', 'L2_row'}: return requested_level, None, [] - scope_is_line = bool(line_key) + scope_is_line = bool(draft_line_id) reasons_hit: list[str] = [] # [STEP 1] 按优先级顺序跑 7 项检测,命中即追加 @@ -326,17 +326,17 @@ def resolve_auto_upgrade_level( if _check_table_duplicate_value( evidence_view, field_id=field_id, - line_key=line_key, + draft_line_id=draft_line_id, field_view_obj=field_view, ): reasons_hit.append('table_duplicate_value') if _check_manual_conflict(field_view): reasons_hit.append('manual_conflict') - if _check_context_borderline(evidence_view, line_key=line_key): + if _check_context_borderline(evidence_view, draft_line_id=draft_line_id): reasons_hit.append('context_borderline') if _check_context_identity_insufficient( evidence_view, - line_key=line_key, + draft_line_id=draft_line_id, field_view_obj=field_view, ): reasons_hit.append('context_identity_insufficient') diff --git a/backend/app/services/shipping_notice/order_review_llm_contract.py b/backend/app/services/shipping_notice/order_review_llm_contract.py index e923af20..f8cf7282 100644 --- a/backend/app/services/shipping_notice/order_review_llm_contract.py +++ b/backend/app/services/shipping_notice/order_review_llm_contract.py @@ -180,9 +180,9 @@ def is_valid_provenance_ref(value: Any) -> bool: return _DRAFT_REF_RE.match(value.strip()) is not None -def build_provenance_ref(*, case_id: int, line_key: str | None, field_code: str) -> str: +def build_provenance_ref(*, case_id: int, draft_line_id: str | None, field_code: str) -> str: """生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。""" - line = str(line_key or 'header').strip() or 'header' + line = str(draft_line_id or 'header').strip() or 'header' return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}' # --------------------------------------------------------------------------- @@ -231,10 +231,10 @@ class V2Target(TypedDict, total=False): field_id: str field_code: str scope: Literal['header', 'line'] - line_key: str | None + draft_line_id: str | None class V2RowContext(TypedDict, total=False): - line_key: str + draft_line_id: str fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source class V2TableContext(TypedDict, total=False): @@ -243,7 +243,7 @@ class V2TableContext(TypedDict, total=False): target_row_index: int | None class V2NeighborRow(TypedDict, total=False): - line_key: str + draft_line_id: str row_index: int fields: list[dict[str, Any]] position: Literal['preceding', 'following'] @@ -347,7 +347,7 @@ def build_suggestion_request_envelope( return envelope # --------------------------------------------------------------------------- -# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增) +# 响应解析(v1/v2 统一出口,draft_line_id/scope/needs_review v2 新增) # --------------------------------------------------------------------------- def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]: """ @@ -371,10 +371,10 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any] needs_review = False if isinstance(item.get('needs_review'), bool): needs_review = bool(item['needs_review']) - line_key_raw = item.get('line_key') - line_key = str(line_key_raw).strip() if line_key_raw is not None else None - if not line_key: - line_key = None + draft_line_id_raw = item.get('draft_line_id') + draft_line_id = str(draft_line_id_raw).strip() if draft_line_id_raw is not None else None + if not draft_line_id: + draft_line_id = None scope = str(item.get('scope') or '').strip().lower() if scope not in {'header', 'line'}: scope = 'line' @@ -387,7 +387,7 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any] 'field_id': field_id, 'field_code': str(item.get('field_code') or '').strip() or None, 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'suggested_value': item.get('suggested_value'), 'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000], 'confidence': confidence, diff --git a/backend/app/services/shipping_notice/order_review_llm_gate.py b/backend/app/services/shipping_notice/order_review_llm_gate.py index a79efd16..6bbf3715 100644 --- a/backend/app/services/shipping_notice/order_review_llm_gate.py +++ b/backend/app/services/shipping_notice/order_review_llm_gate.py @@ -9,7 +9,7 @@ services/shipping_notice/order_review_llm_gate.py - order_review_llm_policy_registry.resolve_llm_context_policy 逻辑: [1] field_not_found 目标 field_id 在 schema 中不存在 - [2] line_not_found 目标 line_key 在视图中行找不到 + [2] line_not_found 目标 draft_line_id 在视图中行找不到 [3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空 [4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实) [5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定 @@ -57,7 +57,7 @@ def run_preflight_gate( evidence_view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, requested_level: EvidenceLevelV2 | None, schema_field_meta: dict[str, Any] | None = None, ) -> GateResult: @@ -77,15 +77,15 @@ def run_preflight_gate( return False, 'context_ambiguous', \ '; '.join(str(r) for r in ambiguous_reasons) - # [2] line scope 需要 line_key 存在 - scope_is_line = bool(line_key) + # [2] line scope 需要 draft_line_id 存在 + scope_is_line = bool(draft_line_id) if scope_is_line: line_fields = evidence_view.get('line_fields') or {} - if str(line_key) not in line_fields: - return False, 'line_not_found', f'line_key={line_key}' + if str(draft_line_id) not in line_fields: + return False, 'line_not_found', f'draft_line_id={draft_line_id}' # [1] field_id 找不到(header/line 都没命中) - field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if field_view is None: return False, 'field_not_found', f'field_id={field_id}' @@ -127,10 +127,10 @@ def run_preflight_gate( effective_level = requested_level or 'L2_row' if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED: if scope_is_line and str(effective_level) in ('L2_row',): - siblings = count_valid_row_fields(evidence_view, str(line_key)) + siblings = count_valid_row_fields(evidence_view, str(draft_line_id)) if siblings < _MIN_LINE_SIBLINGS: return False, 'context_insufficient', \ - f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' + f'draft_line_id={draft_line_id} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' return True, None, None diff --git a/backend/app/services/shipping_notice/order_review_llm_service.py b/backend/app/services/shipping_notice/order_review_llm_service.py index 7cfc03fd..2634c192 100644 --- a/backend/app/services/shipping_notice/order_review_llm_service.py +++ b/backend/app/services/shipping_notice/order_review_llm_service.py @@ -117,7 +117,7 @@ def _audit_llm_suggestion( """ after_payload = { 'field_id': suggestion.field_id, - 'line_key': suggestion.line_key, + 'draft_line_id': suggestion.draft_line_id, 'status': suggestion.status, 'decision': suggestion.decision, **(after or {}), @@ -242,7 +242,7 @@ def serialize_suggestion( base: dict[str, Any] = { 'suggestion_no': row.suggestion_no, 'field_id': row.field_id, - 'line_key': row.line_key, + 'draft_line_id': row.draft_line_id, 'scope': row.scope, 'evidence_level': row.evidence_level, 'contract_version': row.contract_version, @@ -289,7 +289,7 @@ def serialize_suggestion( 'field_id': (i.get('field_id') if isinstance(i, dict) else None), 'field_code': (i.get('field_code') if isinstance(i, dict) else None), 'scope': (i.get('scope') if isinstance(i, dict) else None), - 'line_key': (i.get('line_key') if isinstance(i, dict) else None), + 'draft_line_id': (i.get('draft_line_id') if isinstance(i, dict) else None), } for i in tf if isinstance(i, dict) ][:50] @@ -368,7 +368,7 @@ def request_field_suggestion( user_id: int, case_no: str, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, evidence_level: str | None = None, issue_code: str | None = None, allow_full_pdf: bool = False, @@ -381,7 +381,7 @@ def request_field_suggestion( user_id: Case 属主。 case_no: 复核 Case 编号。 field_id: 目标 field_id。 - line_key: 明细行键。 + draft_line_id: 草稿行身份。 evidence_level: L1_field–L4_pdf。 issue_code: 关联 issue。 allow_full_pdf: 管理员显式 L4。 @@ -396,8 +396,8 @@ def request_field_suggestion( field = _schema_field(case, field_id) scope = str(field.get('scope') or 'header') - if scope == 'line' and not line_key: - raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') + if scope == 'line' and not draft_line_id: + raise ValidationError('draft_line_id is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') level_raw = _normalize_level(evidence_level or 'L1_field') if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf): @@ -409,7 +409,7 @@ def request_field_suggestion( 'field_id': str(field_id), 'field_code': str(field.get('field_code') or field_id), 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': None, }] row = ShippingOrderReviewSuggestion( @@ -418,7 +418,7 @@ def request_field_suggestion( document_id=int(case.document_id), run_id=int(case.run_id) if case.run_id else None, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, scope=scope, evidence_level=level, status='pending', @@ -454,7 +454,7 @@ def request_field_suggestion( upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level( evidence_view=evidence_view, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, requested_level=level, # type: ignore[arg-type] schema_field_meta=field, issue_code=issue_code, @@ -488,15 +488,15 @@ def request_field_suggestion( passed, gate_error, gate_hint = run_preflight_gate( evidence_view, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, requested_level=level, # type: ignore[arg-type] schema_field_meta=field, ) # 填充观测列(gated 或未 gated 都写,便于对账 context_hash) _evidence_view_count = 0 - if line_key: + if draft_line_id: line_map = (evidence_view or {}).get('line_fields') or {} - row_map = line_map.get(str(line_key)) or {} + row_map = line_map.get(str(draft_line_id)) or {} target_view = row_map.get(str(field_id)) else: header_map = (evidence_view or {}).get('header_fields') or {} @@ -617,7 +617,7 @@ def request_field_suggestion( 'field_id': str(field_id), 'field_code': str(field.get('field_code') or field_id), 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, }, expected_target_field_id=str(field_id), auto_upgrade_reason=_auto_upgrade_reason, @@ -631,7 +631,7 @@ def request_field_suggestion( 'document_id': int(case.document_id), 'draft_version': int(case.current_draft.draft_version if case.current_draft else 0), 'field_id': str(field_id), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'contract_version': LLM_REVIEW_CONTRACT_VERSION, 'evidence_level': level, 'target_fields': target_fields, @@ -781,7 +781,7 @@ def request_field_suggestion( evidence_pack=evidence_pack, envelope=request_payload, expected_target_field_id=str(field_id), - expected_line_key=line_key, + expected_draft_line_id=draft_line_id, expected_scope=scope, ) row.validated_suggestions_json = validated @@ -827,7 +827,7 @@ def request_field_suggestion( user_id=user_id, case_no=case_no, field_id=str(field_id), - line_key=line_key, + draft_line_id=draft_line_id, value=value, suggestion_no=row.suggestion_no, expected_draft_version=int(case.current_draft.draft_version), @@ -914,7 +914,7 @@ def decide_suggestion( before_status = { 'status': suggestion.status, 'field_id': suggestion.field_id, - 'line_key': suggestion.line_key, + 'draft_line_id': suggestion.draft_line_id, } case_payload = adjudicate_llm_suggestion_on_draft( user_id=user_id, diff --git a/backend/app/services/shipping_notice/order_review_llm_validation.py b/backend/app/services/shipping_notice/order_review_llm_validation.py index 88c4cc94..c9051329 100644 --- a/backend/app/services/shipping_notice/order_review_llm_validation.py +++ b/backend/app/services/shipping_notice/order_review_llm_validation.py @@ -5,15 +5,15 @@ services/shipping_notice/order_review_llm_validation.py 任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。 依赖: - order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text - - request_payload.envelope:target / expected_target_field_id / evidence[] / line_key 定位 - - 响应解析层:parse_suggestion_response 输出 [{field_id, line_key, scope, suggested_value, quote}] + - request_payload.envelope:target / expected_target_field_id / evidence[] / draft_line_id 定位 + - 响应解析层:parse_suggestion_response 输出 [{field_id, draft_line_id, scope, suggested_value, quote}] 逻辑: 8 项按顺序 fail-closed(优先级从身份→价值→安全性): 1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法) - 2. header_scope_has_line_key scope=header 时 line_key 不为 None(头部不能带行键) + 2. header_scope_has_draft_line_id scope=header 时 draft_line_id 不为 None 3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内 4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致 - 5. line_key_mismatch scope=line 时响应 line_key != 请求 line_key(精确相等) + 5. draft_line_id_mismatch scope=line 时响应 draft_line_id != 请求值(精确相等) 6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后) 7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或 完整相等;即使值存在也视为伪造 @@ -38,10 +38,10 @@ from app.services.shipping_notice.order_review_llm_contract import ( # --------------------------------------------------------------------------- _VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = ( 'json_schema_invalid', - 'header_scope_has_line_key', + 'header_scope_has_draft_line_id', 'non_target_field', 'field_id_mismatch', - 'line_key_mismatch', + 'draft_line_id_mismatch', 'value_not_in_evidence', 'quote_consistency', 'guess_without_evidence', @@ -55,7 +55,7 @@ def _collect_evidence_values( """ 从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。 v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。 - 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, line_key, evidence_ref} + 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, draft_line_id, evidence_ref} """ pool: list[dict[str, Any]] = [] env = envelope if isinstance(envelope, dict) else {} @@ -72,7 +72,7 @@ def _collect_evidence_values( 'value_raw': None if v_raw is None else str(v_raw), 'quote_raw': None if q_raw is None else str(q_raw), 'field_id': str(ev.get('field_id') or ''), - 'line_key': str(ev.get('line_key') or '').strip() or None, + 'draft_line_id': str(ev.get('draft_line_id') or '').strip() or None, 'evidence_ref': ev.get('evidence_ref'), }) return pool @@ -82,7 +82,7 @@ def _collect_evidence_values( if not isinstance(f, dict): continue fid = str(f.get('field_id') or '') - lk = str(f.get('line_key') or '').strip() or None + draft_line_id = str(f.get('draft_line_id') or '').strip() or None for sn in (f.get('snippets') or []): if not isinstance(sn, dict): continue @@ -94,44 +94,56 @@ def _collect_evidence_values( 'value_raw': None if v_raw is None else str(v_raw), 'quote_raw': None if q_raw is None else str(q_raw), 'field_id': fid, - 'line_key': lk, + 'draft_line_id': draft_line_id, 'evidence_ref': sn.get('evidence_ref'), }) return pool +def _is_pure_numeric(value: str) -> bool: + """判定某值是否为纯数字(可含正负号/小数点)。纯数字的子串匹配无意义(如 '10' 命中 '100'), + 会放行数量失真/幻觉,因此纯数字值只允许精确匹配,禁用子串匹配。""" + if not value: + return False + stripped = value.strip().lstrip('+-') + if not stripped: + return False + return stripped.replace('.', '', 1).isdigit() and any(ch.isdigit() for ch in stripped) + + def _find_value_match( pool: list[dict[str, Any]], *, value_norm: str, quote_norm_provided: str, field_id: str, - line_key: str | None, + draft_line_id: str | None, ) -> tuple[str, dict[str, Any] | None]: """ 在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。 严格度:exact → exact_substring → normalized → normalized_substring - 同池内优先匹配 field_id + line_key 双重身份的项;其次 field_id;最后全局任意项。 + 同池内优先匹配 field_id + draft_line_id 双重身份的项;其次 field_id;最后全局任意项。 """ if not value_norm and not quote_norm_provided: return '', None - # 身份过滤:先 field_id + line_key + # 身份过滤:先 field_id + draft_line_id def _iter_filtered(): if not pool: return same_identity = [ p for p in pool if str(p.get('field_id') or '') == field_id - and (str(p.get('line_key') or '') == str(line_key or '') - if line_key else not p.get('line_key')) + and (str(p.get('draft_line_id') or '') == str(draft_line_id or '') + if draft_line_id else not p.get('draft_line_id')) ] same_field = [ p for p in pool if str(p.get('field_id') or '') == field_id and p not in same_identity ] - others = [p for p in pool if p not in same_identity and p not in same_field] - for p in same_identity + same_field + others: + # 字段隔离:只允许用同 field_id 的证据验证当前字段建议, + # 禁止用其它字段(others)的证据兜底,避免跨字段误判(fail-closed)。 + for p in same_identity + same_field: yield p # 1. exact:raw 完全相等 @@ -142,12 +154,12 @@ def _find_value_match( if (vr and vr == needle) or (qr and qr == needle): return 'exact', p - # 2. exact_substring:raw 内 substring + # 2. exact_substring:raw 内 substring(纯数字禁用子串,防止 '10' 误命中 '100') for p in _iter_filtered(): vr = (p.get('value_raw') or '').strip() qr = (p.get('quote_raw') or '').strip() needle = value_norm.strip() - if not needle: + if not needle or _is_pure_numeric(needle): continue if (vr and needle in vr) or (qr and needle in qr): return 'exact_substring', p @@ -159,11 +171,11 @@ def _find_value_match( if (vn and vn == value_norm) or (qn and qn == value_norm): return 'normalized', p - # 4. normalized_substring:norm 内 substring + # 4. normalized_substring:norm 内 substring(纯数字禁用子串) for p in _iter_filtered(): vn = p.get('value_norm') or '' qn = p.get('quote_norm') or '' - if not value_norm: + if not value_norm or _is_pure_numeric(value_norm): continue if (vn and value_norm in vn) or (qn and value_norm in qn): return 'normalized_substring', p @@ -225,7 +237,7 @@ def validate_suggestions_against_evidence( evidence_pack: dict[str, Any], envelope: dict[str, Any] | None = None, expected_target_field_id: str | None = None, - expected_line_key: str | None = None, + expected_draft_line_id: str | None = None, expected_scope: str | None = None, ) -> list[dict[str, Any]]: """ @@ -236,7 +248,7 @@ def validate_suggestions_against_evidence( evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。 envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。 expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。 - expected_line_key: 期望 line_key(行 scope 用;header scope 传 None)。 + expected_draft_line_id: 期望草稿行身份(行 scope 用;header scope 传 None)。 expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。 Returns: @@ -258,9 +270,9 @@ def validate_suggestions_against_evidence( or str(target.get('field_id') or '').strip() or '' ) - _exp_lk_raw = expected_line_key + _exp_lk_raw = expected_draft_line_id if _exp_lk_raw is None: - _exp_lk_from_env = target.get('line_key') + _exp_lk_from_env = target.get('draft_line_id') _exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env) _exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None if _exp_lk == '' or _exp_lk == 'None': @@ -296,18 +308,18 @@ def validate_suggestions_against_evidence( result.append(payload) continue - # ---- [Check 2] header_scope_has_line_key ---- - checks_ran.append('header_scope_has_line_key') + # ---- [Check 2] header_scope_has_draft_line_id ---- + checks_ran.append('header_scope_has_draft_line_id') resp_scope = str(raw_item.get('scope') or '').strip().lower() if not resp_scope: resp_scope = 'line' if _exp_lk else 'header' - resp_lk_raw = raw_item.get('line_key') + resp_lk_raw = raw_item.get('draft_line_id') resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip() if resp_lk in ('', 'None'): resp_lk = None effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope if effective_scope == 'header' and resp_lk is not None: - rejection_reason = 'header_scope_has_line_key' + rejection_reason = 'header_scope_has_draft_line_id' if rejection_reason: payload['valid'] = False payload['rejection_reason'] = rejection_reason @@ -338,11 +350,11 @@ def validate_suggestions_against_evidence( result.append(payload) continue - # ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)---- - checks_ran.append('line_key_mismatch') + # ---- [Check 5] draft_line_id_mismatch ---- + checks_ran.append('draft_line_id_mismatch') if effective_scope == 'line': if _exp_lk and resp_lk != _exp_lk: - rejection_reason = 'line_key_mismatch' + rejection_reason = 'draft_line_id_mismatch' if rejection_reason: payload['valid'] = False payload['rejection_reason'] = rejection_reason @@ -368,7 +380,7 @@ def validate_suggestions_against_evidence( value_norm=sv_norm, quote_norm_provided=quote_norm, field_id=resp_fid, - line_key=resp_lk, + draft_line_id=resp_lk, ) if not _matched_mode: rejection_reason = 'value_not_in_evidence' diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index 648d9363..79c8d4a0 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -12,6 +12,7 @@ backend/app/services/shipping_notice/order_review_projection.py order_review_fulfillment_decision_service.project_review_case_line_decisions / build_inventory_issue_fallback、 order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、 + lifecycle_projection.project_lifecycle(队列摘要五阶段;禁止 build_task_ui_state)、 order_task_service.resolve_order_task_for_candidate、 schema_edit_policy.list_editable_formal_field_ids、 workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。 @@ -33,6 +34,7 @@ backend/app/services/shipping_notice/order_review_projection.py 普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback); 不返回会话级批量恢复动作;失败由当前 Gate 的具体动作恢复。 WorkflowItem 已关闭时 available_actions 仅保留 view; + 会话队列摘要对正式 OT 仅用 project_lifecycle(OT.stage),禁止逐条 build_task_ui_state; 不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。 """ @@ -53,10 +55,14 @@ from app.models import ( ShippingOrderReviewStream, ShippingOrderIntake, ShippingNotice, + ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, ) +from app.services.shipping_notice.line_inventory_match_projection import ( + inventory_rpa_is_running as _inventory_rpa_is_running, +) def _safe_filename(value: Any) -> str | None: @@ -272,6 +278,9 @@ def _project_case_automation_status( } # [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。 + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) job = None latest = None draft = getattr(case, 'current_draft', None) @@ -324,7 +333,7 @@ def _project_case_automation_status( 'can_build': can_build, 'job_id': int(job.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed': # 旧 Job(改造前写入)可能没有 retryable;缺失时按失败即停止处理。 result = latest.result_json if isinstance(latest.result_json, dict) else {} raw_retryable = result.get('retryable') @@ -355,7 +364,7 @@ def _project_case_automation_status( 'error_code': result.get('error_code') or blocking_reason, 'retry_of_job_id': int(latest.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'succeeded', 'success', 'completed'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded': return { 'status': 'completed', 'retryable': False, @@ -428,53 +437,14 @@ def _schema_fields(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]: return fields -def _field_lineage_index(case: ShippingOrderReviewCase) -> dict[tuple[str, str], dict[str, Any]]: - """ - 从关联 Extraction 或 Unit 结果索引派生血缘,键为 (line_key, field_code)。 - - 核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json.field_lineage; - 否则回退 Unit.result_json.field_lineage。仅保留脱敏后的来源元数据。 - """ - rows: list[Any] = [] - candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None - extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None - if extraction_id: - extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) - normalized = extraction.normalized_result_json if extraction is not None and isinstance( - extraction.normalized_result_json, dict, - ) else {} - rows = list(normalized.get('field_lineage') or []) - if not rows and case.unit is not None and isinstance(case.unit.result_json, dict): - rows = list(case.unit.result_json.get('field_lineage') or []) - index: dict[tuple[str, str], dict[str, Any]] = {} - for item in rows: - if not isinstance(item, dict): - continue - line_key = str(item.get('line_key') or '').strip() - field_code = str(item.get('field_code') or '').strip() - if not field_code: - continue - index[(line_key, field_code)] = { - 'value_source': str(item.get('value_source') or 'derived'), - 'rule_id': item.get('rule_id'), - 'skip_reason': item.get('skip_reason'), - 'source_field_code': item.get('source_field_code'), - } - return index - - def _resolve_field_meta( *, container: dict[str, Any], field_id: str, field_code: str, - lineage_index: dict[tuple[str, str], dict[str, Any]], - line_key: str | None = None, ) -> dict[str, Any]: """ - 合并草稿 values 与派生血缘,投影字段值来源元数据。 - - 优先级:manual_override / manual(含 locked、覆盖原因)→ derived/skipped 血缘 → machine。 + 投影草稿 values 的来源元数据;项次由系统生成,不投影派生规则血缘。 """ values = container.get('values') if isinstance(container.get('values'), dict) else {} entry = values.get(field_id) if isinstance(values.get(field_id), dict) else None @@ -492,17 +462,6 @@ def _resolve_field_meta( if entry.get('override_reason_text'): meta['override_reason_text'] = str(entry.get('override_reason_text')) return meta - lineage = lineage_index.get((str(line_key or ''), field_code)) - if lineage is not None: - return { - 'value_source': str(lineage.get('value_source') or 'derived'), - 'locked': False, - 'derivation': { - 'rule_id': lineage.get('rule_id'), - 'skip_reason': lineage.get('skip_reason'), - 'source_field_code': lineage.get('source_field_code'), - }, - } return {'value_source': 'machine', 'locked': False} @@ -510,8 +469,6 @@ def _project_draft_container( container: dict[str, Any] | None, *, scope_fields: list[dict[str, Any]], - lineage_index: dict[tuple[str, str], dict[str, Any]], - line_key: str | None = None, ) -> dict[str, Any]: """在保留原草稿结构基础上附加 field_meta,供复核 UI 展示来源徽章。""" payload = dict(container or {}) @@ -525,8 +482,6 @@ def _project_draft_container( container=payload, field_id=field_id, field_code=field_code, - lineage_index=lineage_index, - line_key=line_key, ) payload['field_meta'] = field_meta return payload @@ -710,7 +665,6 @@ def serialize_review_case( schema_fields = _schema_fields(run) header_fields = [item for item in schema_fields if item.get('scope') == 'header'] line_fields = [item for item in schema_fields if item.get('scope') == 'line'] - lineage_index = _field_lineage_index(case) if draft is not None else {} projected_draft = None llm_suggestions: list[dict[str, Any]] = [] if draft is not None: @@ -720,14 +674,11 @@ def serialize_review_case( 'header_values': _project_draft_container( dict(draft.header_values_json or {}), scope_fields=header_fields, - lineage_index=lineage_index, ), 'lines': [ _project_draft_container( dict(line) if isinstance(line, dict) else {}, scope_fields=line_fields, - lineage_index=lineage_index, - line_key=str((line or {}).get('line_key') or '') if isinstance(line, dict) else None, ) for line in raw_lines ], @@ -956,9 +907,9 @@ def serialize_review_case( ) order_data_version = None - confirmed_notice = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None - if confirmed_notice is not None: - order_data_version = int(confirmed_notice.order_data_version or 1) + confirmed_order_task = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None + if confirmed_order_task is not None: + order_data_version = int(getattr(confirmed_order_task, 'order_data_version', None) or 1) if is_admin and formal_ot.get('task_missing'): technical_progress = { @@ -990,10 +941,8 @@ def serialize_review_case( # [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。 # waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。 - auto_status = str((automation or {}).get('status') or '').strip().lower() - inventory_rpa_running = auto_status in { - 'processing', 'queued', 'automating', 'running', - } + # 库存 RPA 运行态必须来自逐源 Attempt;阶段自动推进 Job 与库存 RPA 解耦。 + inventory_rpa_running = _inventory_rpa_is_running(formal_ot.get('task')) source_labels: dict[str, str] = {} if isinstance(validation_snapshot, dict): raw_labels = validation_snapshot.get('inventory_source_labels') or {} @@ -1052,7 +1001,11 @@ def serialize_review_case( 'formal_editable_field_ids': ( list_editable_formal_field_ids( schema_fields, - excel_ready=is_excel_ready_for_task(confirmed_notice) if confirmed_notice is not None else False, + excel_ready=( + is_excel_ready_for_task(confirmed_order_task) + if confirmed_order_task is not None + else False + ), ) if str(case.status or '') == 'confirmed' else [] @@ -1068,6 +1021,38 @@ def serialize_review_case( } +def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] | None: + """ + 从会话级批量缓存取当前 Gate 码,供队列 lifecycle 在 OT.stage 为旧 step 码时兜底。 + + Args: + case: 当前复核 Case。 + + Returns: + ``{'gate_code': ...}`` 或 None(无 Execution / 缓存未就绪时)。 + """ + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if not isinstance(cache, dict) or getattr(case, 'id', None) is None: + return None + execution = (cache.get('execution_by_case_id') or {}).get(int(case.id)) + if execution is None: + return None + gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower() + if gate_code: + return {'gate_code': gate_code} + gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or [] + for gate in gates: + status = str(getattr(gate, 'status', '') or '').strip().lower() + if status not in { + 'blocked_manual', 'blocked_retryable', 'waiting_external', 'running', 'pending', + }: + continue + code = str(getattr(gate, 'gate_code', '') or '').strip().lower() + if code: + return {'gate_code': code} + return None + + def _serialize_review_case_summary( case: ShippingOrderReviewCase, *, @@ -1076,7 +1061,11 @@ def _serialize_review_case_summary( intakes_by_no: dict[str, ShippingOrderIntake] | None = None, drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None, ) -> dict[str, Any]: - """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" + """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。 + + 正式 OT 的五阶段:优先 OT.stage → project_lifecycle;旧 step* stage 不在映射表时 + 用批量缓存的 current Gate 兜底。禁止调用 build_task_ui_state。 + """ draft = ( drafts_by_id.get(int(case.current_draft_id)) if drafts_by_id is not None and case.current_draft_id @@ -1103,19 +1092,34 @@ def _serialize_review_case_summary( # 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。 lifecycle_stage = 'intake_parse' lifecycle_entries: list[dict[str, str]] = [] + # 正式任务身份:与左侧文件导航共用同一份来源(选法 2),供前端在正式任务下游阶段 + # 解耦对「复核 Case 全量快照」的依赖,按阶段懒加载复核编辑器数据。 + confirmed_task_no = None + has_formal_ot = False # 接收解析是无 Candidate Case 的独立处置面,不属于订单生命周期入口; # 前端只能以此显式授权读取当前 Case 的解析上下文,不能据此开放订单复核。 intake_parse_authorized = False candidate_is_reviewable = False if case.confirmed_task_id: + from app.services.shipping_notice.lifecycle_projection import project_lifecycle from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot - from app.services.shipping_notice.ui_state import build_task_ui_state + # 队列摘要只需五阶段 lifecycle;禁止走 build_task_ui_state(会拉 Gate/summary/ + # 动作全量,会话多 OT 时 N 倍放大到数秒)。正式 OT 已存在即开放候选上下文入口。 + # OT.stage 若仍是历史 step* 码,project_lifecycle 会忽略它并改用 current_gate 兜底。 formal_ot = resolve_formal_ot(case) if formal_ot.get('has_formal_ot'): - task_ui_state = build_task_ui_state(formal_ot['task']) - lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage) - lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or []) + task = formal_ot['task'] + confirmed_task_no = str(getattr(task, 'task_no', None) or '').strip() or None + has_formal_ot = True + lifecycle = project_lifecycle( + current_gate=_queue_current_gate_hint(case), + blocking_reason=None, + has_candidate_context=True, + processing_stage=getattr(task, 'stage', None), + ) + lifecycle_stage = str(lifecycle.get('lifecycle_stage') or lifecycle_stage) + lifecycle_entries = list(lifecycle.get('lifecycle_entries') or []) else: from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate @@ -1162,6 +1166,9 @@ def _serialize_review_case_summary( # 与批次中心 / 任务中心同义;前端不得再根据 Case status 或 stage 推断入口。 'lifecycle_entries': lifecycle_entries, 'intake_parse_authorized': intake_parse_authorized, + # 正式任务身份(选法 2):供工作台在此阶段懒加载复核编辑器,不再反推复核 Case。 + 'confirmed_task_no': confirmed_task_no, + 'has_formal_ot': has_formal_ot, } @@ -1259,7 +1266,7 @@ def _load_review_case_summary_batch( for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all() } if draft_ids else {} if task_ids: - ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all() + ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(task_ids)).all() intake_nos = { str(intake_snapshot.get('intake_no') or '').strip().upper() for case, run in rows diff --git a/backend/app/services/shipping_notice/order_review_reservation_service.py b/backend/app/services/shipping_notice/order_review_reservation_service.py index f103b81f..a7b127f6 100644 --- a/backend/app/services/shipping_notice/order_review_reservation_service.py +++ b/backend/app/services/shipping_notice/order_review_reservation_service.py @@ -112,7 +112,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, if not isinstance(proj, dict): continue effective = str(proj.get('effective_reservation_id') or '').strip() or None - line_key = str(proj.get('line_key') or '').strip() or None + draft_line_id = str(proj.get('draft_line_id') or '').strip() or None block_reason = str(proj.get('block_reason') or '').strip() or None line_reservation_issue = next( ( @@ -133,7 +133,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, ) lines_out.append({ 'line_index': idx, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'effective_reservation_id': effective, 'can_build': bool(proj.get('can_build', True)), # Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。 @@ -150,7 +150,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, rid = _current_line_reservation_id(line, reservation_field_id) lines_out.append({ 'line_index': idx, - 'line_key': str(line.get('line_key') or '').strip() or None, + 'draft_line_id': str(line.get('draft_line_id') or '').strip() or None, 'effective_reservation_id': rid, 'can_build': True, 'block_reason': None, @@ -170,7 +170,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, 'severity': str(item.get('severity') or 'blocking')[:32], 'message': str(item.get('message') or '')[:240] or None, 'line_index': item.get('line_index'), - 'line_key': item.get('line_key'), + 'draft_line_id': item.get('draft_line_id'), 'field_code': item.get('field_code') or 'reservation_id', } for item in issues[:20] diff --git a/backend/app/services/shipping_notice/order_review_service.py b/backend/app/services/shipping_notice/order_review_service.py index dda4cfa4..00d05b34 100644 --- a/backend/app/services/shipping_notice/order_review_service.py +++ b/backend/app/services/shipping_notice/order_review_service.py @@ -202,7 +202,7 @@ def _initial_draft_payload( order = orders[0] header = {'machine_fields': list(order.get('header_fields') or [])} lines = [ - {'line_key': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])} + {'draft_line_id': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])} for index, line in enumerate(order.get('lines') or []) if isinstance(line, dict) ] _restore_machine_source_case(header, lines) @@ -499,7 +499,7 @@ def build_llm_suggestion_request_context( user_id: int, case_no: str, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, ) -> dict[str, Any]: """ 为 LLM 建议请求绑定 Case、Document 与冻结 Schema 字段上下文。 @@ -510,7 +510,7 @@ def build_llm_suggestion_request_context( user_id: Case 属主。 case_no: 复核 Case 编号。 field_id: 目标 field_id。 - line_key: 明细行键。 + draft_line_id: 明细行键。 Returns: 含 case_no、document_id、draft_version、field 的上下文 dict。 @@ -536,6 +536,6 @@ def build_llm_suggestion_request_context( 'field_id': str(field_id), 'field_code': str(field.get('field_code') or field_id), 'scope': str(field.get('scope') or ''), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'schema_version_id': int(case.run.schema_version_id), } diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index f287239c..a0506d34 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -3,13 +3,14 @@ backend/app/services/shipping_notice/order_review_workbench_projection.py 用途:复核工作台 Case 投影的阶段分层辅助——正式 OT 判定、用户态 profile_match、 field_completeness、completed_checks、OT 当前阶段与 automation 责任方; - 以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐。 + 以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐; + 另提供 Job.status → 单一 outcome 投影(project_job_status_outcome)。 依赖:ShippingNotice、ShippingOrderReviewCase、Job、order_review_draft_service._current_value、 process_gate_contract、processing_projection_invariants、queue_service 域常量。 逻辑:由 order_review_projection.serialize_review_case / shipping_processing_projection / order_review_fulfillment_decision_service 调用;不新建状态模型; project_stage_for_task 与 project_post_ot_automation_from_job 为 Case/Progress 同源; - 禁止前端自行拼接里程碑。 + Job 成功/失败同义词只在本模块翻译,调用方只判 succeeded/failed。 """ from __future__ import annotations @@ -18,7 +19,38 @@ from datetime import datetime from typing import Any from app import db -from app.models import ShippingNotice, ShippingOrderReviewCase +from app.models import ShippingNotice, ShippingOrderReviewCase, ShippingOrderTask + +# Job 库内成功/失败词 → 单一 outcome;仅本模块持有 synonym 袋,禁止外溢。 +JOB_FAILURE_STATUS_TOKENS: frozenset[str] = frozenset({'failed', 'dead'}) +JOB_SUCCESS_STATUS_TOKENS: frozenset[str] = frozenset({'succeeded', 'success', 'completed'}) + + +def project_job_status_outcome(raw_status: str | None) -> str: + """将 Job.status 库内词投影为单一 outcome。 + + 核心逻辑:failed/dead → failed;succeeded/success/completed → succeeded; + queued / running|processing 原样归类。调用方只允许 ``== 'failed'`` / ``== 'succeeded'``。 + + Args: + raw_status: Job.status 原值。 + + Returns: + failed | succeeded | queued | running | 其它小写透传 | 空串。 + """ + status = str(raw_status or '').strip().lower() + if not status: + return '' + if status in JOB_FAILURE_STATUS_TOKENS: + return 'failed' + if status in JOB_SUCCESS_STATUS_TOKENS: + return 'succeeded' + if status == 'queued': + return 'queued' + if status in {'running', 'processing'}: + return 'running' + return status + # 正式 OT 创建后不得再作为「当前人工阻断」的建单前 Gate。 _PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({ @@ -65,7 +97,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 判定 Case 是否已绑定可读的正式 OT。 - 核心逻辑:唯一判据为 confirmed_task_id 指向存在且 task_no 有效的 ShippingNotice; + 核心逻辑:唯一判据为 confirmed_task_id 指向存在且 task_no 有效的 ShippingOrderTask; Case.status=confirmed 不能单独证明 OT 存在。 Args: @@ -75,7 +107,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]: { has_formal_ot: bool, task_missing: bool, - task: ShippingNotice | None, + task: ShippingOrderTask | None, task_no: str | None, task_id: int | None, } @@ -89,7 +121,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]: 'task_no': None, 'task_id': None, } - task = db.session.get(ShippingNotice, int(task_id)) + task = db.session.get(ShippingOrderTask, int(task_id)) if task is None: return { 'has_formal_ot': False, @@ -441,17 +473,33 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str } task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None - from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import ( + has_verified_upload_success, + latest_export_artifact, + latest_upload_attempt, + ) verified_upload_success = has_verified_upload_success(task) - upload_status = getattr(task, 'upload_status', None) + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + upload_status = getattr(latest_upload_attempt(task), 'status', None) upload_status = upload_status.strip().lower() if isinstance(upload_status, str) else '' - export_file_path = getattr(task, 'export_file_path', None) - match_status = getattr(task, 'match_status', None) - inventory_lines = getattr(task, 'inventory_lines_json', None) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + export_file_path = getattr(latest_export_artifact(task), 'file_path', None) + if isinstance(task, ShippingOrderTask): + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_for_task, + has_ready_inventory_file_for_task, + ) + + has_match = bool(current_inventory_matches_for_task(task)) + has_inventory = has_ready_inventory_file_for_task(task) + else: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + match_status = aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) + has_match = bool(match_status) + has_inventory = has_ready_inventory_file_for_task(task) has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) - has_match = isinstance(match_status, str) and bool(match_status.strip()) - has_inventory = isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) progress_state = ( 'uploaded' if verified_upload_success else 'export_ready' if has_export @@ -531,11 +579,11 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str **_job_fields(active), } - # [STEP 2] 最近 Job:failed/dead,或 success 但 OT 未推进。 + # [STEP 2] 最近 Job:failed,或 succeeded 但 OT 未推进。 if latest is not None: - latest_status = str(latest.status or '').strip().lower() + latest_outcome = project_job_status_outcome(getattr(latest, 'status', None)) fields = _job_fields(latest) - if latest_status in {'failed', 'dead'}: + if latest_outcome == 'failed': exhausted = _attempts_exhausted(latest) return { 'status': 'manual_fallback' if exhausted else 'failed', @@ -546,7 +594,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str 'reason_code': fields.get('error_code') or 'auto_progress_job_failed', **fields, } - if latest_status in {'succeeded', 'success', 'completed'}: + if latest_outcome == 'succeeded': # Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。 if progress_state in {'', 'not_started'}: exhausted = _attempts_exhausted(latest) @@ -642,21 +690,35 @@ def project_stage_for_task( from app.services.shipping_notice.processing_projection_invariants import ( map_notice_to_processing_status_stage, ) + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task - from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import ( + has_verified_upload_success, + latest_export_artifact, + ) # 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影 # 复用同一成功谓词,否则同一任务会在不同入口出现“已完成/待上传”分叉。 + owner = task + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task verified_upload_success = has_verified_upload_success(task) - raw_upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() + if isinstance(owner, ShippingOrderTask): + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(getattr(owner, 'id', None)).values()) + has_task_match = bool(match_facts) + else: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + has_task_match = bool(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None))) progress_state = ( 'uploaded' if verified_upload_success - else 'export_ready' if getattr(task, 'export_file_path', None) - else 'matched' if getattr(task, 'match_status', None) - else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) + else 'export_ready' if getattr(latest_export_artifact(task), 'file_path', None) + else 'matched' if has_task_match + else 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'not_started' ) - current_step = str(getattr(task, 'current_step', None) or '').strip() or None + current_step = str(getattr(owner, 'current_step', None) or '').strip() or None def _with_label(code: str, *, source: str) -> dict[str, Any]: # order_creating 技术阶段码保留;用户可见文案键固定 waiting_system_start。 @@ -675,7 +737,8 @@ def project_stage_for_task( # freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。 if progress_state == 'uploaded': return _with_label('completed', source='notice_terminal') - if raw_upload_status in {'uploaded', 'succeeded', 'success'}: + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + if project_notice_upload_status(task) == 'uploaded': return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 @@ -685,12 +748,6 @@ def project_stage_for_task( if has_app_context(): if getattr(task, 'order_task_id', None): order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) - if order_task is None and getattr(task, 'id', None): - order_task = ( - ShippingOrderTask.query.filter_by(shipping_notice_id=int(task.id)) - .order_by(ShippingOrderTask.id.desc()) - .first() - ) except Exception: # noqa: BLE001 — 单元测试无 Flask 上下文时跳过 OT 查询 order_task = None ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else '' diff --git a/backend/app/services/shipping_notice/order_schema/derivation_engine.py b/backend/app/services/shipping_notice/order_schema/derivation_engine.py deleted file mode 100644 index 2ccc7613..00000000 --- a/backend/app/services/shipping_notice/order_schema/derivation_engine.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -services/shipping_notice/order_schema/derivation_engine.py - -用途:执行 Schema 级字段派生规则(首期 copy_if_empty),供模拟与运行时共用。 -依赖:field_rules(规则归一化与 line_no 格式)、统一 ValidationError。 -逻辑:仅处理启用中的 line→line 规则;目标非空/来源空/格式非法时记录跳过原因; - 不写库;调用方负责持久化与审计。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.order_schema.field_rules import ( - derivation_rules_checksum, - is_valid_line_no_value, - normalize_derivation_rules, -) - - -def apply_derivation_rules_to_lines( - lines: list[dict[str, Any]], - rules: list[dict[str, Any]] | None, - *, - locked_targets: set[tuple[int, str]] | None = None, -) -> dict[str, Any]: - """ - 对明细行集合执行派生规则,返回派生后行与逐行结果摘要。 - - 核心逻辑:仅启用规则生效;copy_if_empty 仅在目标为空时复制来源; - 目标已锁定(人工覆盖)时跳过;来源缺失或目标格式非法时跳过。 - - Args: - lines: 明细字段字典列表(按行可变副本由本函数新建)。 - rules: Schema definition_json.derivation_rules 或草稿规则。 - locked_targets: 可选 ``{(line_index, field_code)}`` 人工锁定集合。 - - Returns: - ``{lines, results, rules_checksum, derived_count, skipped_count}``; - ``results`` 每项含 line_index、rule_id、status(derived|skipped)、skip_reason、 - source/target 前后值。 - """ - normalized = normalize_derivation_rules(rules, adopted_line_field_codes=None) - checksum = derivation_rules_checksum(normalized) - enabled = [rule for rule in normalized if rule.get('enabled')] - output_lines = [dict(line) for line in lines] - results: list[dict[str, Any]] = [] - locks = locked_targets or set() - - for line_index, line in enumerate(output_lines): - for rule in enabled: - source_code = str(rule['source_field_code']) - target_code = str(rule['target_field_code']) - rule_id = str(rule['rule_id']) - before_target = line.get(target_code) - before_source = line.get(source_code) - entry: dict[str, Any] = { - 'line_index': line_index, - 'rule_id': rule_id, - 'source_field_code': source_code, - 'target_field_code': target_code, - 'strategy': rule['strategy'], - 'before_source': before_source, - 'before_target': before_target, - 'after_target': before_target, - 'status': 'skipped', - 'skip_reason': None, - } - if (line_index, target_code) in locks: - entry['skip_reason'] = 'manual_override_locked' - results.append(entry) - continue - if before_target not in (None, ''): - entry['skip_reason'] = 'target_not_empty' - results.append(entry) - continue - if before_source in (None, ''): - entry['skip_reason'] = 'source_empty' - results.append(entry) - continue - source_text = str(before_source).strip() - if target_code == 'line_no' and not is_valid_line_no_value(source_text): - entry['skip_reason'] = 'source_format_invalid' - results.append(entry) - continue - if rule['strategy'] != 'copy_if_empty': - entry['skip_reason'] = 'unsupported_strategy' - results.append(entry) - continue - line[target_code] = source_text - entry['after_target'] = source_text - entry['status'] = 'derived' - entry['skip_reason'] = None - results.append(entry) - - derived_count = sum(1 for item in results if item['status'] == 'derived') - skipped_count = sum(1 for item in results if item['status'] == 'skipped') - return { - 'lines': output_lines, - 'results': results, - 'rules': normalized, - 'rules_checksum': checksum, - 'derived_count': derived_count, - 'skipped_count': skipped_count, - } diff --git a/backend/app/services/shipping_notice/order_schema/field_rules.py b/backend/app/services/shipping_notice/order_schema/field_rules.py index 02d42447..a68dccee 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -1,18 +1,15 @@ """ backend/app/services/shipping_notice/order_schema/field_rules.py -用途:执行冻结订单 Schema 的通用字段归一化、validator,以及 Schema 级字段派生规则契约校验。 +用途:执行冻结订单 Schema 的通用字段归一化和 validator。 依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。 逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则; Header/Line Reservation 均可选,有效值由行优先回退头计算; - 单价等字段必须已经由显式视觉框或拆分规则提供单值;derivation_rules 仅允许 line→line。 + 单价等字段必须已经由显式视觉框或拆分规则提供单值;订单项次由系统按单据内顺序生成。 """ from __future__ import annotations -import hashlib -import json -import re from datetime import date, datetime from decimal import Decimal, InvalidOperation from typing import Any @@ -20,11 +17,7 @@ from typing import Any from app.core.errors import ValidationError from app.services.shipping_notice.reservation_id import validated_reservation_id -# Phase 0/1 派生规则契约常量。 -DERIVATION_STRATEGIES = frozenset({'copy_if_empty'}) -DERIVATION_ALLOWED_TARGETS = frozenset({'line_no'}) -DERIVATION_LINE_NO_PATTERN = re.compile(r'^\d{1,6}$') -DEFAULT_DERIVATION_RULE_ID = 'R-LINE-NO-FROM-CUSTOMER-PO' +# 硬切换后不再提供 Schema 派生规则;订单项次由系统按单据顺序生成。 def compute_effective_reservation_id( @@ -52,160 +45,21 @@ def compute_effective_reservation_id( ) -def default_derivation_rules() -> list[dict[str, Any]]: - """ - 返回新草稿默认派生规则(关闭状态)。 - - 核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False, - 避免未评审规则自动改写内部项次。 - - Returns: - 可写入 definition_json.derivation_rules 的规则列表。 - """ - return [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': False, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }] - - -def derivation_rules_checksum(rules: list[dict[str, Any]]) -> str: - """ - 计算派生规则稳定校验和,供发布冻结与审计引用。 - - Args: - rules: 已归一化的派生规则列表。 - - Returns: - SHA-256 hex 摘要。 - """ - payload = json.dumps(rules, ensure_ascii=False, sort_keys=True, separators=(',', ':')) - return hashlib.sha256(payload.encode('utf-8')).hexdigest() - - -def normalize_derivation_rules( - value: Any, - *, - adopted_line_field_codes: set[str] | None = None, -) -> list[dict[str, Any]]: - """ - 归一化并校验 Schema definition_json.derivation_rules。 - - 核心逻辑:仅允许 line→line;首期策略仅 copy_if_empty;目标仅 line_no; - 禁止自引用;同一启用目标只允许一条规则;来源/目标须属于已采用明细字段(若提供)。 - - Args: - value: 原始 derivation_rules(None 时返回默认关闭预置)。 - adopted_line_field_codes: 当前草稿已采用的明细 field_code 集合;None 表示跳过采用检查。 - - Returns: - 归一化后的规则列表。 - - Raises: - ValidationError: 结构、策略、循环或竞争冲突。 - """ - if value is None: - return default_derivation_rules() - if not isinstance(value, list): - raise ValidationError( - 'derivation_rules must be a list', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - ) - normalized: list[dict[str, Any]] = [] - enabled_targets: set[str] = set() - for index, raw in enumerate(value): - if not isinstance(raw, dict): - raise ValidationError( - 'derivation rule must be an object', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'index': index}, - ) - rule_id = str(raw.get('rule_id') or '').strip() or f'R-DERIVE-{index + 1}' - enabled = raw.get('enabled', False) - if not isinstance(enabled, bool): - raise ValidationError( - 'derivation rule enabled must be boolean', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - source = str(raw.get('source_field_code') or '').strip() - target = str(raw.get('target_field_code') or '').strip() - strategy = str(raw.get('strategy') or '').strip() - scope = str(raw.get('scope') or 'line').strip() - if scope != 'line': - raise ValidationError( - 'derivation rules only allow line scope', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - if strategy not in DERIVATION_STRATEGIES: - raise ValidationError( - 'unsupported derivation strategy', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'strategy': strategy}, - ) - if target not in DERIVATION_ALLOWED_TARGETS: - raise ValidationError( - 'derivation target is not allowed in this phase', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'target_field_code': target}, - ) - if not source or source == target: - raise ValidationError( - 'derivation source/target must differ and be non-empty', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - if adopted_line_field_codes is not None: - missing = {code for code in (source, target) if code not in adopted_line_field_codes} - if missing: - raise ValidationError( - 'derivation fields must be adopted line fields', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'missing_field_codes': sorted(missing)}, - ) - if enabled and target in enabled_targets: - raise ValidationError( - 'only one enabled derivation rule is allowed per target', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'target_field_code': target}, - ) - if enabled: - enabled_targets.add(target) - normalized.append({ - 'rule_id': rule_id, - 'enabled': enabled, - 'source_field_code': source, - 'target_field_code': target, - 'strategy': strategy, - 'scope': scope, - }) - return normalized - - -def is_valid_line_no_value(value: Any) -> bool: - """ - 校验内部项次格式:1–6 位数字,保留前导零。 - - Args: - value: 候选内部项次。 - - Returns: - 是否符合契约。 - """ - if value in (None, ''): - return False - return bool(DERIVATION_LINE_NO_PATTERN.fullmatch(str(value).strip())) - - def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: """按冻结字段类型解析候选值,同时保留原始文本大小写。 - `uppercase_trim` / `lowercase_trim` 仅可用于比较、索引和规则匹配,不能改写 - PDF/邮件证据对应的业务展示值;否则料号、客户名称、地址和币种会偏离原文件。 + 核心逻辑:按 value_type 做确定性解析;文本类 normalizer 不得改写展示值。 + 日期仅接受显式布局,禁止把自由文本猜成日期。 + + Args: + value: 原始候选值(PDF/邮件单元格或 Observation)。 + config: 冻结 Schema 字段配置(须含 value_type;可选 normalizer_key)。 + + Returns: + 规范化后的业务值;空输入返回 None。 + + Raises: + ValidationError: 类型无法按显式规则解析时失败。 """ if value in (None, ''): return None @@ -231,6 +85,9 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: # ISO date, so downstream validators receive one type. '%m/%d/%y', '%m-%d-%y', '%m.%d.%y', '%d-%b-%Y', '%d-%B-%Y', + # [PARAM_TUNING] 2026-09-08: EML 分配表 PO Date 常见 ``12-Jun-26``; + # 仅有四位年 ``%d-%b-%Y`` 时整行补充被 fail-closed 丢弃,库存源线索/预约号一并落空。 + '%d-%b-%y', '%d-%B-%y', ): try: return datetime.strptime(text, pattern).date() @@ -267,8 +124,6 @@ def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool: field_code = str(config.get('field_code') or '') if field_code == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value): return False - if field_code == 'line_no' and value not in (None, '') and not is_valid_line_no_value(value): - return False for key in config.get('validator_keys') or []: if key == 'non_empty' and value in (None, ''): return False diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 3ff40227..25b5115f 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -3,15 +3,15 @@ backend/app/services/shipping_notice/order_schema/runtime.py 用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。 依赖:订单 Schema 动态模型、standard_field_registry、ShippingOrderDocument、registry、 - derivation_engine、audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、 + audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、 pdf_priority_adjudication(阶段 2 PDF 优先冲突裁决)。 -逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue; +逻辑:提交时先验证原文证据和字段规则并投影;内部项次由系统按行顺序生成; Observation.source_type 按主 PDF / 其他 PDF / Excel / Word / 正文区分; 跨来源冲突时先尝试 PDF_PRIORITY_FIELD_POLICIES,未命中再回退 prefer_attachment/email; Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条; 仅 required 或 auto_create_key_field 字段可进入 blocked_fields; 可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单; - 必填门禁仅在派生后按最终投影判定; + 必填门禁按最终投影判定; published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。 """ @@ -43,13 +43,11 @@ from app.services.shipping_notice.context_fields.runtime import ( canonical_mail_context, persist_deterministic_context_fields, ) -from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches from app.services.shipping_notice.order_schema.field_rules import ( compute_effective_reservation_id, normalize_order_field_value, validate_order_field_value, ) -from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.pdf_priority_adjudication import choose_pdf_priority_value @@ -413,11 +411,19 @@ def _verified_email_supplement_observation( def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool: - """只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。""" + """ + 只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。 + + anchor_bbox 仅锚点定位字段携带;模板固定值区字段(无锚点标签)由解析器合法返回 + None,其冻结 value_bbox + 字符索引已是完整取值证据,不得因缺锚点丢弃观测, + 否则账款客户/地址等固定区头字段永远无法落库,下游客户识别将空转。 + """ + anchor_bbox = raw.get('anchor_bbox') return ( str(raw.get('source') or '') == 'pdf_coordinate' and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1 - and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict) + and (anchor_bbox is None or isinstance(anchor_bbox, dict)) + and isinstance(raw.get('value_bbox'), dict) and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices']) ) @@ -946,7 +952,7 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) - return result -def _persist_derived_line_field( +'''# Disabled legacy derivation helpers intentionally retained as inert source text. *, extraction: ShippingOrderExtraction, line: ShippingOrderLine, @@ -1034,7 +1040,6 @@ def _persist_derived_line_field( 'value': payload, 'reason_code': 'derived', 'rule_id': rule_id, - 'derivation_rules_checksum': rules_checksum, 'observation_ids': [], 'confidence': 1.0, } @@ -1104,6 +1109,7 @@ def _derivation_evidence_refs( return refs +''' def persist_dynamic_order( *, raw_order: dict[str, Any], @@ -1132,9 +1138,12 @@ def persist_dynamic_order( str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or [] if item.get('enabled', True) } + # line_no 是系统生成且只读的订单项次,不是解析出来的业务字段:不进 llm 字段裁决, + # 不落 FieldValue/Decision,只在 ShippingOrderLine.line_no 与 system_line_projections 体现。 configs = { field_id: item for field_id, item in all_configs.items() if item.get('collection_mode', 'llm_extraction') == 'llm_extraction' + and str(item.get('field_code') or '').strip() != 'line_no' } context_configs = [ item for item in all_configs.values() @@ -1196,7 +1205,8 @@ def persist_dynamic_order( line = ShippingOrderLine( extraction_id=extraction.id, position=position, - line_key=str(uuid.uuid4()), + line_no=position + 1, + draft_line_id=str(uuid.uuid4()), ) db.session.add(line) db.session.flush() @@ -1282,79 +1292,19 @@ def persist_dynamic_order( owning_gate_code='order_field_extraction', )) - # [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。 - derivation_outcome = apply_derivation_rules_to_lines( - line_projections, - (version.definition_json or {}).get('derivation_rules'), - ) - line_projections = derivation_outcome['lines'] + # [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。 field_lineage: list[dict[str, Any]] = [] - for item in derivation_outcome['results']: - line_index = int(item['line_index']) - line_obj = extraction.lines[line_index] if line_index < len(extraction.lines) else None - lineage_row = { - 'line_key': line_obj.line_key if line_obj is not None else None, - 'field_code': item['target_field_code'], - 'value_source': 'derived' if item['status'] == 'derived' else 'skipped', - 'rule_id': item['rule_id'], - 'rule_checksum': derivation_outcome['rules_checksum'], - 'skip_reason': item.get('skip_reason'), - 'before_value': item.get('before_target'), - 'after_value': item.get('after_target'), - 'source_field_code': item.get('source_field_code'), - 'source_value': item.get('before_source'), - } - field_lineage.append(lineage_row) - if item['status'] == 'derived' and line_obj is not None: - target_config = _config_by_line_field_code(all_configs, str(item['target_field_code'])) - if target_config is not None and item.get('after_target') not in (None, ''): - decisions.append(_persist_derived_line_field( - extraction=extraction, - line=line_obj, - config=target_config, - value=item.get('after_target'), - rule_id=str(item['rule_id']), - rules_checksum=str(derivation_outcome['rules_checksum']), - )) - event_type = 'FIELD_DERIVED' if item['status'] == 'derived' else 'FIELD_DERIVATION_SKIPPED' - evidence_refs = _derivation_evidence_refs( - extraction_id=int(extraction.id), - line_id=int(line_obj.id) if line_obj is not None else None, - source_field_code=str(item.get('source_field_code') or '') or None, - all_configs=all_configs, - ) - append_shipping_audit_event( - event_type=event_type, - aggregate_type='shipping_order_extraction', - aggregate_id=str(extraction.id), - intake_no=getattr(intake, 'intake_no', None), - actor_type='system', - actor_id='derivation_engine', - action='derive_line_field', - result='success' if item['status'] == 'derived' else 'ignored', - reason_code=item.get('skip_reason'), - evidence_refs=evidence_refs or None, - metadata={ - 'rule_id': item['rule_id'], - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], - 'field_code': item['target_field_code'], - 'line_key': lineage_row['line_key'], - 'source_field_code': item.get('source_field_code'), - 'skip_reason': item.get('skip_reason'), - 'schema_version_id': version.id, - }, - before={'previous_value': item.get('before_target'), 'value_source': 'machine'}, - after={ - 'new_value': item.get('after_target'), - 'value_source': 'derived' if item['status'] == 'derived' else 'skipped', - }, - ) - # [STEP 4] 关键字段完整性仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。 + # [STEP 4] 关键字段完整性按最终投影检查。 for config in all_configs.values(): if not field_may_block_process(config): continue code = str(config['field_code']) + # line_no 是系统生成且只读的订单项次(写入 ShippingOrderLine.line_no,并经 + # system_line_projections 输出);业务行投影不重复携带它,因此不得用“required + # 但业务投影缺失”把这一系统字段误判为缺失阻断。 + if code == 'line_no': + continue missing = False if config['scope'] == 'header' and code not in header: missing = True @@ -1405,11 +1355,12 @@ def persist_dynamic_order( 'blocks_current_action': str(code) in blocking_codes, }) - # 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。 + # 行级辅助投影:输出草稿身份、系统项次与有效 Reservation。 system_line_projections: list[dict[str, Any]] = [] for line, projection in zip(extraction.lines, line_projections): system_line_projections.append({ - 'line_key': line.line_key, + 'draft_line_id': line.draft_line_id, + 'line_no': int(line.line_no), 'effective_reservation_id': compute_effective_reservation_id( line_reservation_id=projection.get('reservation_id'), header_reservation_id=header.get('reservation_id'), @@ -1437,7 +1388,6 @@ def persist_dynamic_order( 'header': header, 'lines': line_projections, 'field_lineage': field_lineage, - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], } extraction.validation_result_json = { 'blocked_fields': blocked_unique, @@ -1447,19 +1397,16 @@ def persist_dynamic_order( extraction.status = 'needs_review' if blocked_unique else 'accepted' extraction.updated_at = datetime.utcnow() db.session.flush() - customer_matches = refresh_order_customer_matches(extraction, header) return { 'extraction': extraction, 'header': header, 'lines': line_projections, 'system_line_projections': system_line_projections, 'field_lineage': field_lineage, - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], 'blocked_fields': blocked_unique, 'findings': deduped_findings, 'observations': observations, 'decisions': decisions, - 'customer_matches': customer_matches, 'auto_create_key_field_thresholds': { str(item['field_code']): float(item['minimum_confidence']) for item in all_configs.values() diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py index f6ade775..95ae4a3e 100644 --- a/backend/app/services/shipping_notice/order_schema/service.py +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -3,8 +3,8 @@ backend/app/services/shipping_notice/order_schema/service.py 用途:管理唯一发货订单 Schema 的版本采用/发布与追加式配置审计;字段资产生命周期委托 field_asset_service。 依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、field_rules、registry、统一 AppError。 -逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、derivation_rules、 - task_edit_policy);乐观锁阻止覆盖;发布冻结快照并追加审计事件。 +逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、task_edit_policy); + 乐观锁阻止覆盖;发布冻结快照并追加审计事件。 """ from __future__ import annotations @@ -68,12 +68,6 @@ from app.services.shipping_notice.order_schema.registry import ( from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.order_schema.diff import compare_definitions -from app.services.shipping_notice.order_schema.field_rules import ( - default_derivation_rules, - derivation_rules_checksum, - normalize_derivation_rules, -) -from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines from app.services.shipping_notice.audit_service import append_shipping_audit_event SCHEMA_CODE = DEFAULT_SCHEMA_FAMILY_CODE @@ -836,7 +830,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]: 'raw_llm_output': _copy_json(extraction.raw_llm_output_json), 'normalized_result': _copy_json(extraction.normalized_result_json), 'validation_result': _copy_json(extraction.validation_result_json), - 'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines], + 'lines': [{'id': row.id, 'position': row.position, 'draft_line_id': row.draft_line_id} for row in lines], 'observations': [ identity(row.field_id) | { 'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id, @@ -1018,12 +1012,6 @@ def create_draft( definition if source else None, fallback=schema.auto_creation_policy_json, ) - # [STEP] 派生规则:复制来源时归一化;全新草稿预置关闭状态的默认规则。 - definition['derivation_rules'] = normalize_derivation_rules( - definition.get('derivation_rules') if source else None, - adopted_line_field_codes=None, - ) - definition['derivation_rules_checksum'] = derivation_rules_checksum(definition['derivation_rules']) version = ShippingOrderSchemaVersion( schema_id=schema.id, version=next_version, @@ -1123,6 +1111,23 @@ def save_draft( raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') before = _definition(version) ensure_standard_assets_seeded(actor_id=actor_id) + # line_no 是系统项次字段:调用方无需提交配置,服务端始终将其纳入 Schema。 + line_no_asset = ShippingOrderField.query.filter_by( + field_code='line_no', scope='line', asset_kind='system_standard', status='active', + ).one() + if not any( + isinstance(item, dict) and str(item.get('field_id') or '') == str(line_no_asset.id) + for item in configs + ): + configs = [*configs, { + 'field_id': str(line_no_asset.id), + 'enabled': True, + 'display_name': line_no_asset.display_name_default or '内部项次', + 'required': True, + 'normalizer_key': 'integer', + 'comparator_key': 'integer', + 'validator_keys': ['positive_integer'], + }] seen: set[str] = set() enabled_purposes: set[str] = set() normalized_fields: list[dict[str, Any]] = [] @@ -1241,34 +1246,36 @@ def save_draft( 'on_revalidation_failure': sanitized['on_revalidation_failure'], } normalized_fields.append(field_entry) + # line_no 是订单项次系统字段:Schema 必须包含且启用为必填,但不得开放人工编辑或派生配置。 + line_no_entries = [item for item in normalized_fields if item.get('field_code') == 'line_no' and item.get('scope') == 'line'] + if len(line_no_entries) != 1: + raise ValidationError( + 'line_no is required exactly once in schema fields', + code='SHIPPING.ORDER_SCHEMA_LINE_NO_REQUIRED', + ) + line_no_entry = line_no_entries[0] + line_no_entry['enabled'] = True + line_no_entry['required'] = True + line_no_entry['auto_create_key_field'] = False + line_no_entry['aliases'] = [] + line_no_entry['extraction_instruction'] = None + line_no_entry['task_edit_policy'] = { + 'editable': False, + 'editable_until': None, + 'change_effect': 'none', + 'on_revalidation_failure': 'block', + } if 'auto_creation_policy' in data: auto_creation_policy = _auto_creation_policy(data.get('auto_creation_policy')) else: auto_creation_policy = _resolve_auto_creation_policy_for_definition( before, fallback=version.schema.auto_creation_policy_json, ) - adopted_line_codes = { - str(item.get('field_code')) - for item in normalized_fields - if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line' - } - # 保存时未传 derivation_rules 则保留草稿既有规则;缺省时回退关闭预置。 - raw_derivation_rules = data['derivation_rules'] if 'derivation_rules' in data else before.get('derivation_rules') - derivation_rules = normalize_derivation_rules( - raw_derivation_rules if raw_derivation_rules is not None else default_derivation_rules(), - adopted_line_field_codes=adopted_line_codes if any( - rule.get('enabled') for rule in ( - raw_derivation_rules if isinstance(raw_derivation_rules, list) else default_derivation_rules() - ) - ) else None, - ) after = { 'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields, 'auto_creation_policy': auto_creation_policy, - 'derivation_rules': derivation_rules, - 'derivation_rules_checksum': derivation_rules_checksum(derivation_rules), } compile_table_header_contract(after) version.definition_json = after @@ -1334,21 +1341,6 @@ def publish( enabled_configs = _enabled_fields(definition) if not enabled_configs: raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') - # [STEP] 发布前再次归一化派生规则;启用中的规则要求来源/目标已采用。 - adopted_line_codes = { - str(item.get('field_code')) - for item in enabled_configs - if item.get('scope') == 'line' and item.get('field_code') - } - derivation_rules = normalize_derivation_rules( - definition.get('derivation_rules'), - adopted_line_field_codes=adopted_line_codes if any( - isinstance(rule, dict) and rule.get('enabled') - for rule in (definition.get('derivation_rules') or []) - ) else None, - ) - definition['derivation_rules'] = derivation_rules - definition['derivation_rules_checksum'] = derivation_rules_checksum(derivation_rules) version.definition_json = definition included_field_ids = {str(config.get('field_id')) for config in enabled_configs} previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first() @@ -1470,134 +1462,11 @@ def simulate_derivation( actor_id: int | None, request_id: str | None = None, ) -> dict[str, Any]: - """ - 对草稿或已发布 Schema 版本的派生规则做只读样本模拟。 - - 核心逻辑:优先使用请求体 derivation_rules,否则读版本 definition; - lines 可直接提交,或通过 sample_ref=`extraction:` 从历史 Extraction 加载明细投影; - 模拟前仅对历史 Extraction 样本剔除规则目标字段,避免已派生结果恒跳过; - 手工 JSON 保留目标字段以真实评估 copy_if_empty; - 写入 DERIVATION_SIMULATED 审计(不 commit),不改订单。 - - Args: - version_id: Schema 版本 ID。 - data: 含 lines 或 sample_ref(extraction:)、可选 derivation_rules。 - actor_id: 管理员 ID。 - request_id: 请求追踪 ID。 - - Returns: - 模拟结果摘要与逐行结果。 - - Raises: - ValidationError: lines / sample_ref 非法。 - NotFoundError: 版本或 Extraction 不存在。 - """ - from app.models import ShippingOrderExtraction - - _, version = _resolve_schema_for_version(version_id) - sample_ref = str(data.get('sample_ref') or '').strip() or None - raw_lines = data.get('lines') - sample_source: dict[str, Any] | None = None - - # [STEP] 支持可追溯样本:extraction: → normalized_result_json.lines - # 历史样本可能已含派生后的目标字段;模拟前剔除规则目标,避免 copy_if_empty 恒跳过。 - if sample_ref and sample_ref.startswith('extraction:'): - try: - extraction_id = int(sample_ref.split(':', 1)[1]) - except (TypeError, ValueError) as exc: - raise ValidationError( - 'sample_ref extraction id is invalid', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_INVALID', - ) from exc - extraction = db.session.get(ShippingOrderExtraction, extraction_id) - if extraction is None: - raise NotFoundError( - 'Derivation sample extraction not found', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_NOT_FOUND', - ) - normalized = extraction.normalized_result_json if isinstance(extraction.normalized_result_json, dict) else {} - loaded = list(normalized.get('lines') or []) - if not loaded or any(not isinstance(item, dict) for item in loaded): - raise ValidationError( - 'extraction sample has no usable line projections', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_EMPTY', - ) - raw_lines = loaded - sample_source = { - 'kind': 'extraction', - 'extraction_id': int(extraction.id), - 'schema_version_id': int(extraction.schema_version_id), - 'intake_id': int(extraction.intake_id), - 'status': extraction.status, - 'targets_stripped_for_simulate': True, - } - - if not isinstance(raw_lines, list) or any(not isinstance(item, dict) for item in raw_lines): - raise ValidationError( - 'lines must be a list of objects (or provide sample_ref=extraction:)', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SIMULATE_INVALID', - ) - definition = _definition(version) - rules = data.get('derivation_rules') if 'derivation_rules' in data else definition.get('derivation_rules') - normalized_rules = normalize_derivation_rules(rules if isinstance(rules, list) else None) - # 仅历史 Extraction 样本剔除目标字段;手工 JSON 保留原值以真实评估 copy_if_empty。 - strip_targets = bool(sample_source and sample_source.get('targets_stripped_for_simulate')) - if strip_targets: - target_codes = { - str(rule.get('target_field_code') or '') - for rule in normalized_rules - if rule.get('target_field_code') - } - simulate_lines = [] - for line in raw_lines: - cleaned = dict(line) - for code in target_codes: - cleaned.pop(code, None) - simulate_lines.append(cleaned) - else: - simulate_lines = [dict(line) for line in raw_lines] - outcome = apply_derivation_rules_to_lines(simulate_lines, normalized_rules) - append_shipping_audit_event( - event_type='DERIVATION_SIMULATED', - aggregate_type='shipping_order_schema_version', - aggregate_id=str(version.id), - actor_type='admin', - actor_id=actor_id, - request_id=request_id, - action='simulate_derivation', - result='success', - metadata={ - 'schema_version': version.version, - 'schema_version_status': version.status, - 'derivation_rules_checksum': outcome['rules_checksum'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'sample_ref': sample_ref, - 'sample_source': sample_source, - 'line_count': len(raw_lines), - }, - after={ - 'derivation_rules_checksum': outcome['rules_checksum'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'sample_ref': sample_ref, - }, + """派生规则已硬切换下线;项次由系统生成,接口统一返回业务错误。""" + raise ValidationError( + 'Schema derivation is disabled; line_no is system-generated', + code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED', ) - # 不在此 commit:由路由层统一提交,便于与样本读取等审计同事务。 - return { - 'schema_version_id': version.id, - 'schema_version': version.version, - 'schema_version_status': version.status, - 'rules_checksum': outcome['rules_checksum'], - 'rules': outcome['rules'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'results': outcome['results'], - 'lines_after': outcome['lines'], - 'sample_ref': sample_ref, - 'sample_source': sample_source, - 'mutates_orders': False, - } def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]: @@ -1637,4 +1506,4 @@ def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]: }) if len(items) >= capped: break - return {'items': items} \ No newline at end of file + return {'items': items} diff --git a/backend/app/services/shipping_notice/order_schema/table_contract.py b/backend/app/services/shipping_notice/order_schema/table_contract.py index 17426ac1..3ac40619 100644 --- a/backend/app/services/shipping_notice/order_schema/table_contract.py +++ b/backend/app/services/shipping_notice/order_schema/table_contract.py @@ -18,7 +18,7 @@ from app.core.errors import ValidationError TABLE_FIELD_CODES = frozenset({ - 'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number', + 'reservation_id', 'part_number', 'product_revision', 'customer_part_number', 'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom', 'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price', 'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate', @@ -36,10 +36,16 @@ class TableHeaderContract: def normalize_table_header(value: Any) -> str: - """以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。""" - # Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are - # distinct configured labels, so a permissive match cannot silently bind a column. + """以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。 + + Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are + distinct configured labels, so a permissive match cannot silently bind a column. + 额外把 camelCase 相邻词拆出空格(``manufacturerPN`` -> ``manufacturer PN``), + 使真实邮件/PDF 表头 ``manufacturerPN`` 能命中 Schema 的 ``Manufacturer PN`` 别名。 + """ text = unicodedata.normalize('NFKC', str(value or '')).strip() + # 在「小写/数字 后紧接大写」的边界插入空格,处理无分隔符的驼峰表头。 + text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", ' ', text) text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE) return re.sub(r'[_\s]+', ' ', text).strip() diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index 16c3bbf8..67335308 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -474,10 +474,16 @@ def ensure_stp_auto_create_for_case( ), } - # [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 + # [STEP] failed 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) latest = find_latest_stp_job(business_ref=idempotency_key) retry_of_job_id = None - if latest is not None and str(latest.status or '') in {'failed', 'dead', 'cancelled'}: + latest_status = str(getattr(latest, 'status', None) or '').strip().lower() if latest is not None else '' + if latest is not None and ( + project_job_status_outcome(latest_status) == 'failed' or latest_status == 'cancelled' + ): retry_of_job_id = int(latest.id) elif force_retry and latest is not None: retry_of_job_id = int(latest.id) diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index ddc5d92c..112ebee3 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -80,6 +80,68 @@ def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dic } +def _canonical_values_span( + fields: Any, span_codes: set[str], ids: dict[str, str], configs: dict[str, dict[str, Any]], +) -> set[Any]: + """收集字段跨多个同订单料号身份 code 的规范值集合(件号/客户件号交叉)。 + + 与匹配层 `part_number ∪ customer_part_number` 的裁决保持一致:邮件补充的 PN 列 + 值可能实为客户件号(MPN),只要命中 PDF 的任一料号身份就视为同一料号, + 禁止把「邮件 PN = PDF 客户件号」判成 `part_number` 字段冲突。 + + Args: + fields: 目标字段 Observation 列表(header 或 line)。 + span_codes: 视作同一身份的字段 code 集合(如 {'part_number','customer_part_number'})。 + ids: {field_code: field_id} 映射。 + configs: {field_code: 冻结 Schema 配置} 映射,用于各字段独立标准化。 + + Returns: + 跨这些 code 收集到的规范值集合。 + """ + if not isinstance(fields, list): + return set() + code_by_id = {str(field_id): code for code, field_id in ids.items()} + out: set[Any] = set() + for field in fields: + if not isinstance(field, dict): + continue + code = code_by_id.get(str(field.get('field_id') or '')) + if code not in span_codes: + continue + config = configs.get(code) + if config is None: + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict) and observation.get('value') not in (None, ''): + out.add(_canonical_field_value(observation.get('value'), config)) + return out + + +# 采购单号类字段:跨来源比较须与匹配层一致,用 PO 专用标准化(含前导零归一), +# 否则 0060208010 与 60208010 会被 Schema「lowercase_trim」误判为不同 PO 而制造冲突。 +_PO_CODES = {'customer_po_number', 'po_number'} + + +def _conflict_canonical(value: Any, field_code: str, config: dict[str, Any]) -> Any: + """返回冲突比较用的字段规范值;PO 类字段复用 PO 标准化,其余走 Schema 正常化。""" + if field_code in _PO_CODES: + return normalize_atomic_po_number(value).upper() + return _canonical_field_value(value, config) + + +def _conflict_canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]: + """收集字段冲突比较用的规范值集合;PO 类字段使用 _conflict_canonical。""" + if not isinstance(fields, list): + return set() + return { + _conflict_canonical(observation.get('value'), code, config) + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + } + + def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]: """返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。""" if not isinstance(fields, list): @@ -125,14 +187,21 @@ def _supplement_field_conflict( { 'source_type': 'pdf', 'raw_value': str(pdf_raw), - 'canonical_value': str(_canonical_field_value(pdf_raw, config)), + 'canonical_value': str(_conflict_canonical(pdf_raw, field_code, config)), 'document_id': pdf.get('document_id'), - 'evidence_ref': dict(pdf.get('evidence_ref') or {}), + # evidence_ref 必须保持 dict 契约(review/evidence 消费方按 dict 处理)。 + # 坐标 observation 的 evidence_ref 是字符串、layout_evidence 才是证据 dict; + # 直接用 dict(<字符串>) 会把字符串按字符拆成长度1序列而崩(dictionary update length 1)。 + 'evidence_ref': ( + pdf.get('layout_evidence') + if isinstance(pdf.get('layout_evidence'), dict) + else (pdf.get('evidence_ref') if isinstance(pdf.get('evidence_ref'), dict) else {}) + ), }, { 'source_type': 'email_body', 'raw_value': str(email_raw), - 'canonical_value': str(_canonical_field_value(email_raw, config)), + 'canonical_value': str(_conflict_canonical(email_raw, field_code, config)), 'document_id': email_document_id or None, 'evidence_ref': dict(email_evidence or {}), }, @@ -162,7 +231,7 @@ def _supplement_multi_value_conflict( sources.append({ 'source_type': 'email_body', 'raw_value': raw_value, - 'canonical_value': str(_canonical_field_value(raw_value, config)), + 'canonical_value': str(_conflict_canonical(raw_value, field_code, config)), 'document_id': email_document_id or None, 'evidence_ref': dict(evidence or {}), }) @@ -271,7 +340,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta raw_value = str(item.get(target_code) or '').strip() if raw_value: value_by_canonical.setdefault( - _canonical_field_value(raw_value, config), + _conflict_canonical(raw_value, target_code, config), (raw_value, item), ) values = {raw_value for raw_value, _ in value_by_canonical.values()} @@ -292,13 +361,23 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta field_id = ids.get(target_code) if not value or not field_id: continue - existing_values = _canonical_values( + same_code_values = _conflict_canonical_values( fields, target_code, {v: k for k, v in ids.items()}, config, ) - if existing_values: + if same_code_values: # PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略: # 保留 PDF 值,强制进入 Review 由人工裁决。 - if existing_values != {_canonical_field_value(value, config)}: + email_canonical = _conflict_canonical(value, target_code, config) + if target_code in part_codes: + # 件号/客户件号属同一料号身份:邮件值命中任一 PDF 料号即视为一致, + # 不因「邮件 PN 实为客户件号(MPN)」制造误判 `part_number` 冲突。 + conflicts_with_pdf = ( + email_canonical + not in _canonical_values_span(fields, part_codes, ids, configs) + ) + else: + conflicts_with_pdf = same_code_values != {email_canonical} + if conflicts_with_pdf: conflict = _supplement_field_conflict( field_code=target_code, config=config, diff --git a/backend/app/services/shipping_notice/order_task_service.py b/backend/app/services/shipping_notice/order_task_service.py index 62021249..74a66ed6 100644 --- a/backend/app/services/shipping_notice/order_task_service.py +++ b/backend/app/services/shipping_notice/order_task_service.py @@ -9,7 +9,7 @@ backend/app/services/shipping_notice/order_task_service.py 局部重识别走 replace_order_task_candidate_after_reparse(专用审计); sync_order_task_processing_state 统一写入 stage/status、递增 progress_version, 并强制写 order_task_progress_changed 审计; - 建单成功后按 candidate_id 定位 OT 再挂 shipping_notice_id(禁止误用 Run 根号串单); + 正式 ShippingNotice 通过 order_task_id 关联 OT;OT 不反向保存通知单指针。 GET 投影只读本表,禁止读路径创建。 """ @@ -146,7 +146,6 @@ def sync_order_task_processing_state( }, metadata={ 'extraction_run_id': getattr(order_task, 'extraction_run_id', None), - 'shipping_notice_id': getattr(order_task, 'shipping_notice_id', None), 'candidate_id': getattr(order_task, 'candidate_id', None), }, source=str(source or 'order_task_service'), @@ -442,11 +441,6 @@ def replace_order_task_candidate_after_review( 'order task candidate binding changed concurrently', code='SHIPPING_NOTICE.ORDER_TASK_CANDIDATE_MISMATCH', ) - if order_task.shipping_notice_id is not None: - raise ConflictError( - 'order task already linked to a shipping notice', - code='SHIPPING_NOTICE.ORDER_TASK_ALREADY_LINKED', - ) case_document_id = int(case.document_id) if getattr(case, 'document_id', None) else None new_document_id = ( @@ -938,7 +932,7 @@ def resolve_order_task_for_candidate(candidate_id: int | None) -> Optional[Shipp def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional[ShippingOrderTask]: """ - 建单成功后双向挂接 OT ↔ Notice。 + 将正式 Notice 单向挂接到 OT。 Args: order_task_no: OT 编号(须为该 Candidate 自己的 OT,禁止误用 Run 根号)。 @@ -957,15 +951,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional ) if row is None: return None - before = { - 'shipping_notice_id': row.shipping_notice_id, - 'candidate_id': row.candidate_id, - } - # 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以 - # ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。 - if row.shipping_notice_id is None: - row.shipping_notice_id = int(notice_id) - row.updated_at = datetime.utcnow() + before = {'candidate_id': row.candidate_id} from app.models import ShippingNotice notice = db.session.get(ShippingNotice, int(notice_id)) @@ -985,7 +971,6 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional reason_code='notice_created', before=before, after={ - 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, 'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None, }, diff --git a/backend/app/services/shipping_notice/order_task_stage_machine.py b/backend/app/services/shipping_notice/order_task_stage_machine.py index a1c87219..ebbbb93e 100644 --- a/backend/app/services/shipping_notice/order_task_stage_machine.py +++ b/backend/app/services/shipping_notice/order_task_stage_machine.py @@ -292,11 +292,19 @@ def sync_order_task_stage_for_candidate( return None # 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算; # 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。 - if ( - getattr(candidate, 'consumed_task_id', None) is not None - or getattr(ot, 'shipping_notice_id', None) is not None - ): + if getattr(candidate, 'consumed_task_id', None) is not None: return ot + # 已挂正式通知单:以 Notice→OT(ShippingNotice.order_task_id)反向关联为准, + # OT 本身不保存通知单指针。只要已有任意 Notice 指向该 OT,即说明 OT 已进入 + # 履约阶段,建单前资格阶段不再是权威事实:原样返回,禁止回退到确认前 stage。 + if getattr(ot, 'id', None) is not None: + bound_notice = ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(ot.id)) + .first() + ) + if bound_notice is not None: + return ot stage, status = resolve_pre_confirm_stage( candidate=candidate, evaluation=evaluation, @@ -328,7 +336,7 @@ def sync_order_task_stage_for_notice( Args: notice: 正式发货通知。 - order_task: 可选;缺省按 notice.order_task_id / ShippingOrderTask.shipping_notice_id。 + order_task: 可选;缺省按 notice.order_task_id 反查 OT。 Returns: 更新后的 OT;找不到时 None。 @@ -340,18 +348,13 @@ def sync_order_task_stage_for_notice( ot = order_task if ot is None and getattr(notice, 'order_task_id', None): ot = db.session.get(ShippingOrderTask, int(notice.order_task_id)) - if ot is None and getattr(notice, 'id', None): - ot = ( - ShippingOrderTask.query.filter_by(shipping_notice_id=int(notice.id)) - .order_by(ShippingOrderTask.id.desc()) - .first() - ) if ot is None: return None status, stage = map_notice_to_processing_status_stage(notice) # [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice # 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。 - active_execution_id = getattr(notice, 'active_process_execution_id', None) + # ProcessExecution 属于 OT;正式 Notice 不保存执行指针。 + active_execution_id = getattr(ot, 'active_process_execution_id', None) if active_execution_id is not None: from app.models import ShippingProcessExecution @@ -359,9 +362,16 @@ def sync_order_task_stage_for_notice( execution_status = str(getattr(execution, 'status', None) or '').strip().lower() gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower() gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code) - if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage: + # [FIX] current_gate_code 是正式履约事实。即使 execution.status 仍为 completed + # (历史遗留旧值或 Gate 状态在 `_refresh_execution_pointers` 刷新前被旁路写成 + # blocked),只要 current_gate_code 仍指向一个未通过 Gate,就不能让 OT.stage 滞留 + # completed 而与实际卡住环节矛盾:据此把该 Gate 阶段回写,并落 blocked。 + if gate_stage and execution_status in {'active', 'waiting_external', 'blocked'}: stage = gate_stage status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked' + elif gate_stage and execution_status == 'completed': + stage = gate_stage + status = 'blocked' if stage not in SHIPPING_PROCESSING_STAGES: stage = 'inventory_matching' return sync_order_task_processing_state( diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py index 18d9767a..01000925 100644 --- a/backend/app/services/shipping_notice/per_source_rpa_service.py +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -3,7 +3,8 @@ services/shipping_notice/per_source_rpa_service.py 用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。 依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、 - rpa.write_inventory_export_trigger_for_task(trigger 文件写入)、 + rpa.write_inventory_export_batch_trigger(批次 trigger 文件写入,单文件多源)与 + rpa.build_on_demand_inventory_trigger_source(逐源条目构造)、 inventory_snapshot_store(快照复用判断)。 逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层, 新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。 @@ -37,7 +38,10 @@ from app.services.shipping_notice.inventory_snapshot_store import ( find_latest_ready_snapshot, is_snapshot_fresh, ) -from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task +from app.services.shipping_notice.rpa import ( + build_on_demand_inventory_trigger_source, + write_inventory_export_batch_trigger, +) def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None: @@ -233,14 +237,6 @@ def _next_attempt_no( return base_no + int(subsequent_count) + 1 -def _trigger_filename(task_no: str, source_code: str, attempt_no: int) -> str: - """ - 新的 per-source trigger 文件名:SN-____A.trigger.json - 与 legacy 文件名(无 __SOURCE 后缀)并行不冲突,RPA Worker 按 __ 分割识别 source_code。 - """ - return f'SN-{task_no}__{source_code.upper()}__A{attempt_no}.trigger.json' - - def _snapshot_ready_for_source( source_code: str, *, @@ -304,6 +300,8 @@ def ensure_all_required_sources_prepared( *, mode: str = 'auto', session: Session | None = None, + allow_auto_retry: bool = True, + source_codes: list[str] | None = None, ) -> PerSourcePrepareResult: """ 遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。 @@ -316,12 +314,15 @@ def ensure_all_required_sources_prepared( b. 否则检查 (task, source) 当前最新 Attempt 状态: - queued/running → pending(仍在等待) - succeeded/consumed → 已 prepared - - failed 且 attempt_no < max_attempts → 触发下一 attempt(queued 新 run) - - failed 且 attempt_no ≥ max_attempts → failed(不自动再触发) - - 从未 attempt → 触发 attempt_no=1 + - 从未 attempt → 首次触发新 attempt(queued 新 run) + - failed/exhausted → 仅用户显式 retry_rpa 才触发下一 Attempt c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件 Args: + allow_auto_retry: 只读轮询开关。poll_inventory_preparation 等查询路径必须传 False: + 轮询只消费 Attempt 事实(快照复用/pending/failed 上报),禁止自动新建 Attempt。 + 无论此开关取值,失败后的重试都只能由用户显式动作(mode='retry_rpa')发起, + 避免 RPA Worker 离线时形成“失败→重试→再失败”的无人值守空转环。 task: 已冻结候选的任务(inventory_source_status ∈ STABLE)。 mode: 'auto' = Orchestrator 自动推进;'retry_rpa' = 用户显式强制重试(跳过复用快照)。 session: 可选 Session。 @@ -331,7 +332,17 @@ def ensure_all_required_sources_prepared( """ task_no = str(task.task_no or '').strip() sess = session or db.session - source_codes = task_frozen_inventory_source_codes(task) + # OT 级互斥:同一库存准备请求只能产生一个批次 trigger,避免并发点击为同一 OT 写出多个批次。 + if getattr(task, 'id', None) is not None: + try: + sess.query(type(task)).filter(type(task).id == int(task.id)).with_for_update().one() + except Exception: + # SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。 + pass + source_codes = [ + str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task)) + if str(code).strip() + ] if not source_codes: return PerSourcePrepareResult( task_no=task_no, all_prepared=False, @@ -344,6 +355,9 @@ def ensure_all_required_sources_prepared( prepared: list[str] = [] pending: list[str] = [] failed: list[str] = [] + # 本轮待触发源的单源条目与对应 Attempt;循环后合并写入单个批次 trigger。 + pending_payloads: list[dict[str, Any]] = [] + pending_attempts: list[ShippingTaskInventoryRpaAttempt] = [] for source_code in source_codes: rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code} @@ -362,7 +376,7 @@ def ensure_all_required_sources_prepared( # 题2B 服务层并发双保险:_latest_attempt 可能读到缓存/旧事务;此处在创建前重新 SELECT ... FOR UPDATE # 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt, # 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。 - if mode == 'retry_rpa' or (current_status == 'failed'): + if mode == 'retry_rpa' or current_status in {'failed', 'exhausted'}: from app.models.shipping_task_inventory_rpa_attempts import ( ShippingTaskInventoryRpaAttempt as _Attempt2, ) @@ -384,10 +398,29 @@ def ensure_all_required_sources_prepared( current_status = double_check.status att = double_check - if current_status in ('succeeded', 'consumed') and att and _attempt_ref_has_ready_snapshot(att, session=sess): + # 显式 retry_rpa 必须忽略历史成功 Attempt,即使其仍指向 ready 快照; + # 否则“重新获取库存”会被误判为已准备完成,既不创建新 RPA Attempt, + # 也不会写入新的 trigger 文件。 + if ( + mode != 'retry_rpa' + and current_status in ('succeeded', 'consumed') + and att + and _attempt_ref_has_ready_snapshot(att, session=sess) + ): prepared.append(source_code) continue + if current_status in {'failed', 'exhausted'} and mode != 'retry_rpa': + # 失败事实只能收口为可重试 Gate;自动推进与轮询不得把它转换为新 RPA Attempt。 + failed.append(source_code) + continue + + if not allow_auto_retry: + # [只读轮询] failed/从未触发的源只上报 failed 事实,由 Gate 收口为人工阻断; + # 新 Attempt 只能由用户显式重试路径(mode='retry_rpa')创建。 + failed.append(source_code) + continue + next_att_no = _next_attempt_no(task_no, source_code, session=sess) # [STEP 2c] 新建 Attempt + 写 trigger 文件 @@ -407,14 +440,7 @@ def ensure_all_required_sources_prepared( new_att.source_run_no = _per_source_run_no(new_att) sess.flush([new_att]) - trigger_fname = _trigger_filename(task_no, source_code, next_att_no) try: - # 复用旧 write_inventory_export_trigger_for_task 内部逻辑,但覆写其生成的文件名 - # (旧函数会按 task 级写 trigger;此处先调旧函数保证 payload 完整,再尝试重命名。) - # - # [T4 兼容策略] 先不修改 rpa.py 避免影响单源任务旧链路;RPA Worker 增加按 source_code 识别 - # trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A 后缀即可。 - # 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。 from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source from app.models import ShippingProcessExecution, ShippingProcessGate @@ -441,16 +467,15 @@ def ensure_all_required_sources_prepared( gate_id=gate_id, expected_warehouse_id=rpa_source.get('warehouse_id'), ) - # 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行 + # [STEP 2c] 仅构造单源条目不落盘;身份键(source_run_no/lease_token/candidate_set/ + # execution/gate)必须冻结在条目内,Worker 回调才能精确收口到本次 Attempt。 per_source_payload = { - 'schema_version': 'shipping_inventory_rpa.v2', 'mode': mode, 'attempt': next_att_no, 'attempt_no': next_att_no, 'source_code': source_code, 'source_run_no': new_att.source_run_no, 'callback_id': f'{new_att.source_run_no}:C1', - 'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}', 'lease_token': new_att.lease_token, # 回调身份必须与本次冻结版本/正式 Execution 绑定;Worker 只原样回传。 'candidate_set_id': getattr(task, 'active_inventory_candidate_set_id', None), @@ -459,22 +484,15 @@ def ensure_all_required_sources_prepared( 'expected_warehouse_id': rpa_source.get('warehouse_id'), 'per_source_attempt': True, } - trigger_result = write_inventory_export_trigger_for_task( - task_no, - dict(legacy_rpa_source, **{'source_code': source_code}), - payload=per_source_payload, + pending_payloads.append( + build_on_demand_inventory_trigger_source( + task_no, + dict(legacy_rpa_source, **{'source_code': source_code}), + body=per_source_payload, + ) ) - if not trigger_result: - # 没有真实文件就不能宣称 queued;否则 Gate 会显示等待 RPA,Worker 永远不会领取。 - new_att.status = 'failed' - new_att.error_code = 'trigger_not_written' - new_att.error_message = '库存 RPA trigger 文件未生成' - new_att.execution_phase = 'trigger_write_failed' - new_att.updated_at = datetime.utcnow() - failed.append(source_code) - else: - new_att.trigger_file_path = str(trigger_result) - pending.append(source_code) + pending.append(source_code) + pending_attempts.append(new_att) except Exception as exc: # pragma: no cover - RPA 环境异常 new_att.status = 'failed' new_att.error_code = 'trigger_write_error' @@ -484,6 +502,41 @@ def ensure_all_required_sources_prepared( finally: sess.flush([new_att]) + # [STEP 2d] 合并批次触发:本轮 ensure 的全部缺失源写入同一个 trigger 文件, + # Worker 单次登录逐源导出;批次写入失败时本轮全部 Attempt 置 failed—— + # 没有真实文件就不能宣称 queued,否则 Gate 会显示等待 RPA,Worker 永远不会领取。 + if pending_payloads: + batch_run_no = f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}" + batch_write_error = None + try: + trigger_path = write_inventory_export_batch_trigger( + batch_run_no, + pending_payloads, + payload={ + 'schema_version': 'shipping_inventory_rpa.v2', + 'trigger_type': 'on_demand', + 'task_no': task_no, + 'mode': mode, + 'per_source_attempt': True, + }, + ) + except Exception as exc: # pragma: no cover - RPA 环境异常 + trigger_path = None + batch_write_error = f'{type(exc).__name__}: {str(exc)[:500]}' + if trigger_path: + for att in pending_attempts: + att.trigger_file_path = str(trigger_path) + else: + for att in pending_attempts: + att.status = 'failed' + att.error_code = 'trigger_not_written' + att.error_message = batch_write_error or '库存 RPA trigger 文件未生成' + att.execution_phase = 'trigger_write_failed' + att.updated_at = datetime.utcnow() + failed.extend(pending) + pending.clear() + sess.flush() + summary = _attempts_summary(task_no, source_codes=source_codes, session=sess) all_ok = len(prepared) == len(source_codes) and not pending and not failed return PerSourcePrepareResult( @@ -624,7 +677,8 @@ def per_source_callback_handler( # [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态) terminal_statuses = {'completed', 'cancelled', 'failed_terminal'} - if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or str(getattr(task, 'upload_status', '') or '').strip().lower() in {'uploaded', 'succeeded', 'success'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or has_verified_upload_success(task): attempt.status = 'superseded' attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal') attempt.callback_payload_json = dict(callback_payload or {}) diff --git a/backend/app/services/shipping_notice/po_number.py b/backend/app/services/shipping_notice/po_number.py index 0568cea7..38627b10 100644 --- a/backend/app/services/shipping_notice/po_number.py +++ b/backend/app/services/shipping_notice/po_number.py @@ -22,6 +22,7 @@ _ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*") def normalize_po_number(value: Any) -> str: """ 标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。 + 纯数字 PO 前导零视为格式差异(0060208010 与 60208010 是同一张 PO),统一剥除,避免跨来源误判冲突。 """ text = str(value or "").strip() if not text: @@ -32,8 +33,8 @@ def normalize_po_number(value: Any) -> str: if upper.startswith("ZNB") and len(text) > 3: tail = text[3:].strip().lstrip("-_/ ") if tail.isdigit(): - return tail - return text + return tail.lstrip("0") or "0" + return text.lstrip("0") or "0" def normalize_atomic_po_number(value: Any) -> str: diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py index 099016f7..32d675ba 100644 --- a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -67,20 +67,20 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] raise ConflictError( 'Inventory not ready for post-OT wave', code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY', - details={'line_key': line.get('line_key'), 'inventory_status': line.get('inventory_status')}, + details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')}, ) if str(line.get('match_result') or '') != 'matched': raise ConflictError( 'Line match result does not allow fulfill', code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE', - details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')}, + details={'snapshot_line_id': line.get('snapshot_line_id'), 'match_result': line.get('match_result')}, ) is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage' if line.get('is_shortage') and not is_released_shortage: raise ConflictError( 'Line has inventory shortage', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', - details={'line_key': line.get('line_key')}, + details={'snapshot_line_id': line.get('snapshot_line_id')}, ) req = _parse_qty(line.get('required_qty')) avail = _parse_qty(line.get('available_qty')) @@ -88,19 +88,19 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] raise ConflictError( 'Line cannot fulfill complete quantity with current inventory facts', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', - details={'line_key': line.get('line_key')}, + details={'snapshot_line_id': line.get('snapshot_line_id')}, ) return req, avail -def _stable_line_keys(keys: list[str]) -> list[str]: - """稳定排序行键。""" - return sorted({str(k).strip() for k in keys if str(k).strip()}) +def _stable_snapshot_line_ids(ids: list[int]) -> list[int]: + """稳定排序冻结订单行 ID。""" + return sorted({int(item) for item in ids}) -def _line_keys_hash(keys: list[str]) -> str: - """行集合指纹。""" - payload = json.dumps(_stable_line_keys(keys), ensure_ascii=False, separators=(',', ':')) +def _snapshot_line_ids_hash(ids: list[int]) -> str: + """冻结订单行集合指纹。""" + payload = json.dumps(_stable_snapshot_line_ids(ids), ensure_ascii=False, separators=(',', ':')) return hashlib.sha256(payload.encode('utf-8')).hexdigest() @@ -112,7 +112,7 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple (单一 snapshot_id 或 None, fingerprint 字符串)。 """ ids: list[int] = [] - by_key = {str(item.get('line_key') or ''): item for item in lines} + by_key = {str(item.get('snapshot_line_id') or ''): item for item in lines} for key in keys: item = by_key.get(key) or {} raw = item.get('inventory_snapshot_id') @@ -131,14 +131,14 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple def _params_conflict( row: ShippingOrderReviewWaveIdempotency, *, - line_keys: list[str], + snapshot_line_ids: list[int], fingerprint: str, decision_source: str, ) -> bool: """同 key 参数是否与已存记录冲突。""" if str(row.decision_source or '') != str(decision_source): return True - if str(row.line_keys_hash or '') != _line_keys_hash(line_keys): + if str(row.snapshot_line_ids_hash or '') != _snapshot_line_ids_hash(snapshot_line_ids): return True if str(row.inventory_snapshot_fingerprint or '') != str(fingerprint): return True @@ -148,7 +148,7 @@ def _params_conflict( def create_post_ot_fulfillment_wave( *, case_no: str, - line_keys: list[str], + snapshot_line_ids: list[int], decision_source: str = 'system', actor_user_id: int | None = None, reason: str | None = None, @@ -162,21 +162,21 @@ def create_post_ot_fulfillment_wave( Args: case_no: Case 编号。 - line_keys: 本波次行键。 + snapshot_line_ids: 本波次冻结订单行 ID。 decision_source: system | user。 actor_user_id: 人工操作人;系统可为 None。 reason: 备注。 idempotency_key: 可选幂等键(独立表强约束)。 Returns: - wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment / + wave_no / task_no / notice_no / accepted_snapshot_line_ids / skipped_snapshot_line_ids / line_fulfillment / idempotency_row_id / idempotent_replay。 """ - keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] + keys = [str(int(k)) for k in (snapshot_line_ids or [])] if not keys: - raise ValidationError('line_keys required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY') + raise ValidationError('snapshot_line_ids required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY') if len(keys) != len(set(keys)): - raise ValidationError('Duplicate line_keys', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE') + raise ValidationError('Duplicate snapshot_line_ids', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE') source = str(decision_source or 'system').strip() if source not in {'system', 'user'}: raise ValidationError('Invalid decision_source', code='SHIPPING.REVIEW_DECISION_SOURCE_INVALID') @@ -197,12 +197,12 @@ def create_post_ot_fulfillment_wave( 'Formal OT required for post-OT fulfillment wave', code='SHIPPING.REVIEW_POST_OT_WAVE_REQUIRES_OT', ) - task: ShippingNotice = formal['task'] + task: ShippingOrderTask = formal['task'] projected = project_review_case_line_decisions(case) projected_lines = [item for item in list(projected.get('lines') or []) if isinstance(item, dict)] by_key = { - str(item.get('line_key') or ''): item + str(item.get('snapshot_line_id') or ''): item for item in projected_lines } snap_id, snap_fp = _snapshot_fingerprint(projected_lines, keys) @@ -217,7 +217,7 @@ def create_post_ot_fulfillment_wave( if existing is not None: if _params_conflict( existing, - line_keys=keys, + snapshot_line_ids=[int(k) for k in keys], fingerprint=snap_fp, decision_source=source, ): @@ -226,7 +226,7 @@ def create_post_ot_fulfillment_wave( code='SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT', details={ 'idempotency_key': idem_key, - 'existing_line_keys_hash': existing.line_keys_hash, + 'existing_snapshot_line_ids_hash': existing.snapshot_line_ids_hash, 'existing_snapshot_fingerprint': existing.inventory_snapshot_fingerprint, 'existing_decision_source': existing.decision_source, }, @@ -238,15 +238,15 @@ def create_post_ot_fulfillment_wave( return replay assigned = { - str(row.line_key) + str(int(row.snapshot_line_id)) for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all() } - accepted: list[str] = [] - skipped: list[str] = [] + accepted_snapshot_line_ids: list[str] = [] + skipped_snapshot_line_ids: list[str] = [] for key in keys: if key in assigned: - skipped.append(key) + skipped_snapshot_line_ids.append(key) continue line = by_key.get(key) if line is None: @@ -255,14 +255,14 @@ def create_post_ot_fulfillment_wave( raise ConflictError( 'Closed line cannot enter wave', code='SHIPPING.REVIEW_LINE_CLOSED', - details={'line_key': key}, + details={'snapshot_line_id': key}, ) _assert_fact_allows_fulfill(line) - accepted.append(key) + accepted_snapshot_line_ids.append(key) wave_no = None notice = None - if accepted: + if accepted_snapshot_line_ids: max_wave = ( db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no)) .filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id)) @@ -272,89 +272,89 @@ def create_post_ot_fulfillment_wave( from app.services.shipping_notice.order_review_confirmation_service import ( _persist_wave_lines_for_task, ) - from app.services.shipping_notice.export import _source_notice_for_order_facts - - source_notice = _source_notice_for_order_facts(task) - snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) - snapshot_line_ids = { + snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + selected_snapshot_line_ids = { int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id) - for key in accepted + for key in accepted_snapshot_line_ids if snapshot is not None and (by_key[key] or {}).get('line_index') is not None and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines) } - if len(snapshot_line_ids) != len(accepted): + if len(selected_snapshot_line_ids) != len(accepted_snapshot_line_ids): raise ConflictError( 'Selected review lines do not map to frozen order lines', code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING', ) - order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None - if order_task is None: - raise ConflictError( - 'Formal notice is not linked to an order task', - code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED', - ) + order_task = task # [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照; # 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。 - if task.customer_id is None: + from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts + + if customer_confirmation_facts(order_task)['customer_id'] is None: raise ConflictError( 'Formal notice customer is required before creating a fulfillment wave', code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED', ) - notice = ShippingNotice( - task_no=generate_task_no(), - order_task_id=int(order_task.id), - customer_id=task.customer_id, - customer_name_snapshot=task.customer_name_snapshot, - customer_short_code_snapshot=task.customer_short_code_snapshot, - user_id=task.user_id, - conversation_id=task.conversation_id, - source_type='post_ot_fulfillment_wave', - inventory_source_code=task.inventory_source_code, - inventory_connector_type=task.inventory_connector_type, - inventory_warehouse_id=task.inventory_warehouse_id, - inventory_source_status=task.inventory_source_status, - inventory_source_method=task.inventory_source_method, - inventory_source_config_version=task.inventory_source_config_version, - inventory_routing_fingerprint=task.inventory_routing_fingerprint, - inventory_snapshot_id=task.inventory_snapshot_id, - customer_resolution_status=task.customer_resolution_status, - customer_resolution_method=task.customer_resolution_method, - customer_identity_fingerprint=task.customer_identity_fingerprint, - customer_confirmed_by=task.customer_confirmed_by, - customer_confirmed_at=task.customer_confirmed_at, + from app.services.shipping_notice.shipping_notice_creation_service import ( + create_shipping_notice_after_inventory_gate, ) - db.session.add(notice) - db.session.flush() - notice.customer_resolution_status = 'confirmed' - replace_notice_lines_from_snapshot( - notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids, + notice = create_shipping_notice_after_inventory_gate( + order_task, + snapshot_line_ids=selected_snapshot_line_ids, + source_type='post_ot_fulfillment_wave', ) _persist_wave_lines_for_task( case=case, task=notice, - line_keys=accepted, + snapshot_line_ids=list(selected_snapshot_line_ids), wave_no=wave_no, revision_id=None, ) + # [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。 + from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_wave_notice_routing + + routing_result = freeze_wave_notice_routing(notice, source_notice=None) + if routing_result is None or not routing_result.source_codes: + raise ConflictError( + 'Inventory source routing is unresolved for selected fulfillment lines', + code='SHIPPING.REVIEW_LINE_INVENTORY_SOURCE_UNRESOLVED', + details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]}, + ) + db.session.flush() # [STEP 2] 写入/推进履约决定(含已在 wave 的幂等行) draft_lines = _draft_line_map(case) + draft_lines_by_index = { + int(row.get('_line_index')): row + for row in draft_lines.values() + if row.get('_line_index') is not None + } now = datetime.utcnow() for key in keys: line = by_key.get(key) or {} - current = _active_decision(case, key) + line_index = line.get('line_index') + draft_line = draft_lines_by_index.get(int(line_index)) if line_index is not None else None + draft_line_id = str( + (line or {}).get('draft_line_id') or (draft_line or {}).get('_draft_line_id') or '' + ).strip() + if not draft_line_id: + raise ConflictError( + 'Selected review line is missing draft identity', + code='SHIPPING.REVIEW_LINE_DRAFT_MAPPING_MISSING', + details={'snapshot_line_id': key}, + ) + current = _active_decision(case, draft_line_id) if current is not None and current.line_status in {'task_created', 'fulfilled'}: continue # [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中, # 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。 if ( - key in accepted + key in accepted_snapshot_line_ids and current is not None and current.decision_code == 'release_inventory_shortage' ): current.line_status = 'task_created' - current.task_id = int(notice.id) + current.task_id = int(order_task.id) current.wave_no = int(wave_no) if wave_no is not None else None current.updated_at = now continue @@ -365,20 +365,20 @@ def create_post_ot_fulfillment_wave( avail = str(line.get('available_qty') or '') or None row = ShippingOrderReviewLineDecision( review_case_id=int(case.id), - line_key=key, - line_index=(draft_lines.get(key) or {}).get('_line_index'), - decision_version=_next_version(case, key), + draft_line_id=draft_line_id, + line_index=line_index, + decision_version=_next_version(case, draft_line_id), decision_code=DECISION_FULFILL, decision_source=source, - line_status='task_created' if key in assigned or key in accepted else _STATUS_BY_DECISION[DECISION_FULFILL], + line_status='task_created' if key in assigned or key in accepted_snapshot_line_ids else _STATUS_BY_DECISION[DECISION_FULFILL], is_active=True, reason=str(reason or '').strip()[:2000] or None, required_qty=req, available_qty=avail, reservation_id=line.get('reservation_id'), part_number=line.get('part_number'), - task_id=int(notice.id) if key in accepted else int(task.id), - wave_no=wave_no if key in accepted else ( + task_id=int(order_task.id), + wave_no=wave_no if key in accepted_snapshot_line_ids else ( int(current.wave_no) if current is not None and current.wave_no is not None else None ), actor_user_id=int(actor_user_id) if actor_user_id is not None else None, @@ -392,14 +392,14 @@ def create_post_ot_fulfillment_wave( created_at=now, updated_at=now, ) - if key in accepted: + if key in accepted_snapshot_line_ids: row.line_status = 'task_created' row.wave_no = wave_no elif key in assigned: row.line_status = 'task_created' existing_wave = ( ShippingOrderReviewWaveLine.query - .filter_by(review_case_id=int(case.id), line_key=key) + .filter_by(review_case_id=int(case.id), snapshot_line_id=int((line or {}).get('snapshot_line_id') or key)) .first() ) if existing_wave is not None: @@ -418,11 +418,11 @@ def create_post_ot_fulfillment_wave( review_case_no=str(case.case_no), run_no=str(case.run.run_no) if case.run is not None else None, task_no=str(task.task_no), - before={'line_keys': keys}, + before={'snapshot_line_ids': [int(item) for item in keys]}, after={ 'wave_no': wave_no, - 'accepted_line_keys': accepted, - 'skipped_line_keys': skipped, + 'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids], + 'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids], 'decision_source': source, 'idempotency_key': idem_key, }, @@ -430,13 +430,13 @@ def create_post_ot_fulfillment_wave( result = { 'case_no': case.case_no, - 'task_no': notice.task_no if notice is not None else task.task_no, - 'task_id': int(notice.id) if notice is not None else int(task.id), + 'task_no': task.task_no, + 'task_id': int(task.id), 'review_case_id': int(case.id), 'wave_no': wave_no, - 'notice_no': notice.task_no if notice is not None else None, - 'accepted_line_keys': accepted, - 'skipped_line_keys': skipped, + 'notice_no': notice.business_no if notice is not None else None, + 'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids], + 'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids], 'decision_source': source, 'idempotent_replay': False, 'line_fulfillment': project_review_case_line_decisions(case), @@ -448,12 +448,12 @@ def create_post_ot_fulfillment_wave( idem_row = ShippingOrderReviewWaveIdempotency( idempotency_key=persist_key, review_case_id=int(case.id), - task_id=int(notice.id) if notice is not None else int(task.id), - task_no=str(notice.task_no if notice is not None else task.task_no), + task_id=int(task.id), + task_no=str(task.task_no), wave_no=wave_no, decision_source=source, - line_keys_json=_stable_line_keys(keys), - line_keys_hash=_line_keys_hash(keys), + snapshot_line_ids_json=[int(item) for item in keys], + snapshot_line_ids_hash=_snapshot_line_ids_hash([int(item) for item in keys]), inventory_snapshot_id=snap_id, inventory_snapshot_fingerprint=snap_fp, status='succeeded', @@ -471,7 +471,7 @@ def create_post_ot_fulfillment_wave( return result -def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: +def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> list[str]: """ 列出可自动/人工履约的行(ready+matched+未关闭+未终态)。 @@ -482,7 +482,7 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: case: 复核 Case。 Returns: - line_key 列表。 + snapshot_line_id 列表。 """ projected = project_review_case_line_decisions(case) out: list[str] = [] @@ -509,5 +509,5 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: avail is not None and avail < req and not is_released_shortage ): continue - out.append(str(item.get('line_key') or '')) + out.append(str(item.get('snapshot_line_id') or '')) return [k for k in out if k] diff --git a/backend/app/services/shipping_notice/post_ot_wave_progress_service.py b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py index 122d6ae3..ea8e3fae 100644 --- a/backend/app/services/shipping_notice/post_ot_wave_progress_service.py +++ b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py @@ -34,7 +34,7 @@ def schedule_post_ot_wave_progress( *, task_no: str, wave_no: int | None, - line_keys: list[str], + snapshot_line_ids: list[int], review_case_id: int | None = None, idempotency_row_id: int | None = None, request_idempotency_key: str | None = None, @@ -49,7 +49,7 @@ def schedule_post_ot_wave_progress( Args: task_no: 正式 OT 编号。 wave_no: 本波次号;可为 None(仅跳过行时)。 - line_keys: 本波行键。 + snapshot_line_ids: 本波冻结订单行 ID。 review_case_id: 复核 Case id。 idempotency_row_id: wave 幂等行 id(用于回写 progress_*)。 request_idempotency_key: 原始 wave 请求幂等键。 @@ -61,7 +61,7 @@ def schedule_post_ot_wave_progress( """ _ = created_by_id normalized = str(task_no or '').strip().upper() - keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] + ids = [int(k) for k in (snapshot_line_ids or [])] if not normalized: return { 'auto_progress_started': False, @@ -69,7 +69,7 @@ def schedule_post_ot_wave_progress( 'reason': 'missing_task_no', 'wave_no': wave_no, } - if wave_no is None and not keys: + if wave_no is None and not ids: return { 'auto_progress_started': False, 'status': 'skipped', @@ -105,7 +105,7 @@ def schedule_post_ot_wave_progress( { 'task_no': normalized, 'wave_no': int(wave_no) if wave_no is not None else None, - 'line_keys': keys, + 'snapshot_line_ids': ids, 'review_case_id': int(review_case_id) if review_case_id is not None else None, 'idempotency_row_id': int(idempotency_row_id) if idempotency_row_id is not None else None, 'progress_idempotency_key': progress_key, @@ -143,7 +143,7 @@ def schedule_post_ot_wave_progress( 'progress_status': 'scheduled' if job_id is not None else 'failed', 'progress_job_id': int(job_id) if job_id is not None else None, 'progress_idempotency_key': progress_key, - 'line_keys': keys, + 'snapshot_line_ids': ids, } diff --git a/backend/app/services/shipping_notice/preview_grant_store.py b/backend/app/services/shipping_notice/preview_grant_store.py index ec166831..1bb04da2 100644 --- a/backend/app/services/shipping_notice/preview_grant_store.py +++ b/backend/app/services/shipping_notice/preview_grant_store.py @@ -3,7 +3,8 @@ backend/app/services/shipping_notice/preview_grant_store.py 用途:为订单文档模板页预览令牌提供受控存储后端选择。 依赖:Flask current_app、统一 Redis client。 -逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内一次性令牌存储。 +逻辑:生产默认强依赖 Redis;开发单进程可按配置回退到进程内短时令牌存储。 + PNG 页预览令牌在 TTL 内可重复 get(支持翻页);原 PDF 预览仍可用 getdel 单次消费。 """ from __future__ import annotations @@ -19,7 +20,7 @@ from app.services.redis_client import get_redis_client class _MemoryGrantStore: - """为单进程开发环境提供最小 setex/getdel 语义,保持一次性令牌行为。""" + """为单进程开发环境提供 setex/get/getdel,PNG 页令牌可在 TTL 内重复读取。""" def __init__(self) -> None: self._lock = threading.Lock() @@ -30,6 +31,19 @@ class _MemoryGrantStore: with self._lock: self._items[key] = (expires_at, value) + def get(self, key: str) -> str | None: + """读取未过期令牌且不删除,供标注画布翻页回访同一 PNG grant。""" + now = time.time() + with self._lock: + row = self._items.get(key) + if row is None: + return None + expires_at, value = row + if expires_at <= now: + self._items.pop(key, None) + return None + return value + def getdel(self, key: str) -> str | None: now = time.time() with self._lock: @@ -57,7 +71,7 @@ def preview_grant_store() -> Any: 返回模板预览授权存储。 AI/调用方触发时机:仅供订单文档模板预览接口内部使用。Redis 不可用时, - 只有启用了开发兜底配置,才允许退回进程内一次性 token 存储。 + 只有启用了开发兜底配置,才允许退回进程内短时 token 存储。 """ client = get_redis_client() if client is not None: diff --git a/backend/app/services/shipping_notice/process_gate_access_service.py b/backend/app/services/shipping_notice/process_gate_access_service.py index 76deb95b..6d0069a7 100644 --- a/backend/app/services/shipping_notice/process_gate_access_service.py +++ b/backend/app/services/shipping_notice/process_gate_access_service.py @@ -17,7 +17,7 @@ from app.models import ( ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingProcessExecution, - ShippingNotice, + ShippingOrderTask, User, ) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit @@ -52,7 +52,7 @@ def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set """ owners: set[int] = set() if execution.task_id is not None: - task = db.session.get(ShippingNotice, int(execution.task_id)) + task = db.session.get(ShippingOrderTask, int(execution.task_id)) if task is not None and task.user_id is not None: owners.add(int(task.user_id)) if execution.review_case_id is not None: @@ -201,7 +201,8 @@ def _record_permission_denied( """ task_no = None if execution.task_id is not None: - task = db.session.get(ShippingNotice, int(execution.task_id)) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, int(execution.task_id)) task_no = str(task.task_no) if task is not None else None record_fulfillment_audit( event_type='process_gate_permission_denied', @@ -241,7 +242,8 @@ def execution_audit_scope_keys(execution: ShippingProcessExecution) -> dict[str, task_no = None case_no = None if execution.task_id is not None: - task = db.session.get(ShippingNotice, int(execution.task_id)) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, int(execution.task_id)) task_no = str(task.task_no) if task is not None else None if execution.review_case_id is not None: case = db.session.get(ShippingOrderReviewCase, int(execution.review_case_id)) diff --git a/backend/app/services/shipping_notice/process_gate_api_service.py b/backend/app/services/shipping_notice/process_gate_api_service.py index edf5a42b..6bb6c2d2 100644 --- a/backend/app/services/shipping_notice/process_gate_api_service.py +++ b/backend/app/services/shipping_notice/process_gate_api_service.py @@ -22,7 +22,7 @@ from app.models import ( ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, - ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.audit_query_service import serialize_shipping_audit_event from app.services.shipping_notice.process_gate_access_service import execution_audit_scope_keys @@ -79,7 +79,7 @@ def serialize_execution_admin_summary(execution: ShippingProcessExecution) -> di ).first() task_no = None if execution.task_id is not None: - task = db.session.get(ShippingNotice, int(execution.task_id)) + task = db.session.get(ShippingOrderTask, int(execution.task_id)) task_no = str(task.task_no) if task is not None else None return { 'execution_no': execution.execution_no, @@ -160,7 +160,7 @@ def list_admin_process_executions( like = f'%{keyword}%' task_ids = [ int(row.id) - for row in ShippingNotice.query.filter(ShippingNotice.task_no.ilike(like)).limit(200).all() + for row in ShippingOrderTask.query.filter(ShippingOrderTask.task_no.ilike(like)).limit(200).all() ] filters = [ShippingProcessExecution.execution_no.ilike(like)] if task_ids: diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index f68941d9..048ed292 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -10,7 +10,9 @@ services/shipping_notice/process_gate_bridge.py co8 后仅按 review_case_id / task_id 创建 Execution,不再依赖 WorkflowItem; 复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details; 确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定; - 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code。 + 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code; + 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation + 供 ensure_inventory(复用未过期快照或触发 RPA)。 """ from __future__ import annotations @@ -21,12 +23,14 @@ import logging from datetime import datetime from typing import Any +from app import db from app.models import ( ShippingOrderReviewCase, ShippingOrderCandidate, ShippingProcessExecution, ShippingProcessGate, ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES from app.services.shipping_notice.process_gate_service import ( @@ -39,36 +43,48 @@ from app.services.shipping_notice.process_gate_service import ( _LOGGER = logging.getLogger(__name__) -def _derived_fulfillment_status(task: ShippingNotice) -> str: +def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str: """从领域结果事实推导履约分支,不读取旧流程状态字段。""" - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() - if upload_status in {'uploaded', 'succeeded', 'success'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt + upload_attempt = latest_upload_attempt(task) + upload_status = str(getattr(upload_attempt, 'status', None) or '').strip().lower() + if has_verified_upload_success(task): return 'uploaded' - pending = str(getattr(task, 'pending_human_reason', None) or '').strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending = str(task_blocking_reason(task) or '').strip() if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}: return 'waiting_inventory' if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}: return 'waiting_upload' if upload_status == 'failed': return 'upload_failed' - if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json: - return 'shortage_review' - match_status = str(getattr(task, 'match_status', None) or '').strip().lower() + if isinstance(task, ShippingOrderTask): + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_have_shortage, + inventory_matches_complete_for_task, + has_ready_inventory_file_for_task, + ) + + if inventory_matches_complete_for_task(task): + return 'shortage_review' if current_inventory_matches_have_shortage(task) else 'matched' + return 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'created' + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + match_status = aggregate_match_status_for_task(match_task_id) or '' if match_status in {'fulfillable', 'partial', 'unfulfillable'}: return 'matched' - if str(getattr(task, 'export_file_path', None) or '').strip(): - return 'inventory_ready' - if isinstance(getattr(task, 'inventory_lines_json', None), list) and task.inventory_lines_json: + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + if has_ready_inventory_file_for_task(task): return 'inventory_ready' return 'created' -def inventory_preparation_reason_code(task: ShippingNotice) -> str: +def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) -> str: """ 由任务事实推导库存准备门禁阻断原因码。 - 核心逻辑:pending_human_reason 与最近 inventory_rpa_failed 事件优先于泛化 - inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。 + 核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt + 失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。 惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。 Args: @@ -84,7 +100,8 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str: ) from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event - pending = str(task.pending_human_reason or '').strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending = str(task_blocking_reason(task) or '').strip() if pending == PH_RPA_PENDING: return 'inventory_rpa_queued' if pending == PH_RPA_EXHAUSTED: @@ -112,6 +129,39 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str: return 'inventory_file_identity_mismatch' return 'inventory_rpa_export_failed' + # 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧 + # ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。 + from app.models import ShippingTaskInventoryRpaAttempt + + latest_attempt = ( + ShippingTaskInventoryRpaAttempt.query + .filter( + ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(), + ) + .order_by( + ShippingTaskInventoryRpaAttempt.attempt_no.desc(), + ShippingTaskInventoryRpaAttempt.id.desc(), + ) + .first() + ) + if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {'failed', 'exhausted'}: + blob = ' '.join([ + str(latest_attempt.status or '').strip().lower(), + str(latest_attempt.error_code or '').strip().lower(), + str(latest_attempt.error_message or '').strip().lower(), + ]) + if 'exhausted' in blob: + return 'inventory_rpa_exhausted' + if 'timeout' in blob or ('not ready' in blob and 'within' in blob): + return 'inventory_rpa_timeout' + if 'login' in blob or 'auth' in blob: + return 'inventory_rpa_login_failed' + if 'empty' in blob: + return 'inventory_file_empty' + if 'identity' in blob or 'mismatch' in blob: + return 'inventory_file_identity_mismatch' + return 'inventory_rpa_export_failed' + # inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计, # 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。 if pending == PH_INV_UNAVAIL: @@ -120,7 +170,7 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str: # 未持久化测试对象仍携带 ``[]`` 时,明确表达“文件已解析但无库存行”。 # ``None`` 才表示未得到库存文件,避免把空文件误投影成缺文件。 if getattr(task, 'id', None) is None: - return 'inventory_file_empty' if getattr(task, 'inventory_lines_json', None) == [] else 'inventory_file_missing' + return 'inventory_file_missing' # [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。 from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task @@ -141,7 +191,7 @@ _FREIGHT_UPLOAD_RPA_REASON_CODES = frozenset({ }) -def manual_upload_reason_code(task: ShippingNotice) -> str: +def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str: """ 由任务事实推导货代上传相关阻断原因码。 @@ -158,7 +208,8 @@ def manual_upload_reason_code(task: ShippingNotice) -> str: PH_UPLOAD_RPA_PENDING, ) - pending = str(task.pending_human_reason or '').strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending = str(task_blocking_reason(task) or '').strip() status = _derived_fulfillment_status(task) if pending == PH_UPLOAD_RPA_PENDING: return 'upload_rpa_pending' @@ -243,11 +294,20 @@ def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExe ) -def find_execution_for_task(task: ShippingNotice) -> ShippingProcessExecution | None: - """按 Task 查找绑定的 Execution。""" +def find_execution_for_task(task: ShippingOrderTask | ShippingNotice) -> ShippingProcessExecution | None: + """按 OT 查找绑定的 Execution;正式 Notice 入口仅沿 order_task_id 定位其 OT。""" + task_id = ( + int(task.id) + if isinstance(task, ShippingOrderTask) and getattr(task, 'id', None) is not None + else int(task.order_task_id) + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None) is not None + else None + ) + if task_id is None: + return None return ( ShippingProcessExecution.query - .filter_by(task_id=int(task.id)) + .filter_by(task_id=task_id) .filter(ShippingProcessExecution.status != 'superseded') .order_by(ShippingProcessExecution.id.desc()) .first() @@ -348,7 +408,7 @@ def mark_gates_passed_through( """ 将 sequence 不大于 through_gate_code 且仍为 pending/skipped 的门禁标记为 passed。 - 核心逻辑:用于人工确认建单后一次性推进到 task_creation;已阻断门禁不静默覆盖。 + 核心逻辑:用于人工确认建单后推进已满足的前置门禁;已阻断门禁不静默覆盖。 Returns: 实际推进的 gate_code 列表。 @@ -368,11 +428,9 @@ def mark_gates_passed_through( break if gate.status in {'passed', 'skipped'}: continue - if gate.status not in {'pending', 'blocked_manual', 'blocked_retryable', 'invalidated', 'queued'}: - continue - # 仅放行人工确认可覆盖的冻结就绪与前置 pending;技术失败不覆盖。 - if gate.status == 'failed_terminal': + if gate.status not in {'pending', 'skipped'}: continue + # 人工确认只能推进仍未评估的前置门禁;任何真实阻断必须保留。 apply_gate_outcome( execution=execution, gate_code=gate.gate_code, @@ -394,7 +452,7 @@ def mark_gates_passed_through( def sync_execution_after_review_confirm( *, case: ShippingOrderReviewCase, - task: ShippingNotice, + task: ShippingOrderTask, actor_id: int, ) -> ShippingProcessExecution | None: """ @@ -407,7 +465,7 @@ def sync_execution_after_review_confirm( Args: case: 复核 Case。 - task: 本波次新建的 ShippingNotice。 + task: 复核确认生成的 ShippingOrderTask。 actor_id: 确认操作人。 Returns: @@ -436,13 +494,74 @@ def sync_execution_after_review_confirm( actor_type='user', actor_id=actor_id, ) - mark_gates_passed_through( + # Task 已真实创建并绑定 Execution,先收口 task_creation;后续 Gate 不得越过该事实。 + apply_gate_outcome( execution=execution, - through_gate_code='task_creation', + gate_code='task_creation', + passed=True, + effective_result={'findings': [], 'task_id': int(task.id), 'task_no': task.task_no}, actor_type='user', actor_id=actor_id, - reason='review_confirmed', + idempotency_key=f'task-creation-after-confirm:{execution.execution_no}:{task.id}', + force=True, ) + # Snapshot 已在确认事务中成功冻结;该事实单独收口 order_freeze_readiness。 + from app.models import ShippingOrderSnapshot + + snapshot_id = getattr(task, 'order_snapshot_id', None) + snapshot = ( + db.session.get(ShippingOrderSnapshot, int(snapshot_id)) + if snapshot_id is not None else None + ) + if not ( + snapshot is not None + and int(getattr(snapshot, 'task_id', 0) or 0) == int(task.id) + and int(getattr(snapshot, 'extraction_id', 0) or 0) == int(task.current_order_extraction_id or 0) + ): + return execution + apply_gate_outcome( + execution=execution, + gate_code='order_freeze_readiness', + passed=True, + effective_result={'findings': [], 'task_id': int(task.id), 'snapshot_id': int(snapshot_id)}, + actor_type='user', + actor_id=actor_id, + idempotency_key=f'order-freeze-after-confirm:{execution.execution_no}:{snapshot_id}', + force=True, + ) + # [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。 + # CandidateSet 是 inventory_source_routing 通过的必要业务事实。 + from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source + + adjudication = adjudicate_and_apply_inventory_source( + task, + execution_id=int(execution.id), + ) + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + if not task_frozen_inventory_source_codes(task): + # 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。 + return execution + + apply_gate_outcome( + execution=execution, + gate_code='inventory_source_routing', + passed=True, + effective_result={ + 'findings': [], + 'candidate_set_id': int(task.active_inventory_candidate_set_id), + 'source_codes': task_frozen_inventory_source_codes(task), + 'status': str(adjudication.status or 'resolved'), + }, + actor_type='user', + actor_id=actor_id, + idempotency_key=( + f'inventory-routing-after-confirm:{execution.execution_no}:' + f'{task.active_inventory_candidate_set_id}' + ), + force=True, + ) + # [STEP] 建单后立即按 Task 状态投影履约门禁,避免 13–19 长期停留 pending。 sync_fulfillment_gates_from_task( execution=execution, @@ -785,12 +904,13 @@ def _supersede_auto_inventory_poll_for_rpa_failure( """ from app import db from app.models import ShippingProcessGateAttempt - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED + from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + from app.services.shipping_notice.process_gate_projection import task_blocking_reason if ( _derived_fulfillment_status(task) != 'waiting_inventory' - or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED + or str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING ): return gate = ShippingProcessGate.query.filter_by( @@ -847,6 +967,7 @@ def sync_fulfillment_gates_from_task( 按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。 核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果; + 建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数; RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断 manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 @@ -857,7 +978,7 @@ def sync_fulfillment_gates_from_task( """ if not execution.task_id: return - task = ShippingNotice.query.get(int(execution.task_id)) + task = ShippingOrderTask.query.get(int(execution.task_id)) if task is None: return @@ -868,19 +989,29 @@ def sync_fulfillment_gates_from_task( actor_id=actor_id, ) - from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.fulfillment_workflow import ( + inventory_match_facts_complete, + match_completed, + ) + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + from app.services.shipping_notice.inventory_file_store import ( + active_inventory_file_for_task, + active_inventory_lines_for_task, + ) - match_status = str(task.match_status or '').strip() - has_export = bool(str(task.export_file_path or '').strip()) - has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0 + inv_file = active_inventory_file_for_task(task) + has_inventory_lines = bool( + inv_file is not None + and str(getattr(inv_file, 'snapshot_status', '') or '').strip().lower() == 'ready' + and getattr(inv_file, 'invalidated_at', None) is None + and active_inventory_lines_for_task(task) + ) status = _derived_fulfillment_status(task) # [STEP 1A] 已验证并绑定的库存行是库存准备的正式成功事实。RPA 回调与 # 旧失败/超时 Attempt 可以乱序到达;不能让遗留的 rpa_exhausted 把已成功 # 入库的任务重新投影为 waiting_inventory,否则 Gate 会停在“手工上传”。 if has_inventory_lines and status == 'waiting_inventory': status = 'inventory_ready' - inv_file = active_inventory_file_for_task(task) mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False))) # [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。 done_statuses = {'uploaded', 'closed'} @@ -918,16 +1049,10 @@ def sync_fulfillment_gates_from_task( force=True, ) return - post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses} sufficiency_ok = match_completed(task) - shortage = (not sufficiency_ok) and ( - match_status in {'unfulfillable', 'partial'} - or bool(task.shortage_json) - or status == 'shortage_review' - ) - match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in { - 'matched', 'waiting_upload', 'upload_failed', *done_statuses, - } + match_passed = inventory_match_facts_complete(task) + shortage = match_passed and not sufficiency_ok + match_status = 'fulfillable' if sufficiency_ok else ('unfulfillable' if match_passed else None) # 手动上传文件也必须由已发布库存模板自动映射;若尚未完成,只能进入系统 # 可重试状态,不能产生“人工确认字段映射”业务节点。 source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None @@ -993,7 +1118,7 @@ def sync_fulfillment_gates_from_task( }) # Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能 # 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。 - task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted' + task_rpa_exhausted = str(task_blocking_reason(task) or '').strip() == 'rpa_exhausted' if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending): apply_gate_outcome( execution=execution, gate_code='inventory_preparation', passed=False, @@ -1029,7 +1154,7 @@ def sync_fulfillment_gates_from_task( if status == 'waiting_inventory': from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING - pending_reason = str(task.pending_human_reason or '').strip() + pending_reason = str(task_blocking_reason(task) or '').strip() # 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或历史次数耗尽时 # 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。 if pending_reason == PH_RPA_PENDING: @@ -1062,7 +1187,38 @@ def sync_fulfillment_gates_from_task( force=True, ) return - inv_prep_passed = status in post_inventory or has_inventory_lines + # [STEP 2B] 建单后尚无库存事实(derived=created)时,禁止把「未取数」投影成 + # inventory_file_empty 失败。应保留 pending 并露出 Worker 动作,由 + # submit_auto_progress → ensure_inventory:先复用未过期快照,否则触发 RPA。 + if not has_inventory_lines and status == 'created': + prep_gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code='inventory_preparation') + .first() + ) + if prep_gate is not None and str(prep_gate.status or '').strip().lower() in { + 'pending', 'queued', 'running', + }: + if not str(prep_gate.next_action_code or '').strip(): + from app.services.shipping_notice.process_gate_contract import ( + primary_next_action_for_gate, + ) + prep_gate.next_action_code = ( + primary_next_action_for_gate( + gate_code='inventory_preparation', + status='blocked_retryable', + ) + or 'retry_inventory_preparation' + ) + prep_gate.updated_at = datetime.utcnow() + from app.services.shipping_notice.process_gate_service import ( + _refresh_execution_pointers, + ) + _refresh_execution_pointers(execution) + return + # 库存准备的成功事实只能是已验证并绑定的库存行。下游状态可能因历史脏数据、 + # 并发投影或错误侧路动作残留,绝不能反向证明库存文件已经准备完成。 + inv_prep_passed = has_inventory_lines inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task) apply_gate_outcome( execution=execution, @@ -1124,11 +1280,9 @@ def sync_fulfillment_gates_from_task( classify_inventory_match_reason, ) - line_results = ( - list(task.line_results_json) - if isinstance(task.line_results_json, list) - else [] - ) + from app.models import ShippingNoticeLineInventoryMatch + current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + line_results = [{'disposition': row.match_result} for row in current_match_rows] match_reason = None if match_passed else classify_inventory_match_reason( line_results=line_results, match_status=match_status, @@ -1190,7 +1344,11 @@ def sync_fulfillment_gates_from_task( ) ), 'match_status': match_status or None, - 'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None, + 'shortage': [ + {'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty} + for row in current_match_rows + if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'} + ], }, blocking_reason_code=None if sufficiency_ok else str(shortage_reason or 'inventory_insufficient'), actor_type=actor_type, @@ -1198,6 +1356,7 @@ def sync_fulfillment_gates_from_task( idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}', force=True, ) + from app.services.shipping_notice.fulfillment_workflow import excel_gate_error # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。 # 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。 excel_error = excel_gate_error(task) @@ -1225,6 +1384,17 @@ def sync_fulfillment_gates_from_task( if not excel_ready: return + # [STEP 6A] 正式 Notice 仅在库存门禁通过后的产物生成动作中创建。通知准备 + # 及 Excel 资格检查必须只读 OT;进入产物/上传后段才允许读取 Notice 事实。 + formal_notice = ( + ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first() + ) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + export_artifact = latest_export_artifact(formal_notice) if formal_notice is not None else None + has_export = export_artifact is not None + status = None + if formal_notice is not None: + status = _derived_fulfillment_status(formal_notice) artifact_ok = has_export or status in done_statuses apply_gate_outcome( execution=execution, @@ -1254,7 +1424,7 @@ def sync_fulfillment_gates_from_task( # [STEP 7] freight_upload_rpa(RPA)与 manual_upload_handoff(真正人工)分离。 uploaded = status in done_statuses - upload_reason = None if uploaded else manual_upload_reason_code(task) + upload_reason = None if uploaded else manual_upload_reason_code(formal_notice or task) task_details = { 'derived_fulfillment_status': status or None, 'task_no': str(task.task_no or '') or None, diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 7826e66b..d02ba303 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -3,12 +3,14 @@ services/shipping_notice/process_gate_contract.py 用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、 阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格; + 以及 Gate→粗分类/位置/待办(derive_*); 作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。 依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用; 细粒度错误可解释性分层码见 error_explainability_contract。 逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码; 同一根因只允许一个 owning_gate 产生用户阻断 Finding; - 单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层。 + 单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层; + derive_user_mode / derive_position / derive_todo_category 供进度早停、待办与摘要消费。 """ from __future__ import annotations @@ -196,23 +198,21 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'inventory_source_routing', + 'gate_code': 'task_creation', 'sequence_no': 10, - 'label': '库存源路由', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'}, - 'responsible_party': 'owner', + 'label': '订单任务创建', + 'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'}, + 'responsible_party': 'system', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_with_latest_rules', - # 库存源由规则自动裁决;规则冲突属于配置/数据治理,不允许用户人工选源。 - 'blocked_manual': 'retry_with_latest_rules', + 'blocked_retryable': 'retry_task_creation', }, }, { 'gate_code': 'order_freeze_readiness', 'sequence_no': 11, - 'label': '订单冻结资格', + 'label': '订单冻结完成', 'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'freeze_readiness'}, 'responsible_party': 'system', 'implementation_status': 'implemented', @@ -223,15 +223,16 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'task_creation', + 'gate_code': 'inventory_source_routing', 'sequence_no': 12, - 'label': 'ShippingNotice 创建', - 'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'}, - 'responsible_party': 'system', + 'label': '库存源路由', + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'}, + 'responsible_party': 'owner', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_task_creation', + 'blocked_retryable': 'retry_with_latest_rules', + 'blocked_manual': 'retry_with_latest_rules', }, }, { @@ -373,6 +374,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching', + 'override_line_inventory_source', 'open_inventory_match_review', 'recheck_inventory_sufficiency', 'open_shortage_review', @@ -473,13 +475,21 @@ def inventory_preparation_primary_action( status: str | None, blocking_reason_code: str | None = None, ) -> str | None: - """裁决库存准备 Gate 面向业务用户的主动作。""" + """裁决库存准备 Gate 面向业务用户的主动作。 + + 单源合并(用户拍板):库存失败只保留 2 个按钮 —— + ``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching`` + (优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。 + 已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 + ``retry_inventory_matching``。 + """ normalized_status = str(status or '').strip().lower() normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': return 'poll_inventory_preparation' if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: - return 'reload_inventory_result' + # [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。 + return 'retry_inventory_matching' if normalized_status in {'blocked_manual', 'blocked_retryable'}: return 'retry_inventory_preparation' return None @@ -490,6 +500,53 @@ def is_technical_gate_party(responsible_party: str | None) -> bool: return str(responsible_party or '').strip() in PROCESS_GATE_TECHNICAL_PARTIES +def gate_side_recovery_actions( + *, + gate_code: str, + status: str | None = None, + blocking_reason_code: str | None = None, +) -> tuple[str, ...]: + """ + 返回当前阻断状态下,除主动作外业务用户仍可提交的侧路恢复动作序列。 + + 核心逻辑:投影层(serialize_process_gate 的 allowed_actions 侧路)与校验层 + (request_gate_action 的 allowed_side)必须共用同一份裁决,禁止各自硬编码, + 否则会出现「投影放行按钮、校验却拒绝提交」的漂移(如 RPA 超时/耗尽时点击 + 「重新获取库存 (RPA)」被报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。 + 这些动作由 Gate 契约或状态显式允许;仅用于展示/提交统一入口,不改变主动作。 + + Args: + gate_code: 当前阻断 Gate 编码。 + status: Gate 状态(如 blocked_retryable / blocked_manual / waiting_external)。 + blocking_reason_code: 阻断原因码。 + + Returns: + 允许的侧路动作码序列(有序,保证投影 allowed_actions 顺序稳定);无则空元组。 + """ + code = str(gate_code or '').strip().lower() + reason = str(blocking_reason_code or '').strip().lower() + sides: list[str] = [] + # [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照 + # 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。 + if ( + code == 'inventory_preparation' + and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} + ): + sides.append('retry_inventory_preparation') + # [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。 + if ( + code == 'manual_upload_handoff' + and reason in {'manual_upload_pending', 'upload_result_unknown'} + ): + sides.append('retry_freight_upload_rpa') + # [STEP] 行级库存源人工覆写(方案 3·放开):通知准备(Excel 生成前)与库存匹配阶段 + # 均允许用户把某行库存源覆写为任一已启用源后再重匹配;Excel 锁与源启用校验由执行器负责。 + # 已取代旧 D5 多文件冲突逐行选源(select_line_inventory_source,已下线)。 + if code in {'inventory_source_routing', 'inventory_preparation', 'inventory_matching'}: + sides.append('override_line_inventory_source') + return tuple(sides) + + PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'document_unavailable', 'layout_parse_failed', @@ -822,10 +879,18 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: if recovery_plan_for_action(current_gate=code, action_code=action) is not None: return True - if action == 'retry_inventory_matching' and code == 'inventory_sufficiency': + if action == 'retry_inventory_matching' and code in { + 'inventory_preparation', 'inventory_matching', 'inventory_sufficiency', + }: return True if action == 'reload_inventory_result' and code == 'inventory_preparation': return True + # 人工覆写行级库存源(方案 3·放开):通知准备(取数失败/多候选)与匹配阶段(Excel 前)均可。 + # 已取代旧 D5 逐行选源(select_line_inventory_source,已下线)。 + if action == 'override_line_inventory_source' and code in { + 'inventory_source_routing', 'inventory_preparation', 'inventory_matching', + }: + return True navigation_owners = { 'open_order_review': {'order_freeze_readiness', 'order_field_extraction'}, 'open_profile_review': {'document_profile_routing'}, @@ -1173,8 +1238,8 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { # ============================================================ INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = ( - 'inventory_source_routing', # 路由规则计算(sub_stage=calculated) - 'order_freeze_readiness', # 候选冻结(建单瞬间,sub_stage=frozen)——注意:复用现有 Gate,避免 seq 漂移 + 'order_freeze_readiness', # 订单 Snapshot 冻结(sub_stage=frozen) + 'inventory_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated) 'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready) 'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) ) @@ -1241,3 +1306,155 @@ def user_mode_for_blocking_reason(reason_code: str | None) -> str | None: if not reason_code: return None return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip()) + + +# review_status 人工复核处置 → must_human(在 auto_continue 默认之前) +_REVIEW_STATUS_MUST_HUMAN: Final[frozenset[str]] = frozenset({ + 'parse_review', + 'rsv_req', + 'quality_issue', + 'customer_review', + 'shortage_review', +}) + + +def derive_user_mode( + *, + user_status: str | None, + gate_code: str | None, + review_status: str | None, + lifecycle_stage: str | None, +) -> str: + """ + 粗分类(auto_continue / must_human / wait_manual_upload / complete)。 + + 用途:从 Gate user_status/gate_code 与 review_status 推导用户模式;不投影领域标量。 + 核心逻辑:rejected→complete;复核处置(parse_review/rsv_req/quality_issue/ + customer_review/shortage_review)→must_human;再按 Gate/user_status 分支。 + """ + rs = str(review_status or '').strip() + if rs == 'rejected': + return 'complete' + if rs in _REVIEW_STATUS_MUST_HUMAN: + return 'must_human' + if str(user_status or '').strip() == 'completed': + return 'complete' + code = str(gate_code or '').strip() + stage = str(lifecycle_stage or '').strip() + status = str(user_status or '').strip() + if code == 'manual_upload_handoff' or ( + stage in {'freight_upload', 'upload_complete'} and status == 'waiting_human' + ): + return 'wait_manual_upload' + if status == 'waiting_human': + return 'must_human' + return 'auto_continue' + + +def derive_position(*, gate_code: str | None, review_status: str | None) -> str | None: + """ + 位置标签(与 POSITION_* / 文案表 key 对齐),供待办/用户态/阶段摘要消费。 + + 用途:复核处置优先读 review_status;履约位置读 current_gate_code。 + """ + rs = str(review_status or '').strip() + if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}: + return rs + mapping = { + 'order_field_extraction': 'parse_review', + 'customer_resolution': 'customer_review', + 'reservation_validation': 'rsv_req', + 'inventory_preparation': 'inventory_pending', + 'inventory_matching': 'ready_to_match', + 'inventory_sufficiency': 'shortage_review', + 'order_freeze_readiness': 'order_freeze', + 'excel_readiness': 'ready_to_export', + 'artifact_generation': 'export_ready', + 'freight_upload_rpa': 'upload_failed', + 'manual_upload_handoff': 'waiting_upload', + } + return mapping.get(str(gate_code or '').strip()) + + +def derive_todo_category(*, user_mode: str, position: str | None = None) -> str: + """ + 待办分类(review / exception / manual_upload / done / in_progress)。 + + 用途:由 user_mode + position 推导待办分类(Gate-first 唯一口径)。 + """ + if user_mode == 'wait_manual_upload': + return 'manual_upload' + if user_mode == 'complete': + return 'done' + if user_mode == 'must_human': + return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception' + return 'in_progress' + + +# ============================================================ +# 阶段能力集(Stage Capabilities)——一期:通知准备阶段 +# 能力可用性 = 阶段 + Excel 未生成 + 预条件(数据在场),不由门禁通过与否决定。 +# 与 PROCESS_GATE_ACTION_CODES(门禁恢复动作)语义不同:能力动作允许请求「非当前 gate」, +# request_gate_action 对阶段能力豁免,并走 execute_stage_capability(作废下游——重置+重跑)。 +# ============================================================ + +STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = { + 'override_line_inventory_source': { + 'stage': 'fulfillment_prep', + 'scope': 'line', + 'action_code': 'override_line_inventory_source', + 'invalidate': { + 'inventory_field_mapping', 'inventory_matching', + 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + }, + 'reset_to': 'inventory_preparation', + }, + 'retry_inventory_preparation': { + 'stage': 'fulfillment_prep', + 'scope': 'task', + 'action_code': 'retry_inventory_preparation', + 'invalidate': { + 'inventory_field_mapping', 'inventory_matching', + 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + }, + 'reset_to': 'inventory_preparation', + }, + # 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。 + # 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel, + # 因此不重置回 inventory_preparation,也不作废上游 source/mapping。 + 'retry_inventory_matching': { + 'stage': 'fulfillment_prep', + 'scope': 'task', + 'action_code': 'retry_inventory_matching', + 'invalidate': { + 'inventory_matching', 'inventory_sufficiency', + 'excel_readiness', 'artifact_generation', + }, + 'invalidate_change_type': 'inventory_field_mapping_changed', + 'reset_to': 'inventory_matching', + }, + 'reload_inventory_result': { + 'stage': 'fulfillment_prep', + 'scope': 'task', + 'action_code': 'reload_inventory_result', + 'invalidate': frozenset(), + 'reset_to': None, + }, +} + + +def stage_capability(action_code: str | None) -> dict[str, Any] | None: + """按动作码返回阶段能力定义;非阶段能力返回 None。""" + code = str(action_code or '').strip() + return STAGE_CAPABILITY_DEFINITIONS.get(code) + + +def is_stage_capability(action_code: str | None) -> bool: + """判断动作码是否为阶段能力。""" + return stage_capability(action_code) is not None + + +def capability_stage(action_code: str | None) -> str | None: + """返回能力所属阶段码;非能力返回 None。""" + cap = stage_capability(action_code) + return str(cap['stage']) if cap else None diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py index 283dc814..c1449f33 100644 --- a/backend/app/services/shipping_notice/process_gate_dependency.py +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -151,10 +151,10 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { 'customer_resolution': ('reservation_validation',), 'duplicate_detection': ('customer_resolution',), 'field_conflict_resolution': ('duplicate_detection',), - 'inventory_source_routing': ('field_conflict_resolution',), - 'order_freeze_readiness': ('inventory_source_routing',), - 'task_creation': ('order_freeze_readiness',), - 'inventory_preparation': ('task_creation',), + 'task_creation': ('field_conflict_resolution',), + 'order_freeze_readiness': ('task_creation',), + 'inventory_source_routing': ('order_freeze_readiness',), + 'inventory_preparation': ('inventory_source_routing',), 'inventory_field_mapping': ('inventory_preparation',), 'inventory_matching': ('inventory_field_mapping',), 'inventory_sufficiency': ('inventory_matching',), diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index bdbf79be..4da9c9a9 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -4,11 +4,13 @@ services/shipping_notice/process_gate_executor.py 用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。 依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、 inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 - document_layout.lifecycle、process_gate_contract、process_gate_bridge。 + document_layout.lifecycle、process_gate_contract、process_gate_bridge、 + inventory_candidate_projection、recovery_invalidation_service。 逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态; 库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径; co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem; - 人工入口动作返回 navigation 提示,保持 blocked_manual。 + 人工入口动作返回 navigation 提示,保持 blocked_manual; + 行级库存重抓按 snapshot_line_id → candidate.source_codes_json 收窄 RPA/失效。 """ from __future__ import annotations @@ -18,6 +20,8 @@ from typing import Any, Callable from app import db from app.core.errors import ValidationError from app.models import ( + ShippingNotice, + ShippingOrderTask, ShippingOrderDocument, ShippingOrderProcessingRun, ShippingOrderReviewCase, @@ -74,6 +78,13 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ 'regenerate_manual_upload_todo', }) +# 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。 +# poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。 +_FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({ + 'retry_inventory_preparation', + 'retry_inventory_from_preparation', +}) + # 人工入口:前端应导航,不把业务状态改为 passed。 _NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'open_order_review', @@ -188,6 +199,7 @@ def _dispatch_action( 'retry_inventory_from_preparation': _handle_retry_inventory_preparation, 'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping, 'retry_inventory_from_matching': _handle_retry_inventory_from_matching, + 'override_line_inventory_source': _handle_override_line_inventory_source, 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, 'recheck_excel_readiness': _handle_recheck_excel_readiness, 'regenerate_excel_artifact': _handle_regenerate_excel, @@ -339,9 +351,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) ``_orchestrator_internal_dispatch``,禁止库存/Excel workflow 再次绕回 ``run_task_auto_progress``,把当前活动 Attempt 误判成“无待处理 Gate”。 """ - from app.models import ShippingNotice - - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None if task is None: raise ValidationError('Execution has no bound task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND') return { @@ -355,6 +365,71 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) } +def _resolve_line_inventory_scope( + task: ShippingOrderTask | ShippingNotice | None, + *, + line_scope_key: Any = None, +) -> dict[str, Any] | None: + """ + 由 snapshot_line_id / line_scope_key 解析行级库存作用域。 + + 核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。 + Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。 + + Args: + task: 当前 OT / 兼容 Notice owner。 + line_scope_key: 前端 snapshot_line_id 或已规范化的行 scope。 + + Returns: + {snapshot_line_id, line_no, source_codes};无法解析时 None。 + """ + if task is None: + return None + raw = line_scope_key + if raw is None: + return None + try: + scoped_line_id = int(raw) + except (TypeError, ValueError): + return None + if scoped_line_id <= 0 or not getattr(task, 'order_snapshot_id', None): + return None + + from app.models import ShippingOrderSnapshot + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + scoped_line = next( + ( + line for line in (getattr(snapshot, 'lines', None) or []) + if int(getattr(line, 'id', 0) or 0) == scoped_line_id + ), + None, + ) + if scoped_line is None: + return None + line_no = int(getattr(scoped_line, 'line_no', 0) or 0) + candidate_line = next( + ( + line for line in get_active_candidate_lines(task) + if int(getattr(line, 'line_no', 0) or 0) == line_no + ), + None, + ) + source_codes = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if not source_codes: + return None + return { + 'snapshot_line_id': scoped_line_id, + 'line_no': line_no, + 'source_codes': source_codes, + } + + def _tool_outcome( *, action_code: str, @@ -706,9 +781,7 @@ def _handle_retry_task_creation( ) task_no = (result or {}).get('task_no') if task_no: - from app.models import ShippingNotice - - task = ShippingNotice.query.filter_by(task_no=str(task_no)).first() + task = ShippingOrderTask.query.filter_by(task_no=str(task_no)).first() if task is not None: bind_execution_task( execution_no=str(execution.execution_no), @@ -746,7 +819,19 @@ def _handle_retry_inventory_preparation( """ 重试/轮询库存准备。 - 核心逻辑:调用 ensure_inventory 后按任务事实推导细粒度阻断码,再同步履约门禁。 + 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation → + retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto); + 若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄 + RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导 + 细粒度阻断码,再同步履约门禁。 + + Args: + execution: 当前 ProcessExecution。 + gate: 当前库存准备 Gate。 + payload: 须含 action_code;可选 actor_user_id / line_scope_key / snapshot_line_id。 + + Returns: + Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。 """ from app.models import ShippingNotice from app.services.shipping_notice.inventory_workflow import ensure_inventory @@ -757,7 +842,7 @@ def _handle_retry_inventory_preparation( sync_fulfillment_gates_from_task, ) - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_order_task(execution) recovery_plan_id = payload.get('recovery_plan_id') # Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。 # 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。 @@ -766,6 +851,33 @@ def _handle_retry_inventory_preparation( or payload.get('user_id') or payload.get('operator_id') ) + # [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。 + # 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。 + if task is not None: + from app.services.shipping_notice.inventory_candidate_projection import ( + get_active_candidate_lines, + get_active_candidate_set, + get_active_candidate_sources, + ) + candidate_set = get_active_candidate_set(task) + lines = get_active_candidate_lines(task) + sources = get_active_candidate_sources(task) + if ( + not task.order_snapshot_id + or candidate_set is None + or not sources + or not lines + or any(not list(getattr(line, 'source_codes_json', None) or []) for line in lines) + ): + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'inventory_source_routing_required', + 'effective_result_json': {'findings': [], 'routing_required': True}, + 'output_snapshot': { + 'action_code': str(payload.get('action_code') or 'retry_inventory_preparation'), + 'routing_required': True, + }, + } if task is not None and payload.get('action_code') == 'poll_inventory_preparation': # 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。 # 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。 @@ -800,7 +912,19 @@ def _handle_retry_inventory_preparation( }, } preparation_round = None - is_initial_auto_dispatch = str(payload.get('trigger') or '') == 'gate_attempt_passed' + is_manual_rpa_retry = str(payload.get('inventory_mode') or '').strip() == 'retry_rpa' + is_initial_auto_dispatch = ( + str(payload.get('trigger') or '') == 'gate_attempt_passed' + and not is_manual_rpa_retry + ) + line_scope = _resolve_line_inventory_scope( + task, + line_scope_key=( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ), + ) if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: # 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实, # 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。 @@ -824,6 +948,8 @@ def _handle_retry_inventory_preparation( action_code=str(payload.get('action_code')), attempt_id=payload.get('attempt_id'), actor_id=actor_id, + source_codes=(line_scope or {}).get('source_codes'), + snapshot_line_id=(line_scope or {}).get('snapshot_line_id'), ) preparation_round = create_inventory_preparation_round( task=task, @@ -834,9 +960,26 @@ def _handle_retry_inventory_preparation( gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None, ) inventory_payload = _task_payload(execution, payload) - # 只有用户显式重试强制生成新 Attempt;首次自动投递应先尝试复用有效快照。 - if payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: + # 阶段能力重试在入队时统一保存为 line_scope_key;兼容旧 Attempt 仍可能携带 snapshot_line_id。 + inventory_payload['line_scope_key'] = ( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ) + if line_scope is not None: + # 行级重抓:只把该行 candidate.source_codes_json 交给 ensure_inventory / RPA。 + inventory_payload['source_codes'] = list(line_scope['source_codes']) + inventory_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id']) + # [STEP] 按已有动作码映射 ensure_inventory mode(零新动作码)。 + # 禁止「人工入口一律 retry_rpa」:仅显式强制 RPA 码写 retry_rpa;poll 只读轮询; + # 首次 gate_attempt_passed 自动投递保持默认 auto(先复用快照)。 + action_code = str(payload.get('action_code') or '').strip() + if action_code in _FORCE_INVENTORY_RPA_ACTION_CODES and not is_initial_auto_dispatch: inventory_payload['mode'] = 'retry_rpa' + if action_code == 'poll_inventory_preparation': + # [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试, + # 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。 + inventory_payload['allow_auto_retry'] = False response = ensure_inventory(inventory_payload) if preparation_round is not None: from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round @@ -861,6 +1004,197 @@ def _handle_retry_inventory_preparation( return outcome +def _handle_override_line_inventory_source( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 人工覆写行级库存源(方案 3·放开):通知准备阶段(Excel 生成前)允许用户把某行库存源 + 覆写为任一**已启用**库存源,而不仅限于规则候选。先放开、后续再收紧到仅候选源。 + + 校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写; + 覆写后把该行候选钉为所选源并重跑该行匹配(snapshot 复用/触发 RPA 由既有 + auto-progress / ensure_inventory 处理:有未过期快照直接匹配,否则重新 RPA)。 + + Args: + execution: 门禁执行上下文。 + gate: 当前门禁实例。 + payload: 含 line_no / source_code / 可选 reason、actor_user_id。 + + Returns: + 符合动作契约的 tool 响应。 + """ + from app.core.errors import ConflictError, ValidationError + from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + list_database_inventory_sources, + ) + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + from app.services.shipping_notice.inventory_candidate_freeze_service import ( + freeze_manual_line_source_selection, + ) + + task = _resolve_order_task(execution) + line_no_raw = payload.get('line_no') + source_code = str(payload.get('source_code') or '').strip().upper() + reason = str(payload.get('reason') or '').strip()[:500] or None + actor_raw = payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id') + try: + line_no = int(line_no_raw) + except (TypeError, ValueError) as exc: + raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID') from exc + if task is None or not source_code or line_no < 1: + raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID') + # Excel 是不可变输出边界(D7):生成后源锁定,改源只能走撤销/人工流程。 + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + if (latest_export_artifact(task) is not None): + raise ConflictError( + '通知 Excel 已生成,库存源已锁定,请走撤销/人工纠错流程', + code='SHIPPING.LINE_SOURCE_LOCKED', + ) + # 方案 3:任一已启用源都允许(不限于规则候选)。 + enabled_codes = { + str(item.get('source_code') or '').strip().upper() + for item in list_database_inventory_sources(enabled_only=True) + } + if source_code not in enabled_codes or get_database_inventory_source(source_code) is None: + raise ConflictError('所选库存源不存在或已停用', code='SHIPPING.LINE_SOURCE_UNAVAILABLE') + try: + actor_id = int(actor_raw) if actor_raw not in (None, '') else None + except (TypeError, ValueError): + actor_id = None + try: + candidate_result, all_lines_selected = freeze_manual_line_source_selection( + task, + line_no=line_no, + source_code=source_code, + actor_id=actor_id, + reason=reason, + execution_id=int(execution.id), + ) + except ValueError as exc: + raise ConflictError(str(exc), code='SHIPPING.REVIEW_LINE_NOT_FOUND') from exc + db.session.flush() + record_fulfillment_audit( + event_type='review_line_source_overridden', + aggregate_type='shipping_notice', + aggregate_id=str(task.task_no), + action='override_line_inventory_source', + actor_type='user' if actor_id else 'system', + actor_id=actor_id, + task_no=task.task_no, + before={'line_no': line_no, 'previous_source_code': None}, + after={'line_no': line_no, 'selected_source_code': source_code, 'reason': reason}, + ) + if not all_lines_selected: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'no_inventory_source_candidates', + 'effective_result_json': { + 'findings': [], 'candidate_set_id': candidate_result.candidate_set_id, + 'selected_line_no': line_no, 'all_lines_selected': False, + }, + 'output_snapshot': { + 'action_code': 'override_line_inventory_source', + 'candidate_set_id': candidate_result.candidate_set_id, + 'all_lines_selected': False, + }, + } + + # 首次人工选源完成的是 routing Gate 本身;让 Attempt 以 passed 收口后, + # process_gate_service 会统一入队下一道 inventory_preparation,避免在当前 + # routing Attempt 内递归触发 RPA 而把 Gate 状态写错。 + if gate.gate_code == 'inventory_source_routing': + return { + 'outcome': 'passed', + 'effective_result_json': { + 'findings': [], 'candidate_set_id': candidate_result.candidate_set_id, + 'selected_line_no': line_no, 'all_lines_selected': True, + }, + 'output_snapshot': { + 'action_code': 'override_line_inventory_source', + 'candidate_set_id': candidate_result.candidate_set_id, + 'all_lines_selected': True, + }, + } + + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + # [ROOT CAUSE FIX · RPA 不触发] 行级库存源覆写冻结新候选后,必须把 inventory_preparation Gate + # 作为「定向人工恢复」重新推进:显式传 resume_gate_code='inventory_preparation' 与 + # inventory_mode='retry_rpa'。否则 AutoProgress 会读取该 Gate 残留的 next_action_code + # (waiting_external → poll_inventory_preparation),只排队一个只读 poll,既不创建 + # InventoryPreparationAttempt 也不触发 RPA,最终永远停在 inventory_file_empty。 + # 与 execute_stage_capability 的「重新获取库存」路径保持同一语义(见 process_gate_service)。 + run_task_auto_progress( + task.task_no, + trigger='manual_override_source', + operator_id=actor_id, + resume_gate_code='inventory_preparation', + inventory_mode='retry_rpa', + ) + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id) + # 覆写库存源只改变后续取数/匹配的输入,不能把“库存准备”本身伪造成成功。 + # 续跑后必须以 Gate 同步得到的库存事实收口:只有有效库存快照已落库时才通过; + # RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。 + db.session.flush() + preparation_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).first() + gate_status = str(getattr(preparation_gate, 'status', '') or '').strip().lower() + reason_code = str(getattr(preparation_gate, 'blocking_reason_code', '') or '').strip() or None + if gate_status == 'passed': + outcome = 'passed' + elif gate_status in {'queued', 'running', 'waiting_external'}: + outcome = 'waiting_external' + else: + outcome = 'blocked_retryable' + return { + 'outcome': outcome, + 'blocking_reason_code': None if outcome == 'passed' else ( + reason_code or 'inventory_preparation_failed' + ), + 'effective_result_json': { + 'findings': [], + 'inventory_preparation_status': gate_status or 'blocked_retryable', + }, + 'output_snapshot': { + 'action_code': 'override_line_inventory_source', + 'inventory_preparation_status': gate_status or 'blocked_retryable', + }, + } + + +def _resolve_order_task(execution: ShippingProcessExecution) -> ShippingOrderTask | None: + """按 Execution.task_id 解析 OT;Execution 永不直接指向正式 Notice。""" + return ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None + + +def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool: + """ + 任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。 + + 【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。 + + 核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结, + 没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。 + """ + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + return bool(task_frozen_inventory_source_codes(task)) + + +def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None: + """解析已由库存门禁创建的正式 Notice,仅供 Excel/上传动作使用。""" + task = _resolve_order_task(execution) + if task is None: + return None + return ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first() + + def _handle_reload_inventory_result( *, execution: ShippingProcessExecution, @@ -881,7 +1215,7 @@ def _handle_reload_inventory_result( sync_fulfillment_gates_from_task, ) - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_order_task(execution) if task is None: return { 'outcome': 'blocked_retryable', @@ -895,6 +1229,14 @@ def _handle_reload_inventory_result( mode='reload_result', ) if response is None: + # [STEP] 重读未命中意味着本次等待链没有可消费的回调结果。Gate 将收口为 + # blocked_retryable,必须同步取消尚未领取的延迟 poll,避免继续显示/执行轮询。 + from app.services.shipping_notice.process_gate_job_service import cancel_inventory_external_wait_polls + + cancel_inventory_external_wait_polls( + gate_id=int(gate.id), + reason='库存结果重读未命中,外部等待轮询已终止', + ) return { 'outcome': 'blocked_retryable', 'blocking_reason_code': inventory_preparation_reason_code(task), @@ -926,7 +1268,7 @@ def _handle_retry_inventory_field_mapping( from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_order_task(execution) if task is None: return { 'outcome': 'blocked_retryable', @@ -980,7 +1322,12 @@ def _handle_retry_inventory_from_field_mapping( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。""" + """ + 从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。 + + Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt, + 禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。 + """ from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream invalidate_inventory_downstream( @@ -1018,16 +1365,62 @@ def _handle_retry_inventory_matching( ``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency; 当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的 满足性 Gate 归属并再次显示“进入库存匹配处理”。 + 行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退 + ensure_inventory 时携带该行 source_codes。 """ - from app.models import ShippingNotice - from app.services.shipping_notice.fulfillment_workflow import match_inventory + from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - response = match_inventory(_task_payload(execution, payload)) + task = _resolve_order_task(execution) + match_payload = _task_payload(execution, payload) + line_scope = _resolve_line_inventory_scope( + task, + line_scope_key=( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ), + ) + if line_scope is not None: + match_payload['source_codes'] = list(line_scope['source_codes']) + match_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id']) + match_payload['line_scope_key'] = int(line_scope['snapshot_line_id']) + response = match_inventory_line(match_payload, line_no=int(line_scope['line_no'])) + else: + response = match_inventory(match_payload) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None - match_status = str(getattr(task, 'match_status', '') or '').strip().lower() - has_shortage = bool(getattr(task, 'shortage_json', None)) + task = _resolve_order_task(execution) + from app.services.shipping_notice.fulfillment_workflow import ( + inventory_match_facts_complete, + match_completed, + ) + + match_complete = bool(task is not None and inventory_match_facts_complete(task)) + sufficient = bool(task is not None and match_completed(task)) + match_status = 'fulfillable' if sufficient else ('unfulfillable' if match_complete else '') + has_shortage = match_complete and not sufficient + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + shortage = [ + row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values() + if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + ] + # 订单已可履约:重匹配为成功,交由 suff/artifact 后续;不得把 match_inventory 内部 + # run_task_auto_progress 的"无待处理 Gate"(status='completed')误判为失败。 + if match_status == 'fulfillable': + return { + 'outcome': 'passed', + 'effective_result_json': { + 'findings': [], + 'match_status': match_status or None, + 'shortage': shortage, + }, + 'output_snapshot': { + 'action_code': 'retry_inventory_matching', + 'tool_status': 'passed', + 'business_result': 'fulfillable', + }, + } if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and ( match_status in {'partial', 'unfulfillable'} or has_shortage ): @@ -1038,7 +1431,7 @@ def _handle_retry_inventory_matching( 'effective_result_json': { 'findings': [], 'match_status': match_status or None, - 'shortage': getattr(task, 'shortage_json', None), + 'shortage': shortage, }, 'output_snapshot': { 'action_code': 'retry_inventory_matching', @@ -1083,14 +1476,14 @@ def _handle_recheck_inventory_sufficiency( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。""" + """独立库存满足性复核:读取当前行级 Match,不重跑库存匹配。""" from app.models import ShippingNotice from app.services.shipping_notice.fulfillment_workflow import ( recompute_task_fulfillment_state, ) from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_order_task(execution) if task is None: return { 'outcome': 'blocked_manual', @@ -1110,7 +1503,13 @@ def _handle_recheck_inventory_sufficiency( from app.services.shipping_notice.fulfillment_workflow import match_completed sufficient = match_completed(task) - shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None + from app.models import ShippingNoticeLineInventoryMatch + shortage = [ + {'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty} + for row in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'} + ] + match_status = 'fulfillable' if sufficient else 'unfulfillable' apply_gate_outcome( execution=execution, gate_code='inventory_sufficiency', @@ -1118,19 +1517,19 @@ def _handle_recheck_inventory_sufficiency( outcome=None if sufficient else 'blocked_manual', effective_result={ 'findings': [], - 'match_status': task.match_status, + 'match_status': match_status, 'shortage': shortage, }, blocking_reason_code=None if sufficient else 'inventory_insufficient', actor_type='system', actor_id=payload.get('actor_user_id'), - idempotency_key=f'inv-suff:{execution.execution_no}:{task.match_status}:{sufficient}', + idempotency_key=f'inv-suff:{execution.execution_no}:{match_status}:{sufficient}', force=True, ) if sufficient: return { 'outcome': 'passed', - 'effective_result_json': {'findings': [], 'match_status': task.match_status}, + 'effective_result_json': {'findings': [], 'match_status': match_status}, 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True}, } return { @@ -1149,11 +1548,10 @@ def _handle_recheck_excel_readiness( payload: dict[str, Any], ) -> dict[str, Any]: """Excel 生成资格检查:只跑 excel_gate_error,不生成 Artifact。""" - from app.models import ShippingNotice from app.services.shipping_notice.fulfillment_workflow import excel_gate_error from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_order_task(execution) if task is None: return { 'outcome': 'blocked_retryable', @@ -1171,7 +1569,7 @@ def _handle_recheck_excel_readiness( blocking_reason_code=None if ready else 'excel_not_ready', actor_type='system', actor_id=payload.get('actor_user_id'), - idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{task.match_status}', + idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{getattr(task, "order_data_version", 1)}', force=True, ) if ready: @@ -1196,22 +1594,16 @@ def _handle_regenerate_excel( payload: dict[str, Any], ) -> dict[str, Any]: """仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。""" - from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.fulfillment_workflow import generate_excel from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None - existing = ( - ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() - if task is not None and task.id is not None else None - ) - if existing is not None: + task = _resolve_order_task(execution) + if task is None: return { - 'outcome': 'blocked_manual', - 'blocking_reason_code': 'notice_excel_already_generated', - 'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'}, + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'artifact_generation_failed', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True}, + 'output_snapshot': {'action_code': 'regenerate_excel_artifact'}, } response = generate_excel(_task_payload(execution, payload)) outcome = _tool_outcome( @@ -1246,7 +1638,7 @@ def _handle_freight_upload_rpa( sync_fulfillment_gates_from_task, ) - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_shipping_notice(execution) if task is None: return { 'outcome': 'blocked_manual', @@ -1287,7 +1679,7 @@ def _handle_regenerate_manual_upload_todo( from app.models import ShippingNotice from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task - task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + task = _resolve_shipping_notice(execution) if task is None: return _manual_open('regenerate_manual_upload_todo', 'manual_upload_handoff')( execution=execution, gate=gate, payload=payload, @@ -1377,7 +1769,7 @@ def _handle_inventory_reroute( case_no=str(case.case_no), expected_draft_version=payload.get('expected_draft_version'), idempotency_key=str(payload.get('idempotency_key') or f'gate-reroute-{gate.id}-{gate.evaluation_version}'), - line_key=str(payload.get('line_key') or '').strip() or None, + draft_line_id=str(payload.get('draft_line_id') or '').strip() or None, ) return { 'outcome': 'passed', @@ -1416,7 +1808,7 @@ def _handle_recheck_freeze( }, 'output_snapshot': {'action_code': 'recheck_freeze_readiness'}, } - task = ShippingNotice.query.get(int(execution.task_id)) + task = _resolve_order_task(execution) extraction = None if task is not None and task.order_extraction_id: extraction = ShippingOrderExtraction.query.get(int(task.order_extraction_id)) diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py index 500c8a70..cb25cd24 100644 --- a/backend/app/services/shipping_notice/process_gate_job_service.py +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -24,7 +24,7 @@ from app import db from app.core.errors import ConflictError, NotFoundError from app.jobs.queue import enqueue from app.jobs.types import JobType -from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt +from app.models import Job, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate, primary_next_action_for_gate from app.services.shipping_notice.process_gate_executor import execute_queued_attempt @@ -61,6 +61,40 @@ def _technical_job_max_attempts() -> int: return 1 +def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int: + """ + 取消某库存准备 Gate 尚未领取的延迟轮询 Job。 + + 核心逻辑:库存 Gate 从 waiting_external 收口为失败/人工恢复后,排队中的 + ``external-wait::*`` 不再有业务意义,必须立即取消,不能等到下一次 + 延迟触发后才发现 Gate 已变更。仅更新 queued Job;运行中的 Job 不能强杀, + 其执行入口会再次读取 Gate 并自行停止。 + + Args: + gate_id: inventory_preparation Gate 主键。 + reason: 取消原因,写入 Job message 供审计排查。 + + Returns: + 被取消的 Job 数量。 + """ + now = _utc_now() + return int( + Job.query.filter( + Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_PROCESS_GATE.value, + Job.status == 'queued', + Job.business_ref.like(f'external-wait:{int(gate_id)}:%'), + ).update( + { + 'status': 'cancelled', + 'finished_at': now, + 'message': str(reason or '库存等待已终止')[:500], + }, + synchronize_session=False, + ) + ) + + def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int: """ 入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。 @@ -204,11 +238,11 @@ def schedule_waiting_external_poll( from app.models import ShippingNotice from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - task = db.session.get(ShippingNotice, int(execution.task_id)) - has_inventory_lines = bool( - isinstance(getattr(task, 'inventory_lines_json', None), list) - and getattr(task, 'inventory_lines_json', None) - ) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, int(execution.task_id)) + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + has_inventory_lines = bool(task is not None and has_ready_inventory_file_for_task(task)) if task is not None and has_inventory_lines: sync_fulfillment_gates_from_task(execution=execution, actor_type='system') db.session.flush() @@ -306,6 +340,22 @@ def schedule_waiting_external_poll( execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if execution is None: return None + if str(gate.gate_code or '').strip() == 'inventory_preparation': + poll_count = int(effective.get('poll_count') or 0) + 1 + effective['poll_count'] = poll_count + gate.effective_result_json = effective + delay_seconds = min(poll_seconds * (2 ** min(poll_count - 1, 3)), 300) + return int(enqueue( + JobType.SHIPPING_PROCESS_GATE, + {'external_wait_poll_gate_id': int(gate.id)}, + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + business_ref=f'external-wait:{int(gate.id)}:{poll_count}', + message='等待库存 RPA 回传,延迟复查', + max_attempts=1, + scheduled_at=now + timedelta(seconds=delay_seconds), + dedupe_active=False, + commit=False, + )) poll_attempt = queue_gate_attempt( execution_no=str(execution.execution_no), gate_code=gate.gate_code, @@ -324,6 +374,30 @@ def schedule_waiting_external_poll( ) +def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]: + """执行库存 RPA 的只读等待轮询,不创建新的 Gate Attempt。""" + gate = ShippingProcessGate.query.filter_by(id=int(gate_id)).with_for_update().first() + if gate is None or gate.status != 'waiting_external': + return {'gate_status': getattr(gate, 'status', 'missing'), 'stopped': True} + execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) + if execution is None: + return {'gate_status': 'missing_execution', 'stopped': True} + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation + + outcome = _handle_retry_inventory_preparation( + execution=execution, + gate=gate, + payload={'action_code': 'poll_inventory_preparation'}, + ) + db.session.flush() + db.session.refresh(gate) + return { + 'gate_id': int(gate.id), + 'gate_status': gate.status, + 'outcome': str(outcome.get('outcome') or ''), + } + + def heartbeat_gate_attempt( *, attempt_id: int, diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 7b060f11..d0689a19 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -15,11 +15,14 @@ from __future__ import annotations from typing import Any +from app import db from app.models import ( ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, ShippingProcessRecoveryPlan, + ShippingOrderTask, + ShippingNotice, ) from app.services.shipping_notice.error_explainability_contract import ( build_explainability_reason, @@ -29,6 +32,7 @@ from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_CODE_SET, PROCESS_GATE_RECOVERABLE_STATUSES, action_presentation, + gate_side_recovery_actions, get_process_gate_definition, inventory_preparation_primary_action, is_business_user_action, @@ -62,6 +66,51 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = { 'open_shortage_review': 'draft', } + +def task_blocking_reason(task: ShippingOrderTask | ShippingNotice | None) -> str | None: + """读取任务当前人工阻断原因;OT 以 Process Gate 为唯一事实源。""" + if task is None: + return None + if not isinstance(task, ShippingOrderTask): + owner = None + if getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) + if owner is not None: + task = owner + else: + return None + execution_id = getattr(task, 'active_process_execution_id', None) + if execution_id is None: + # OT 在 Execution 尚未绑定/旧执行已清理时,pending_human_reason 仍是 + # 当前任务的流程事实;不能只回退到技术 error_code,否则 RPA 耗尽、 + # 库存不可用等业务阻断会被误判为“无阻断”,恢复入口也不会下发。 + return ( + str( + getattr(task, 'pending_human_reason', None) + or getattr(task, 'error_code', None) + or '' + ).strip() + or None + ) + execution = db.session.get(ShippingProcessExecution, int(execution_id)) + if execution is None or str(execution.status or '').strip().lower() == 'superseded': + return ( + str( + getattr(task, 'pending_human_reason', None) + or getattr(task, 'error_code', None) + or '' + ).strip() + or None + ) + gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .filter(ShippingProcessGate.status.in_(('blocked_manual', 'blocked_retryable', 'waiting_external'))) + .order_by(ShippingProcessGate.sequence_no.asc()) + .first() + ) + return str(getattr(gate, 'blocking_reason_code', None) or '').strip() or None + def _projection_gate_definition(gate_code: str) -> dict[str, Any]: """只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。""" return get_process_gate_definition(gate_code) @@ -84,8 +133,8 @@ def _resolve_recovery_next_action( """ 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - [STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果; - 其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 + [STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配, + 无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 [STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。 [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 @@ -438,9 +487,7 @@ def _execution_navigation_refs(execution: ShippingProcessExecution) -> dict[str, if run is not None and getattr(run, 'run_no', None): review_run_no = str(run.run_no) if execution.task_id: - from app.models import ShippingNotice - - task = ShippingNotice.query.get(int(execution.task_id)) + task = ShippingOrderTask.query.get(int(execution.task_id)) if task is not None: task_no = str(task.task_no) return { @@ -483,19 +530,56 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) - """判断正式任务是否已有可复用、未失效的已确认库存快照。""" if not execution.task_id: return False - from app.models import ShippingNotice - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task - task = ShippingNotice.query.get(int(execution.task_id)) - if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json: + task = ShippingOrderTask.query.get(int(execution.task_id)) + return bool(task is not None and has_ready_inventory_file_for_task(task)) + + +def _row_source_editable(execution: ShippingProcessExecution) -> bool: + """判断正式任务是否仍处于「行级库存源可编辑」阶段(发货 Excel 尚未生成)。 + + 核心逻辑:锁定边界 = Excel 生成(D7)。只有生成发货通知/发货 Excel 之后 + (存在有效 ShippingExportArtifact)才锁定行源;此前用户应能对行反复选源/覆写, + 因此行级编辑动作的授权必须以此为准,而不能依赖门禁是否恰好处于人工阻断态。 + """ + if not getattr(execution, 'task_id', None): return False - inventory_file = active_inventory_file_for_task(task) - return bool( - inventory_file is not None - and str(getattr(inventory_file, 'snapshot_status', '') or '').strip().lower() == 'ready' - and getattr(inventory_file, 'invalidated_at', None) is None - and bool(getattr(inventory_file, 'mapping_confirmed', False)) + task = ShippingOrderTask.query.get(int(execution.task_id)) + notice = ( + ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first() + if task is not None else None ) + if notice is None: + # OT 阶段尚未生成正式 Notice,库存源天然可编辑。 + return True + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + return latest_export_artifact(notice) is None + + +def _ensure_editable_row_source_actions( + *, + allowed_actions: list[str], + gate_code: str | None, + execution: ShippingProcessExecution, +) -> None: + """行级库源可编辑时,确保允许前端展示并提交行级选源/覆写动作。 + + 与 project_user_gate_summary 的 `if blocking:` 侧路不同:行可编辑性由「Excel 是否 + 生成」(_row_source_editable)决定,而非门禁是否处于阻断态。避免首次覆写成功后门禁 + 推进、allowed_actions 清空,导致用户对同一行二次编辑在前端被 noAction 拦下。 + """ + if not _row_source_editable(execution): + return + code = str(gate_code or '').strip().lower() + if code not in {'inventory_preparation', 'inventory_matching'}: + return + # 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口, + # 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。 + # retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。 + for side in ('override_line_inventory_source',): + if side not in allowed_actions and is_business_user_action(side): + allowed_actions.append(side) def _excel_regeneration_allowed( @@ -504,10 +588,18 @@ def _excel_regeneration_allowed( """判断上传阶段是否仍可安全替代 Excel;已上传、未知结果和并发恢复一律拒绝。""" if not execution.task_id or active_recovery_plans: return False - from app.models import ShippingExportArtifact, ShippingUploadAttempt + from app.models import ShippingExportArtifact, ShippingUploadAttempt, ShippingNotice + + # ProcessExecution.task_id 始终指向 OT;Artifact.task_id 指向正式 Notice。 + # 不能直接用 OT 主键查询 Artifact,否则会误判没有可重生的 Excel。 + notice = ShippingNotice.query.filter_by(order_task_id=int(execution.task_id)).order_by( + ShippingNotice.id.desc(), + ).first() + if notice is None: + return False artifact = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == int(execution.task_id), + ShippingExportArtifact.task_id == int(notice.id), ShippingExportArtifact.status == 'ready', ).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first() if artifact is None: @@ -615,24 +707,18 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if blocking: if next_action and is_business_user_action(str(next_action)): allowed_actions.append(str(next_action)) - # 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作, - # 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。 - if ( - str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation' - and str(reason_code or '').strip().lower() - in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} - and 'retry_inventory_preparation' not in allowed_actions + # [STEP] 侧路动作与校验层同源:allowed_actions 的侧路必须等于 + # request_gate_action 的 allowed_side(gate_side_recovery_actions), + # 禁止在此另行硬编码,避免「投影放行按钮、校验却拒绝提交」的漂移。 + # 覆盖:RPA 超时/耗尽的显式 RPA 重试、Gate 20 人工交接下的货代 RPA 重试、 + # 库存多文件冲突行的人工选源。 + for side_code in gate_side_recovery_actions( + gate_code=str(blocking.get('gate_code') or ''), + status=str(blocking.get('status') or ''), + blocking_reason_code=reason_code, ): - allowed_actions.append('retry_inventory_preparation') - # Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。 - # 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。 - if ( - str(blocking.get('gate_code') or '').strip().lower() == 'manual_upload_handoff' - and str(reason_code or '').strip().lower() in { - 'manual_upload_pending', 'upload_result_unknown', - } - ): - allowed_actions.append('retry_freight_upload_rpa') + if side_code not in allowed_actions: + allowed_actions.append(side_code) for target in recovery_targets: code = str(target.get('action_code') or '').strip() if code and code not in allowed_actions and is_business_user_action(code): @@ -667,6 +753,38 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if item: action_items.append(item) + # [EDITABLE] 行级库源可编辑(Excel 未生成)时,选源/覆写动作不与门禁阻断态绑定: + # 即使门禁已推进/不再处于人工阻断态,也应继续授权,避免首提成功后再编辑被 noAction 拦下。 + _ensure_editable_row_source_actions( + allowed_actions=allowed_actions, + gate_code=current_gate_code or str((blocking or {}).get('gate_code') or ''), + execution=execution, + ) + # 上面新增了行级编辑动作(尤其当 `if blocking:` 为假时原 action_items 为空),需重建 presentation。 + # 与 `if blocking:` 内建项保持同构,避免漏掉因可编辑性补充的动作。 + existing_codes = {str(item.get('code') or '') for item in action_items} + for code in allowed_actions: + if code in existing_codes: + continue + item = action_presentation(code, gate_code=current_gate_code) + recovery_definition = None + try: + from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action + + recovery_definition = recovery_plan_for_action( + current_gate=current_gate_code or '', action_code=code, + ) + except Exception: # noqa: BLE001 - recoverable (unknown gate) must not break presentation + recovery_definition = None + placement = (recovery_definition or {}).get('ui_placement') + if item and isinstance(placement, dict): + item.update({ + 'target_surface': placement.get('target_surface'), + 'target_anchor': placement.get('target_anchor'), + }) + if item: + action_items.append(item) + # [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源; # request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。 explainability = None @@ -867,7 +985,8 @@ _USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({ 'matched_rule_ids', 'raw_rule_source_codes', 'candidate_inventory_source_codes', - 'line_key', + 'draft_line_id', + 'snapshot_line_id', 'line_index', 'field_code', 'request_id', diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index 56a7674b..845f8f63 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -19,17 +19,26 @@ from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingPr from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_ACTION_CODES, + gate_side_recovery_actions, get_process_gate_definition, inventory_preparation_primary_action, is_business_user_action, + is_stage_capability, is_technical_gate_party, primary_next_action_for_gate, + stage_capability, ) from app.services.shipping_notice.process_gate_executor import ( action_requires_async_worker, execute_queued_attempt, ) -from app.services.shipping_notice.process_gate_service import queue_gate_attempt +from app.services.shipping_notice.process_gate_projection import serialize_process_gate +from app.services.shipping_notice.process_gate_service import ( + execute_stage_capability, + execute_stage_capability_override_source, + execute_stage_capability_rematch, + queue_gate_attempt, +) from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action from app.services.shipping_notice.recovery_plan_service import bind_recovery_attempt, create_recovery_plan @@ -119,19 +128,13 @@ def _primary_recovery_action( if gate.gate_code == 'inventory_matching' and execution.task_id: return 'retry_inventory_matching' if gate.gate_code == 'inventory_sufficiency' and execution.task_id: - from app.models import ShippingNotice - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.models import ShippingOrderTask + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task - task = ShippingNotice.query.get(int(execution.task_id)) - inventory_file = active_inventory_file_for_task(task) if task is not None else None + task = ShippingOrderTask.query.get(int(execution.task_id)) if ( task is not None - and isinstance(task.inventory_lines_json, list) - and bool(task.inventory_lines_json) - and inventory_file is not None - and str(inventory_file.snapshot_status or '').strip().lower() == 'ready' - and inventory_file.invalidated_at is None - and bool(inventory_file.mapping_confirmed) + and has_ready_inventory_file_for_task(task) ): return 'retry_inventory_matching' return gate.next_action_code or primary_next_action_for_gate( @@ -139,6 +142,43 @@ def _primary_recovery_action( ) +def is_stage_capability_exempt( + *, + current_gate: str, + requested_gate: str, + action_code: str, + lifecycle_stage: str, +) -> bool: + """判断阶段能力动作是否豁免「必须命中当前 gate」校验。 + + 【AI 触发时机】:request_gate_action 对阶段能力动作允许请求非当前 Gate 时调用; + 本函数为纯谓词、无 IO,供单测直接验证豁免边界。 + + 核心逻辑(三条件同时满足才放行): + 1) 动作是阶段能力(stage_capability 非 None); + 2) 当前生命周期阶段 == 能力阶段(cap['stage']); + 3) 请求的目标 Gate 落在该能力作废或重置范围(invalidate ∪ reset_to)。 + + Args: + current_gate: 当前 Execution 的 current_gate_code(保留用于接口对称,当前逻辑未使用)。 + requested_gate: 用户请求的 Gate 编码。 + action_code: 请求的动作码。 + lifecycle_stage: 当前生命周期阶段码(由 current_gate 的 ui_placement.target_surface 派生)。 + + Returns: + True 表示豁免非当前 Gate 校验;否则 False 走既有校验。 + """ + cap = stage_capability(action_code) + if cap is None: + return False + if lifecycle_stage != cap.get('stage'): + return False + targets = set(cap.get('invalidate') or ()) + if cap.get('reset_to'): + targets.add(cap['reset_to']) + return requested_gate in targets + + def request_gate_action( *, execution_no: str, @@ -213,9 +253,47 @@ def request_gate_action( details={'current_gate': gate.gate_code, 'action_code': action}, ) + # [STAGE_CAPABILITY] 生命周期阶段由当前 execution 的 current_gate 映射派生: + # 用 gate 定义的 ui_placement.target_surface 作为阶段码(库存门禁 → fulfillment_prep)。 + # 校验路径不再重算完整 ui_state,避免重活。 + lifecycle_stage = '' + if current_gate: + try: + lifecycle_stage = str( + get_process_gate_definition(current_gate).get('ui_placement', {}).get('target_surface') or '' + ) + except KeyError: + lifecycle_stage = '' + + # [STAGE_CAPABILITY] 阶段能力豁免:通知准备阶段内允许回退/重抓到上游库存 gate。 + # 前道数据可变,用户可在窗口内重抓/改源;执行走 execute_stage_capability, + # 不走普通主/侧路动作校验,也不触发 SHIPPING.PROCESS_GATE_NOT_CURRENT。 + stage_cap = stage_capability(action) + stage_exempt = ( + is_stage_capability(action) + and is_stage_capability_exempt( + current_gate=current_gate, + requested_gate=str(gate.gate_code or '').strip(), + action_code=action, + lifecycle_stage=lifecycle_stage, + ) + ) + + # [STEP] 库存阶段能力只属于正式 OT 执行链。建单前的 Review Execution 可以没有 + # task_id,但绝不能借同名 Gate 执行 reload/retry 并制造无归属 Attempt。 + if is_stage_capability(action) and not execution.task_id: + raise ValidationError( + 'Stage capability requires a bound shipping order task', + code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND', + details={'execution_no': execution.execution_no, 'action_code': action}, + ) + # [GLOBAL ACTION GUARD] 所有 20 Gate 共用同一入口:请求 Gate 必须是 Execution 当前 Gate。 # 跨阶段动作已在前面完成目标归属判定,避免错误地把非法恢复目标报告为状态漂移。 - if replay_attempt is None and (not current_gate or current_gate != str(gate.gate_code or '').strip()): + # 阶段能力(stage_exempt)允许访问非当前 Gate,故豁免此校验。 + if replay_attempt is None and not stage_exempt and ( + not current_gate or current_gate != str(gate.gate_code or '').strip() + ): raise ValidationError( 'Action must target the current process gate', code='SHIPPING.PROCESS_GATE_NOT_CURRENT', @@ -227,6 +305,38 @@ def request_gate_action( }, ) + # [STAGE_CAPABILITY] 阶段能力直接执行:作废下游 + 重置回起始 gate + 幂等重跑; + # 不经过下方普通主/侧路动作校验(primary/allowed_side)与技术 Gate 守卫。 + # 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑), + # 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。 + if stage_exempt: + if action == 'retry_inventory_matching': + result = execute_stage_capability_rematch( + execution=execution, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=idempotency_key, + ) + elif action == 'override_line_inventory_source': + # [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用 + # execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」 + # 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。 + result = execute_stage_capability_override_source( + execution=execution, gate=gate, payload=body, + actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key, + ) + else: + result = execute_stage_capability( + execution=execution, gate=gate, capability=stage_cap, + actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key, + line_scope_key=body.get('snapshot_line_id'), + ) + return { + 'outcome': 'submitted', + 'gate_summary': serialize_process_gate(gate), + 'stage_capability': result, + } + # [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。 # 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。 if str(actor_type or '') == 'user' and not is_business_user_action(action): @@ -258,8 +368,15 @@ def request_gate_action( ) primary = _primary_recovery_action(execution=execution, gate=gate) - # [STEP] 库存准备、选源与字段映射均为自动治理,不提供库存文件人工补传旁路。 - allowed_side: set[str] = set() + # [STEP] 侧路动作与投影层同源:request_gate_action 的 allowed_side 必须等于 + # serialize_process_gate 投影暴露的侧路动作集,否则会出现「按钮可点但提交被拒」的 + # 漂移(例如 RPA 超时/耗尽时点击「重新获取库存 (RPA)」被报 + # SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。禁止在此另行硬编码。 + allowed_side = set(gate_side_recovery_actions( + gate_code=gate.gate_code, + status=gate.status, + blocking_reason_code=gate.blocking_reason_code, + )) if primary and action != primary and action not in allowed_side and recovery_definition is None: raise ValidationError( 'Action is not the primary recovery action for this gate', diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index cbe50b90..695b5336 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -41,6 +41,18 @@ def _auto_match_enabled() -> bool: from app.services.shipping_notice.tool_common import auto_match_enabled return bool(auto_match_enabled()) + + +def _auto_generate_excel_enabled() -> bool: + """是否自动入队 artifact_generation Attempt(SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED)。 + + 关闭时匹配通过后停在「重新生成 Excel」人工入口,禁止静默投递 regenerate Job。 + """ + from app.services.shipping_notice.tool_common import auto_generate_excel_enabled + + return bool(auto_generate_excel_enabled()) + + from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text @@ -76,11 +88,11 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution: def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None: """ - 为既有 Execution 补齐契约新增的门禁行(如 freight_upload_rpa)。 + 为既有 Execution 补齐并校正当前 Gate 契约。 - 核心逻辑:按 PROCESS_GATE_DEFINITIONS 插入缺失 gate_code;若旧版 - manual_upload_handoff 仍占 sequence 19,先挪到 20 再插入 freight_upload_rpa=19, - 避免 uq_shipping_process_gates_execution_sequence 冲突。不改动既有状态语义。 + 核心逻辑:先将既有 Gate 临时移位,再按 PROCESS_GATE_DEFINITIONS 写回 + sequence_no 并插入缺失 Gate,避免顺序调整时触发唯一约束;只修正结构顺序, + 不改动既有状态语义。 Args: execution: 目标 Execution。 @@ -90,32 +102,35 @@ def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> N now = _utc_now() changed = False - # [STEP 1] 旧 Execution:manual 占 19 时先腾出序号给 freight_upload_rpa。 - manual = by_code.get('manual_upload_handoff') - freight_def = next( - (item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'freight_upload_rpa'), - None, + # [STEP 1] 旧 Execution:先把既有 Gate 行移到临时序号,避免顺序交换时触发 + # uq_shipping_process_gates_execution_sequence;随后统一写入当前契约 sequence_no。 + # 这样 PROCESS_GATE_DEFINITIONS 调整后,既有 Execution 也不会继续沿用旧顺序。 + expected_by_code = { + str(item['gate_code']): int(item['sequence_no']) + for item in PROCESS_GATE_DEFINITIONS + } + needs_sequence_reconcile = any( + code in expected_by_code and int(row.sequence_no or 0) != expected_by_code[code] + for code, row in by_code.items() ) - manual_def = next( - (item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'manual_upload_handoff'), - None, - ) - if ( - freight_def is not None - and manual_def is not None - and 'freight_upload_rpa' not in by_code - and manual is not None - and int(manual.sequence_no) == int(freight_def['sequence_no']) - ): - manual.sequence_no = int(manual_def['sequence_no']) - manual.updated_at = now + if needs_sequence_reconcile: + sequence_offset = 1000 + for row in rows: + row.sequence_no = sequence_offset + int(row.sequence_no or 0) + row.updated_at = now changed = True db.session.flush() - # [STEP 2] 插入仍缺失的门禁行。 + # [STEP 2] 按当前契约修正既有 Gate 顺序,并插入仍缺失的门禁行。 for item in PROCESS_GATE_DEFINITIONS: code = str(item['gate_code']) if code in by_code: + row = by_code[code] + expected_sequence = int(item['sequence_no']) + if int(row.sequence_no or 0) != expected_sequence: + row.sequence_no = expected_sequence + row.updated_at = now + changed = True continue db.session.add(ShippingProcessGate( execution_id=int(execution.id), @@ -269,14 +284,24 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio """Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。""" if getattr(execution, 'task_id', None) is None: return - from app.models import ShippingNotice + from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.order_task_stage_machine import ( sync_order_task_stage_for_notice, ) - notice = db.session.get(ShippingNotice, int(execution.task_id)) + task = db.session.get(ShippingOrderTask, int(execution.task_id)) + notice = ( + db.session.query(ShippingNotice) + .filter_by(order_task_id=int(task.id)) + .order_by(ShippingNotice.id.desc()) + .first() + if task is not None else None + ) if notice is not None: - sync_order_task_stage_for_notice(notice) + sync_order_task_stage_for_notice(notice, order_task=task) + elif task is not None: + # Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。 + task.stage = task.stage or 'notification_preparation' def ensure_execution_for_workflow_version( @@ -412,7 +437,7 @@ def bind_execution_task( actor_type: str = 'system', actor_id: str | int | None = None, ) -> ShippingProcessExecution: - """建单后绑定 ShippingNotice;幂等覆盖空 task_id。""" + """正式建单后将 Execution 绑定到 ShippingOrderTask;仅允许填充空 task_id。""" execution = _locked_execution(execution_no) if execution.task_id and int(execution.task_id) != int(task_id): raise ConflictError('Execution already bound to another task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND') @@ -787,6 +812,36 @@ def complete_gate_attempt( return gate +def _abort_active_attempt_as_superseded( + *, + gate: ShippingProcessGate, + active_attempt: ShippingProcessGateAttempt, + reason: str, +) -> None: + """把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。 + + 触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、 + 且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。 + 仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方 + 常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败 + 覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。 + """ + now = _utc_now() + active_attempt.status = 'superseded' + active_attempt.finished_at = now + active_attempt.lease_token = None + active_attempt.lease_expires_at = None + active_attempt.error_code = str(reason or 'business_fact_passed')[:64] + active_attempt.error_summary = 'Attempt superseded by a newer passed business fact.' + gate.status = 'pending' + gate.blocking_reason_code = None + gate.blocking_reason_json = None + gate.next_action_code = None + gate.latest_attempt_id = int(active_attempt.id) + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.updated_at = now + + def skip_gate_as_superseded( *, execution_no: str, @@ -953,9 +1008,13 @@ def _enqueue_auto_progress_after_gate_pass( # 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试, # 不能由 AutoProgress 无限重放。 if next_gate.next_action_code == 'retry_inventory_preparation': - from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt + from app.models import ShippingTaskInventoryRpaAttempt - task = db.session.get(ShippingNotice, int(execution.task_id)) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, int(execution.task_id)) + if task is None: + # Execution 必须绑定 OT;缺失任务时禁止自动投递,避免错误重放。 + return task_no = str(getattr(task, 'task_no', '') or '').strip() existing = ( ShippingTaskInventoryRpaAttempt.query @@ -970,6 +1029,10 @@ def _enqueue_auto_progress_after_gate_pass( next_gate.next_action_code in {'retry_inventory_matching'} and not _auto_match_enabled() ) + or ( + next_gate.next_action_code == 'regenerate_excel_artifact' + and not _auto_generate_excel_enabled() + ) or str(next_gate.next_action_code).startswith('open_') ): return @@ -986,6 +1049,9 @@ def _enqueue_auto_progress_after_gate_pass( expected_gate_version=int(next_gate.evaluation_version), input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}}, ) + # 幂等命中时队列函数可能返回 None;此时已有 Attempt,无需再次投递。 + if attempt is None: + return from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None) except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖 @@ -999,7 +1065,7 @@ def _enqueue_auto_progress_after_gate_pass( result='failure', reason_code='auto_progress_enqueue_failed', error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED', - error_summary=str(exc)[:500], + reason=str(exc)[:500], after={'execution_no': execution.execution_no, 'gate_code': gate.gate_code}, source='process_gate', ) @@ -1011,14 +1077,22 @@ def invalidate_downstream_gates( change_type: str, actor_type: str = 'system', actor_id: str | int | None = None, + exclude_gate_codes: set[str] | None = None, ) -> list[str]: """ 将依赖图指定的下游已通过门禁标记为 invalidated。 + Args: + execution: 当前正式执行链。 + change_type: 上游输入变更类型。 + actor_type / actor_id: 触发审计主体。 + exclude_gate_codes: 本次重置的起始 Gate;即使依赖图包含它也不得作废。 + Returns: 实际失效的 gate_code 列表。 """ targets = set(compute_invalidated_gates(change_type)) + targets.difference_update({str(code).strip() for code in (exclude_gate_codes or set())}) if not targets: return [] now = _utc_now() @@ -1141,15 +1215,40 @@ def sync_gate_from_business_result( active_attempt.trigger_type == 'auto' and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation' ) - if not inventory_ready or not is_auto_poll: - return gate - return complete_gate_attempt( - attempt_id=int(active_attempt.id), - outcome='passed', - output_snapshot=effective_result_json, - recommendation_json=recommendation_json, - effective_result_json=effective_result_json, + if (inventory_ready or is_auto_poll) and passed: + return complete_gate_attempt( + attempt_id=int(active_attempt.id), + outcome='passed', + output_snapshot=effective_result_json, + recommendation_json=recommendation_json, + effective_result_json=effective_result_json, + ) + # [STEP] 业务事实已判定通过,但占位 Attempt 是一个与本 Gate 通过评估无冲突的 + # 行级人工动作(例如并发 override_line_inventory_source)。 + # 若直接 `return gate` 静默丢弃,该并发 Attempt 随后以失败态收口会把真实成功 + # 覆盖为 blocked_retryable,前端误判「自动处理失败」(真实任务 + # SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。 + # 仅对这类行级人工动作做 superseded 收口;同 Gate 的自动准备/匹配 Attempt 属于 + # 当前执行器自身体系,必须保留让外层统一 complete,禁止在此提前收口或再入队。 + is_conflicting_user_line_action = ( + active_attempt.trigger_type in {'user_manual', 'user_retry'} + and str(snapshot.get('action_code') or '').strip() in { + 'override_line_inventory_source', + } ) + if is_conflicting_user_line_action and passed: + # 收口该并发行级动作后继续走下方 queue+complete 写入 passed(Gate 已复位 + # 为 pending,且活动 Attempt 已清除,可安全再入队)。 + _abort_active_attempt_as_superseded( + gate=gate, + active_attempt=active_attempt, + reason=f'business_fact_passed:{gate_code}', + ) + db.session.flush() + else: + # 其余活动 Attempt(同 Gate 自动准备/匹配、轮询、或非 passed 同步)都交由 + # 外层 Attempt 统一 complete,禁止在此提前收口或再入队,避免 PROCESS_GATE_BUSY。 + return gate if allow_repass and gate.status == 'passed': gate.status = 'invalidated' @@ -1198,3 +1297,278 @@ def sync_gate_from_business_result( effective_result_json=effective_result_json, invalidate_change_type=resolved_invalidate, ) + + +# ============================================================ +# 阶段能力编排器 · execute_stage_capability(作废下游 + 重置 + 幂等重跑) +# +# 用途:阶段能力允许在窗口内回退/重抓库存源;当前道(inventory_preparation)输入一旦 +# 变化,下游 mapping/matching/sufficiency/excel/artifact 结果必须作废并重算, +# 避免「旧匹配 + 新库存」拼出错误 Excel。 +# 依赖:run_task_auto_progress(progress_workflow,本模块模块级引用以便测试打桩)、 +# invalidate_downstream_gates(同文件)、process_gate_contract.stage_capability。 +# 逻辑:作废下游 → 重置执行指针回能力起始 gate → 解析 task_no 后幂等重跑;重跑失败 +# 不抛出,仅置 reran=False 交给调用方/前端处置。 +# ============================================================ +from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + +def execute_stage_capability( + *, + execution: Any, + gate: Any, + capability: dict[str, Any], + actor_type: str, + actor_id: int | str | None, + idempotency_key: str, + line_scope_key: int | str | None = None, +) -> dict[str, Any]: + """执行阶段能力(一期·通知准备):作废下游库存 gate → 重置回准备 → 幂等重跑。 + + 【AI 触发时机】:用户在通知准备阶段点击「重抓库存 / 重读结果 / 行级改源」等能力按钮 + 时由上游编排器调用;不要把作废/重算逻辑散落在各执行器里。 + + 核心步骤: + [STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate + 时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。 + [STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。 + [STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定 + 以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False + (run_task_auto_progress 对失败返回 dict 而非抛异常,不能仅凭「未抛异常」判成功)。 + + Args: + execution: 当前 ShippingProcessExecution。 + gate: 触发能力的门禁行(为接口稳定保留;当前失效链不依赖具体 gate)。 + capability: STAGE_CAPABILITY_DEFINITIONS 的能力定义。 + actor_type: 触发方角色(user/system/admin)。 + actor_id: 触发方 ID(可空)。 + idempotency_key: 幂等键;随调用透传给 run_task_auto_progress,供其短时幂等去重,避免重放重复推进。 + + Returns: + dict: {'invalidated_gates': list[str], 'reset_to': str|None, 'reran': bool}; + 重跑未成功时附带 'reran_reason': str(失败状态或异常摘要)。 + """ + invalidated: list[str] = [] + if capability.get('invalidate'): + invalidated = list(invalidate_downstream_gates( + execution=execution, + change_type='inventory_source_changed', + actor_type=actor_type, + actor_id=actor_id, + # 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。 + exclude_gate_codes={str(capability.get('reset_to') or '').strip()} - {''}, + )) + reset_to = capability.get('reset_to') + if reset_to: + execution.current_gate_code = reset_to + reran = False + reran_reason: str | None = None + try: + # [STEP 3] execution 持有 ShippingOrderTask 主键,先解析出 task_no。 + from app.models import ShippingOrderTask + + task = db.session.get(ShippingOrderTask, int(execution.task_id)) if getattr(execution, 'task_id', None) else None + task_no = getattr(task, 'task_no', None) + progress_result = run_task_auto_progress( + task_no, + trigger='manual_stage_capability', + idempotency_key=idempotency_key, + operator_id=str(actor_id) if actor_id is not None else None, + # 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate; + # 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。 + resume_gate_code=str(reset_to or '').strip() or None, + inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto', + line_scope_key=str(line_scope_key).strip() or None, + ) + # run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常; + # 仅凭「未抛异常」会把实际失败误判为 reran=True。按返回状态判定后写入失败原因。 + if isinstance(progress_result, dict): + run_status = str(progress_result.get('status') or '') + if run_status in {'failed', 'conflict'}: + reran = False + reran_reason = ( + str(progress_result.get('message') or '') + or str(progress_result.get('current_progress_version') or '') + or run_status + ) + else: + reran = True + else: + reran = True + except Exception as exc: # noqa: BLE001 — 幂等重跑失败不抛,交由调用方/前端处置 + reran = False + reran_reason = f'{type(exc).__name__}: {str(exc)[:200]}' + result: dict[str, Any] = {'invalidated_gates': invalidated, 'reset_to': reset_to, 'reran': reran} + if reran_reason is not None: + result['reran_reason'] = reran_reason + return result + + +def execute_stage_capability_rematch( + *, + execution: Any, + actor_type: str, + actor_id: int | str | None, + idempotency_key: str, +) -> dict[str, Any]: + """执行「重新匹配库存」阶段能力:作废匹配及下游,重跑匹配并重新收口满足性/Excel 事实。 + + 【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成) + 时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处 + 保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经 + inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel), + 避免错误重抓 RPA 或重做字段映射。 + + Args: + execution: 当前 ShippingProcessExecution。 + actor_type: 触发方角色(user/system/admin)。 + actor_id: 触发方 ID(可空)。 + idempotency_key: 幂等键;随 Attempt 透传。 + + Returns: + dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'}; + 重匹配未成功时附带 'reran_reason'(缺 matching gate 或 Attempt 执行异常摘要)。 + """ + from app.services.shipping_notice.process_gate_executor import execute_queued_attempt + + invalidated = list(invalidate_downstream_gates( + execution=execution, + change_type='inventory_field_mapping_changed', + actor_type=actor_type, + actor_id=actor_id, + )) + match_gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .first() + ) + if match_gate is None: + db.session.flush() + return { + 'invalidated_gates': invalidated, + 'reset_to': 'inventory_matching', + 'reran': False, + 'reran_reason': 'inventory_matching_gate_missing', + } + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code='inventory_matching', + trigger_type='user_retry', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=str(idempotency_key or ''), + expected_gate_version=None, + input_snapshot={ + 'action_code': 'retry_inventory_matching', + 'payload': { + 'actor_user_id': actor_id, + 'idempotency_key': str(idempotency_key or ''), + 'source': 'stage_capability_rematch', + }, + }, + ) + try: + updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery') + reran = True + except Exception as exc: # noqa: BLE001 — 重匹配失败不抛,交由调用方/前端处置 + db.session.flush() + return { + 'invalidated_gates': invalidated, + 'reset_to': 'inventory_matching', + 'reran': False, + 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', + } + # 收口执行指针到最早未通过 gate(complete_gate_attempt 已刷新,此处兜底幂等)。 + _refresh_execution_pointers(execution) + db.session.flush() + return { + 'invalidated_gates': invalidated, + 'reset_to': 'inventory_matching', + 'reran': reran, + 'gate_status': updated_gate.status, + 'current_gate_code': execution.current_gate_code, + } + + +def execute_stage_capability_override_source( + *, + execution: Any, + gate: Any, + payload: dict[str, Any], + actor_type: str, + actor_id: int | str | None, + idempotency_key: str, +) -> dict[str, Any]: + """执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。 + + 【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交 + override_line_inventory_source)时由 request_gate_action 调用。 + + 关键差异 / root cause 说明: + - `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` / + ``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个 + 关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。 + - 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义, + 但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到 + CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress + 按新候选重取/匹配库存,从而让 RPA 正常触发。 + + Args: + execution: 当前 ShippingProcessExecution。 + gate: 触发能力的门禁行。 + payload: 用户提交的原始动作载荷(含 line_no / source_code / reason / actor_user_id)。 + actor_type: 触发方角色(user/system/admin)。 + actor_id: 触发方 ID(可空)。 + idempotency_key: 幂等键;随 Attempt 透传。 + + Returns: + dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'}; + 失败时附带 'reran_reason'。 + """ + from app.services.shipping_notice.process_gate_executor import execute_queued_attempt + + invalidated = list(invalidate_downstream_gates( + execution=execution, + change_type='inventory_source_changed', + actor_type=actor_type, + actor_id=actor_id, + # 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。 + exclude_gate_codes={'inventory_preparation'} - {''}, + )) + # 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。 + execution.current_gate_code = 'inventory_preparation' + prepared_payload = dict(payload or {}) + prepared_payload.setdefault('idempotency_key', str(idempotency_key or '')) + try: + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code=str(gate.gate_code), + trigger_type='user_manual', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=str(idempotency_key or ''), + expected_gate_version=None, + input_snapshot={ + 'action_code': 'override_line_inventory_source', + 'payload': prepared_payload, + }, + ) + updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery') + reran = True + except Exception as exc: # noqa: BLE001 — 覆写失败不抛,交由调用方/前端处置 + db.session.flush() + return { + 'invalidated_gates': invalidated, + 'reset_to': 'inventory_preparation', + 'reran': False, + 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', + } + _refresh_execution_pointers(execution) + db.session.flush() + return { + 'invalidated_gates': invalidated, + 'reset_to': 'inventory_preparation', + 'reran': reran, + 'gate_status': updated_gate.status, + 'current_gate_code': execution.current_gate_code, + } diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 2116c5b2..17b115cc 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -205,12 +205,32 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: Returns: (ShippingProcessingStatus, ShippingProcessingStage)。 """ - step = str(getattr(notice, 'current_step', None) or '').strip().lower() - upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower() - export_path = str(getattr(notice, 'export_file_path', None) or '').strip() - pending = str(getattr(notice, 'pending_human_reason', None) or '').strip().lower() - review = str(getattr(notice, 'review_status', None) or '').strip().lower() - match = str(getattr(notice, 'match_status', None) or '').strip().lower() + owner = notice + if not hasattr(notice, 'current_step') and getattr(notice, 'order_task_id', None): + try: + from app import db + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, int(notice.order_task_id)) or notice + except Exception: # noqa: BLE001 + owner = notice + step = str(getattr(owner, 'current_step', None) or '').strip().lower() + pending = str(getattr(owner, 'pending_human_reason', None) or '').strip().lower() + review = str(getattr(owner, 'review_status', None) or '').strip().lower() + match = '' + export_path = '' + projected_upload = None + try: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else '' + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_notice_upload_status, + ) + artifact = latest_export_artifact(owner) + export_path = str(getattr(artifact, 'file_path', None) or '').strip() + projected_upload = project_notice_upload_status(owner) + except Exception: # noqa: BLE001 + pass lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower() from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success @@ -219,17 +239,17 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: return ('cancelled', 'cancelled') if verified_upload_success: ps = 'uploaded' - elif upload_st in {'uploaded', 'succeeded', 'success'}: - # 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。 + elif projected_upload == 'uploaded': + # 有 Notice 面成功投影但未过三层验证:留在上传工作面核对。 ps = 'waiting_upload' - elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}: - ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed' + elif projected_upload in {'uploading', 'pending', 'failed', 'unknown'} or pending in { + 'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown', + }: + ps = 'waiting_upload' if projected_upload != 'failed' else 'upload_failed' elif export_path: ps = 'matched' elif match: ps = 'matched' - elif getattr(notice, 'inventory_lines_json', None): - ps = 'inventory_ready' elif pending or review: ps = 'pending_review' else: @@ -237,7 +257,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: if ps in {'uploaded', 'closed', 'completed'}: return ('completed', 'completed') - if ps in {'waiting_upload', 'upload_failed', 'uploading'} or upload_st == 'uploading': + if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading': return ('automating', 'freight_uploading') if 'upload' in step or step.startswith('step7'): return ('automating', 'freight_uploading') @@ -512,7 +532,7 @@ def reconcile_processing_projection_facts( stage_idx = shipping_processing_stage_index(stage) waiting_idx = shipping_processing_stage_index('waiting_review') or 8 - # 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。 + # 关键事实无法读取时 fail-closed:不能继续沿用遗留位置投影或写动作。 if payload.get('projection_data_inconsistent'): payload['status'] = 'waiting_human' payload['stage'] = 'waiting_review' @@ -740,15 +760,25 @@ def apply_user_projection_fields( pending_reason: str | None = None review_status_raw: str | None = None inventory_source_status_raw: str | None = None - if notice is not None: - pending_reason = str(getattr(notice, 'pending_human_reason', None) or '').strip() or None - review_status_raw = str(getattr(notice, 'review_status', None) or '').strip() or None - inventory_source_status_raw = str(getattr(notice, 'inventory_source_status', None) or '').strip() or None - if order_task is not None and not pending_reason: + if order_task is None and notice is not None and getattr(notice, 'order_task_id', None): + try: + from app import db + from app.models import ShippingOrderTask + order_task = db.session.get(ShippingOrderTask, int(notice.order_task_id)) + except Exception: # noqa: BLE001 + order_task = None + if order_task is not None: pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None + review_status_raw = str(getattr(order_task, 'review_status', None) or '').strip() or None # ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status ===== - notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' + projected_upload = None + if order_task is not None and notice is not None: + try: + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + projected_upload = project_notice_upload_status(notice) + except Exception: # noqa: BLE001 + projected_upload = None from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success # 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed @@ -760,7 +790,7 @@ def apply_user_projection_fields( and ( old_status == 'completed' or old_stage == 'completed' - or notice_upload_status in {'uploaded', 'succeeded', 'success'} + or projected_upload == 'uploaded' ) ) def _compute_user_status() -> str: @@ -1018,6 +1048,41 @@ def apply_user_projection_fields( primary_action = _compute_primary_action() + # ===== [STEP 8: flatten C→A] 复用唯一裁决 C(process_gate),不再二次推导 drift ===== + # 契约 §2.1/§2.2:primary_action.code / blocking_reason.code 唯一来源是 C(project_user_gate_summary)。 + # A(本函数)只把 C 已裁决的规范化码包成 ui_state DTO;禁止再走别名(D1: regenerate_excel_artifact→ + # regenerate_excel)或坍缩(D2: inventory_preparation_failed→technical_failure_present)覆盖 C。 + # 条件化:仅当 _project_order_task_work_item 已写入 payload['process_gate'](正式 OT 有 Execution)时 + # 消费 C;Intake/min 投影路径(shipping_processing_projection.py:983/:4695)无 process_gate,保留现有推导。 + # 该实现与前端右卡仅读 A(§2.4)同批上线,保证右卡/对话流/批次进度中心同源;此处不改 user_status + # (那是 A 独有的六值展示分组枚举,C/B 均不产出,留在 A)。 + _process_gate = payload.get('process_gate') if isinstance(payload.get('process_gate'), dict) else None + if _process_gate is not None: + # D1: primary_action.code 取 C 规范码(去 A 的 regenerate_excel_artifact→regenerate_excel 别名)。 + _c_primary_code = str((_process_gate.get('primary_action') or {}).get('code') or '').strip() + if not _c_primary_code: + _c_primary_code = str(_process_gate.get('next_action_code') or '').strip() + if _c_primary_code: + _a_primary_code = str((primary_action or {}).get('code') or '').strip() + if _a_primary_code != _c_primary_code: + primary_action = { + 'code': _c_primary_code, + 'i18n_key': _resolve_action_i18n_key(_c_primary_code), + 'parameters': {}, + } + # D2: blocking_reason.code 取 C 已裁决的具体码,不再坍缩为 technical_failure_present。 + _c_reason_code = str(_process_gate.get('blocking_reason_code') or '').strip() + if _c_reason_code and isinstance(blocking_reason, dict): + _a_reason_code = str(blocking_reason.get('code') or '').strip() + if _a_reason_code != _c_reason_code: + blocking_reason = { + 'code': _c_reason_code, + 'i18n_key': _REASON_TO_I18N_KEY.get(_c_reason_code) or ( + (blocking_reason or {}).get('i18n_key') + ), + 'details': dict((blocking_reason or {}).get('details') or {}), + } + # ===== [不变] facts 子事实计算(保持不动) ===== facts: dict[str, Any] = { 'inventory_source_status': inventory_source_status_raw or 'unresolved', @@ -1055,25 +1120,13 @@ def apply_user_projection_fields( if isinstance(cand, list): facts['candidate_source_codes'] = [str(c or '').strip().upper() for c in cand if str(c or '').strip()] if notice is not None: - step_payload = getattr(notice, 'step_payload_json', None) - if isinstance(step_payload, dict): - prep = step_payload.get('candidate_inventory_prep') - if isinstance(prep, dict): - facts['prepared_source_codes'] = list(prep.get('loaded_source_codes') or []) - facts['pending_source_codes'] = list(prep.get('missing_source_codes') or []) - resolutions = step_payload.get('line_inventory_resolutions') - if isinstance(resolutions, list): - facts['line_resolutions'] = resolutions[:] - fms = step_payload.get('forced_match_source_code') - if fms: - facts['forced_match_source_code'] = str(fms).strip().upper() - # 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧 - # step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。 + # 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate + # 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。 try: from app.services.shipping_notice.inventory_candidate_projection import ( project_inventory_candidate_facts, ) - candidate_facts = project_inventory_candidate_facts(notice) + candidate_facts = project_inventory_candidate_facts(order_task) if candidate_facts.get('current_set') is not None: facts['candidate_set_id'] = candidate_facts.get('candidate_set_id') facts['candidate_set_version'] = candidate_facts.get('candidate_set_version') @@ -1096,7 +1149,7 @@ def apply_user_projection_fields( # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 try: from app.models import ShippingTaskInventoryRpaAttempt - attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(notice, 'task_no', '') or '')).all() + attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() facts['rpa_attempts'] = [{ 'source_code': a.source_code, 'attempt_no': a.attempt_no, 'source_run_no': a.source_run_no, 'status': a.status, @@ -1107,11 +1160,17 @@ def apply_user_projection_fields( } for a in attempts] except Exception: facts['rpa_attempts'] = [] - if getattr(notice, 'export_artifact_id', None): - facts['export_state'] = 'created' - if getattr(notice, 'upload_status', None): - us = str(getattr(notice, 'upload_status') or '').strip().lower() - facts['upload_state'] = us if us else 'not_created' + try: + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_facts_upload_state, + ) + artifact = latest_export_artifact(order_task or notice) + if artifact is not None: + facts['export_state'] = str(getattr(artifact, 'status', None) or 'created') + facts['upload_state'] = project_facts_upload_state(order_task or notice) + except Exception: # noqa: BLE001 + pass if getattr(notice, 'wecom_sent_at', None): facts['switch_state'] = 'sent' diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 93abf8c2..799aa1dd 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -523,8 +523,6 @@ PROCESS_GATE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ 'FIELD_DERIVED', 'FIELD_DERIVATION_SKIPPED', - 'LINE_NO_OVERRIDDEN', - 'LINE_NO_RESTORED', 'DERIVATION_SIMULATED', 'DERIVATION_RULES_CHANGED', 'ORDER_FROZEN', @@ -823,7 +821,6 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'validation_blocking_count', 'validation_warning_count', 'field_id', - 'line_key', 'previous_value', 'new_value', 'value_source', @@ -858,10 +855,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ # 字段派生 / 覆盖 / 导出血缘(脱敏摘要,禁止邮件/PDF 正文)。 'rule_id', 'rule_checksum', - 'derivation_rules_checksum', 'skip_reason', 'override_reason_code', - 'export_sequence', 'export_artifact_no', 'template_version', 'field_code', @@ -874,7 +869,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'suggestion_pending', 'idempotency_key', 'action_semantics', - 'line_keys', + 'draft_line_ids', + 'snapshot_line_ids', 'routing_status', # Process Gate 恢复摘要(禁止正文、规则 SQL、对象存储 URL)。 'gate_code', diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 6dae0c38..c312255b 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -3,10 +3,13 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。 依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 - state_machine(CheckpointKind)、tool_response、process_gate_bridge。 + process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、 + state_machine(双读回退)、tool_response、process_gate_bridge。 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交 当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留 - 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度。 + 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度; + 早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state; + inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。 """ from __future__ import annotations @@ -19,7 +22,7 @@ from app.services.shipping_notice import fulfillment_workflow from app import db from app.models.shipping_process_gate import ShippingProcessGateAttempt from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, + POSITION_INVENTORY_SOURCE_REVIEW, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, PH_RSV_REQ, @@ -32,12 +35,86 @@ from app.services.shipping_notice.inventory_source_gate import ( ) from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state +from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response +def _entry_user_mode(task) -> str: + """ + 自动推进入口早停:从 Gate 推导用户处置模式。 + + 无活动 Execution 时回退 resolve_task_ui_state.user_mode。 + inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker + 继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 + """ + from app.services.shipping_notice.process_gate_contract import ( + derive_user_mode, + user_mode_for_blocking_reason, + ) + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(task) + if not isinstance(gate, dict) or not gate: + return str(resolve_task_ui_state(task).user_mode) + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = str(gate_view.get('status') or '').strip().lower() + summary_status = str(gate.get('status') or gate.get('gate_status') or '').strip().lower() + gate_code = str(gate.get('current_gate_code') or gate_view.get('gate_code') or '').strip() + reason_code = str( + gate_view.get('blocking_reason_code') + or gate.get('blocking_reason_code') + or '' + ).strip() + # [STEP] 库存准备可自动恢复:候选已冻结但尚无快照时,sync 可能先投影 + # blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由 + # submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。 + if ( + gate_code == 'inventory_preparation' + and status == 'blocked_retryable' + and user_mode_for_blocking_reason(reason_code) == 'retryable_tech' + ): + return 'auto_continue' + if summary_status in {'completed', 'done'}: + user_status = 'completed' + elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked': + user_status = 'waiting_human' + elif status == 'failed_terminal' or summary_status == 'failed': + user_status = 'failed' + else: + user_status = 'running' + return derive_user_mode( + user_status=user_status, + gate_code=gate_code or None, + review_status=getattr(task, 'review_status', None), + lifecycle_stage=gate.get('lifecycle_stage'), + ) + + +def _entry_position(task) -> str | None: + """ + 工具响应下发位置标签:优先 Gate derive_position,否则 resolve_task_ui_state。 + """ + from app.services.shipping_notice.process_gate_contract import derive_position + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(task) + if isinstance(gate, dict) and gate: + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + pos = derive_position( + gate_code=gate.get('current_gate_code') or gate_view.get('gate_code'), + review_status=getattr(task, 'review_status', None), + ) + if pos: + return pos + return resolve_task_ui_state(task).position + + # --------------------------------------------------------------------------- # T5: 唯一 AutoProgress Orchestrator 入口 facade # --------------------------------------------------------------------------- @@ -56,7 +133,7 @@ from app.services.shipping_notice.customer_identity_gate import customer_gate_to _RESUME_GATE_CODE_LEGACY_ENTRY = { # inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现) 'inventory_preparation': 'ensure_inventory', - # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key) + # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次) 'inventory_matching': 'match_inventory', # None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传) 'auto': 'auto_progress_full', @@ -130,8 +207,12 @@ def _dispatch_legacy_orchestration( resume_after_gate: str | None = None, ) -> dict[str, Any]: """ - resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。 - 长期目标:每个 Gate 只在本函数内跑原子 run_one_gate_step();旧实现会逐步下线。 + [DEPRECATED / P0-3 后不可达主路径] resume_gate_code → 旧跨 Gate 串联实现。 + + 正式开心路径已改为 ProcessGate:``submit_auto_progress`` / + ``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 只入队下一 Gate + Attempt;匹配成功不得在此函数内嵌 ``generate_excel`` / ``upload_to_freight``。 + 本函数体暂保留供兼容调用方与测试打桩,不得再作为新编排入口扩展。 """ entry = _RESUME_GATE_CODE_LEGACY_ENTRY.get(resume_gate_code, 'auto_progress_full') base_payload: dict[str, Any] = { @@ -150,7 +231,49 @@ def _dispatch_legacy_orchestration( ) frozen_sources = task_frozen_inventory_source_codes(task) if frozen_sources and len(frozen_sources) >= 1: - prepare_result = ensure_all_required_sources_prepared(task, mode=inventory_mode) + scoped_source_codes: list[str] | None = None + scope_key = str(line_scope_key or '').strip() + if scope_key: + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + + try: + scoped_line_id = int(scope_key) + except (TypeError, ValueError): + scoped_line_id = 0 + from app.models import ShippingOrderSnapshot + + snapshot = ( + db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if getattr(task, 'order_snapshot_id', None) else None + ) + scoped_line = next( + ( + line for line in (getattr(snapshot, 'lines', None) or []) + if int(getattr(line, 'id', 0) or 0) == scoped_line_id + ), + None, + ) + if scoped_line is not None: + candidate_lines = get_active_candidate_lines(task) + candidate_line = next( + ( + line for line in candidate_lines + if int(getattr(line, 'line_no', 0) or 0) == int(getattr(scoped_line, 'line_no', 0) or 0) + ), + None, + ) + scoped_sources = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if scoped_sources: + frozen_sources = scoped_sources + scoped_source_codes = scoped_sources + + prepare_result = ensure_all_required_sources_prepared( + task, mode=inventory_mode, source_codes=scoped_source_codes, + ) if prepare_result.all_prepared: return _legacy_ensure_inventory({**base_payload, '_prepared_sources': prepare_result.prepared_source_codes, '_orchestrator_internal_dispatch': True}) return tool_response( @@ -178,7 +301,7 @@ def _dispatch_legacy_orchestration( if norm_line_scope: return fulfillment_workflow.match_inventory_line( {**base_payload, '_orchestrator_internal_dispatch': True}, - line_key=norm_line_scope, + line_no=int(norm_line_scope), ) return fulfillment_workflow.match_inventory({**base_payload, '_orchestrator_internal_dispatch': True}) return _auto_progress_full(task, base_payload, trigger=trigger, operator_id=operator_id) @@ -265,6 +388,8 @@ def run_task_auto_progress( submitted = submit_auto_progress( task=task, trigger=trigger, operator_id=operator_id, resume_gate_code=resume_gate_code, commit=True, + inventory_mode=inventory_mode, + line_scope_key=line_scope_key, recovery_plan_id=recovery_plan_id, recovery_attempt_id=recovery_attempt_id, resume_after_gate=resume_after_gate, @@ -377,7 +502,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: 【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。 亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。 - 核心逻辑:先按 checkpoint_kind 处理早停;WAIT_MANUAL_UPLOAD 在 AUTO_UPLOAD 开启时 + 核心逻辑:先按 Gate derive_user_mode 处理早停(无 Execution 回退 user_mode); + WAIT_MANUAL_UPLOAD / wait_manual_upload 在 AUTO_UPLOAD 开启时 不早停、落入履约链触发货代 RPA;关闭时才对齐 manual_upload_pending 并禁止自动上传。 再检查解析门禁与客户/库存源,库存就绪后委托 fulfillment_workflow 同一编排链。 Args: @@ -411,21 +537,22 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: # 正式 20-Gate 编排仍由后续分支负责;这里仅返回用户可执行的当前结果。 early_task = resolve_task_from_payload({'task_no': task_no}) if task_no else None if early_task is not None: - early_ui = resolve_task_ui_state(early_task) - if early_ui.checkpoint_kind == CheckpointKind.MUST_HUMAN: + early_mode = _entry_user_mode(early_task) + early_position = _entry_position(early_task) + if early_mode == 'must_human': return tool_response( status='needs_human', task=early_task, message='当前任务需要人工处理,已暂停自动推进。', data=serialize_task_for_tool(early_task), - checkpoint=early_ui.checkpoint, + position=early_position, stop_agent_turn=True, ) - if early_ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD and not fulfillment_workflow.is_auto_upload_enabled(): + if early_mode == 'wait_manual_upload' and not fulfillment_workflow.is_auto_upload_enabled(): return tool_response( status='ok', task=early_task, message='Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。', data=serialize_task_for_tool(early_task), - checkpoint=early_ui.checkpoint, + position=early_position, stop_agent_turn=True, forbidden_next_tools=['upload_to_freight'], ) @@ -491,25 +618,26 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: steps: list[str] = [] - # [STEP 0] STP 检查点早停:必须人工、待人工上传登记或已完成时不产生新副作用。 - ui_early = resolve_task_ui_state(task) - if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN: + # [STEP 0] Gate 粗分类早停:必须人工、待人工上传登记或已完成时不产生新副作用。 + early_mode = _entry_user_mode(task) + early_position = _entry_position(task) + if early_mode == 'must_human': return tool_response( status="needs_human", task=task, message="当前任务需要人工处理,已暂停自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, ) - if ui_early.checkpoint_kind == CheckpointKind.COMPLETE: + if early_mode == 'complete': return tool_response( status="ok", task=task, message="任务已结束,无需自动推进。", data=serialize_task_for_tool(task), ) - if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD: + if early_mode == 'wait_manual_upload': pending = str(getattr(task, 'pending_human_reason', '') or '').strip() # RPA 已触发/失败:只对齐细粒度投影,不再重复编排。 if pending in {'upload_rpa_pending', 'upload_rpa_failed'}: @@ -539,7 +667,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: else '货代上传 RPA 失败,请在对话侧恢复或改人工登记。' ), data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, ) # AUTO_UPLOAD 开启:与 fulfillment 链统一,继续向下触发上传,禁止在此早停。 @@ -569,7 +697,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: task=task, message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, forbidden_next_tools=["upload_to_freight"], ) @@ -583,29 +711,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: threshold = 0.7 confidence = None try: - confidence = float(task.parse_confidence) if task.parse_confidence is not None else None + parse_validation = (task.step_payload_json or {}).get('parse_validation') if isinstance(getattr(task, 'step_payload_json', None), dict) else None + raw_confidence = parse_validation.get('confidence') if isinstance(parse_validation, dict) else None + confidence = float(raw_confidence) if raw_confidence is not None else None except (TypeError, ValueError): confidence = None - if task.review_status == RS_RSV_REQ or task.pending_human_reason == PH_RSV_REQ: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + blocking_reason = task_blocking_reason(task) + if task.review_status == RS_RSV_REQ or blocking_reason == PH_RSV_REQ: ui = resolve_task_ui_state(task) return tool_response( status="needs_human", task=task, message="订单仍缺少后续处理必需字段,请先补充后再继续。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], ) - if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF: + if task.review_status == RS_PARSE_REVIEW or blocking_reason == PH_LOW_CONF: ui = resolve_task_ui_state(task) return tool_response( status="needs_human", task=task, message="发货通知解析需要人工确认后才能自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, ) if confidence is not None and confidence < threshold: @@ -615,7 +748,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=f"解析置信度 {confidence:.2f} 低于阈值 {threshold:.2f},请人工确认后再自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, ) @@ -623,7 +756,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: if customer_gate is not None: return customer_gate - if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): + if blocking_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): adjudication = ensure_inventory_source_review_state(task) db.session.commit() if not is_inventory_source_stable(task): @@ -639,12 +772,13 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: "inventory_source_reason": adjudication.reason, "destination_candidates": adjudication.destination_candidates, }, - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) # [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。 - if not task.inventory_lines_json: + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + if not has_ready_inventory_file_for_task(task): lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"} if lang: @@ -660,7 +794,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: else: steps.append("载入库存") - # [STEP 3] 库存就绪后进入履约侧自动推进(与 try_auto_chain 同一语义:可含货代 RPA)。 + # [STEP 3] 库存就绪后进入履约侧自动推进。 + # [DEPRECATED] 旧语义曾与 try_auto_chain 同 Attempt 串联 generate±upload; + # P0-3 / 编排分离后正式路径为独立 Gate Attempt,本 legacy 体仅兼容残留入口。 fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps) # [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。 diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 527912ac..843410e0 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -10,13 +10,17 @@ services/shipping_notice/query_service.py tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉; SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event, 以及统一 shipping_processing_status / progress_version / order_task_no(BE-02), + 直接序列化 ShippingOrderTask 时 order_task_no 取自身 task_no(禁止经 order_task_id 冲 null), 并注入 review_run_no 供任务中心深链订单处理工作台(UI-04); list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办; serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create; - 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与 Task(客户快照/来源文件名); - 待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT, - 仅水合当前页(禁止 500 截断冒充总数); + 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与确认客户/来源文档; + 待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);无 Execution 回退 position/user_mode; + SQL CASE 仍为粗筛近似(双读过渡,与 Gate 可能短暂漂移); + list 用 UNION ALL + COUNT/OFFSET/LIMIT,仅水合当前页(禁止 500 截断冒充总数); + fetch_gate_positions 批量读 Execution.current_gate_code,供 Gate 推导待办避免 N+1; DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact); + view=workbench 跳过 SUMMARY/DETAIL 重投影,仅身份壳 + enrich(ui_state),禁止算完再删; co8 起 WorkflowItem 账本已下线,不再附加 workflow_item 投影(BE-06); 订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。 """ @@ -29,6 +33,7 @@ from pathlib import Path from typing import Any from sqlalchemy import String, asc, case, cast, desc, exists, func, literal, select, union_all +from sqlalchemy.orm import aliased from app import db from app.core.errors import ValidationError @@ -37,6 +42,7 @@ from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, ShippingInventoryVerification, + ShippingInventoryFile, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, @@ -46,19 +52,23 @@ from app.models import ( ShippingOrderLine, ShippingOrderReviewCase, ShippingOrderSnapshot, + ShippingOrderSnapshotLine, ShippingOrderReviewStream, ShippingOrderSubmission, ShippingReservation, ShippingNotice, + ShippingOrderTask, + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingProcessExecution, + ShippingProcessGate, + ShippingTaskInventoryLink, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, ShippingTaskEvent, ShippingUploadAttempt, ) from app.services.shipping_notice.constants import ( - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_PARSE_REVIEW, - CP_RSV_REQ, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, @@ -75,10 +85,10 @@ from app.services.shipping_notice.constants import ( RS_RSV_REQ, RS_SHORTAGE_REVIEW, ) +from app.services.shipping_notice.upload_attempt_service import latest_export_artifact from app.services.shipping_notice.state_machine import ( - CheckpointKind, + UserMode, resolve_task_ui_state, - resolve_task_ui_state_from_fields, ) from app.services.shipping_notice.task_order_field_editor import ( current_header_field_values_or_empty, @@ -92,13 +102,14 @@ EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml. _TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE) _BUSINESS_NO_RE = re.compile(r"(? ShippingOrderCandidate | None: + """ + 定位同一文件当前可复核 Candidate,不依赖单个 Case 的 ``candidate_id``。 + + 触发时机:Review Case 的生命周期投影需要裁决「是否已进入订单复核」时,遇到 + 重解析时序(doc67)——Stream.current_case 可能仍是空的旧 Case(``candidate_id=None``), + 而真正带可复核 Candidate 的是同文档另一 Case。若只读当前 Case 的 candidate_id, + 会把「PO + 订单明细已识别、仅被阻塞需人工复核」的文档误压回「接收解析」。 + + 核心逻辑:先按 document_id 遍历同文档已回链 Candidate 的 Case,找到满足 + ``is_current_reviewable_candidate`` 的 Candidate;回退时按主文档直查。空、过期或 + 被替代 Candidate 一律不开放候选上下文。 + + Args: + document_id: Review Case 的源文档 ID。 + + Returns: + 当前可复核 Candidate;无有效候选时返回 None。 + """ + from app.services.shipping_notice.candidate_service import ( + is_current_reviewable_candidate, + ) + + if document_id is None: + return None + for sibling in ( + ShippingOrderReviewCase.query + .filter( + ShippingOrderReviewCase.document_id == int(document_id), + ShippingOrderReviewCase.candidate_id.isnot(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .all() + ): + candidate = db.session.get(ShippingOrderCandidate, int(sibling.candidate_id)) + if is_current_reviewable_candidate(candidate): + return candidate + candidate = ( + ShippingOrderCandidate.query + .filter(ShippingOrderCandidate.primary_document_id == int(document_id)) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) + return candidate if is_current_reviewable_candidate(candidate) else None + + def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]: """复用统一生命周期投影裁决 Review Case 的当前阶段与入口。 当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。 此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。 + 候选上下文按「文件」粒度裁决:当前 Case 落到空旧 Case(``candidate_id=None``) + 时,回退定位该文件真实可复核 Candidate,避免已识别+阻塞文档被压回接收解析。 """ candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id is not None else None ) - from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate + from app.services.shipping_notice.candidate_service import ( + is_current_reviewable_candidate, + ) from app.services.shipping_notice.lifecycle_projection import project_lifecycle has_candidate_context = is_current_reviewable_candidate(candidate) + if not has_candidate_context: + # doc67 类重解析时序:Stream.current_case 可能是空旧 Case,真实可复核 + # Candidate 在同文档另一 Case。按文件粒度回退定位,禁止把已解析+阻塞 + # 文档误投影为「接收解析」。 + candidate = _current_reviewable_candidate_for_document( + getattr(case, 'document_id', None), + ) + has_candidate_context = candidate is not None if has_candidate_context: return project_lifecycle( current_gate=None, @@ -176,19 +247,22 @@ class TaskProjection(str, Enum): def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" - verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by( + inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id) + verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by( ShippingInventoryVerification.created_at, ShippingInventoryVerification.id, ).all() - artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by( - ShippingExportArtifact.created_at, ShippingExportArtifact.id, - ).all() + artifacts = [] + if isinstance(task, ShippingNotice): + artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by( + ShippingExportArtifact.created_at, ShippingExportArtifact.id, + ).all() artifact_ids = [item.id for item in artifacts] artifact_lines = ShippingExportArtifactLine.query.filter( ShippingExportArtifactLine.artifact_id.in_(artifact_ids), ).all() if artifact_ids else [] reservation_ids = { item.id: item.reservation_id - for item in ShippingReservation.query.filter(ShippingReservation.task_id == task.id).all() + for item in ShippingReservation.query.filter(ShippingReservation.task_id == inventory_task_id).all() } reservations_by_artifact: dict[int, list[str]] = {} for line in artifact_lines: @@ -224,11 +298,14 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] } -def get_task_by_ref(task_ref: str) -> ShippingNotice | None: - """按 task_no、business_no 或数字主键精确查找 Notice。""" +def get_task_by_ref(task_ref: str) -> ShippingOrderTask | ShippingNotice | None: + """按 OT task_no 查找订单任务;业务编号/Notice 主键仅用于正式通知专用查询。""" value = str(task_ref or "").strip() if not value: return None + task = ShippingOrderTask.query.filter_by(task_no=value).first() + if task: + return task task = ShippingNotice.query.filter_by(task_no=value).first() if task: return task @@ -236,7 +313,7 @@ def get_task_by_ref(task_ref: str) -> ShippingNotice | None: if task: return task if value.isdigit(): - return db.session.get(ShippingNotice, int(value)) + return db.session.get(ShippingOrderTask, int(value)) or db.session.get(ShippingNotice, int(value)) return None @@ -279,13 +356,13 @@ def resolve_order_extraction_ui_target( # co8 起 Intake.consumed_batch_id 已删除;仅通过 Candidate→Task 反查已有任务。 task = ( - db.session.query(ShippingNotice) - .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingNotice.id) + db.session.query(ShippingOrderTask) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( ShippingOrderCandidate.intake_id.in_([int(item.id) for item in intakes]), - ShippingNotice.user_id == int(user_id), + ShippingOrderTask.user_id == int(user_id), ) - .order_by(ShippingOrderCandidate.id.asc(), ShippingNotice.id.asc()) + .order_by(ShippingOrderCandidate.id.asc(), ShippingOrderTask.id.asc()) .first() ) return None, task @@ -293,7 +370,7 @@ def resolve_order_extraction_ui_target( def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None: """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" - if not task or not task.export_file_path: + if not task or isinstance(task, ShippingOrderTask) or getattr(task, 'id', None) is None: return None from app.models import ShippingExportArtifact # 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel; @@ -301,7 +378,6 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str artifact = ShippingExportArtifact.query.filter( ShippingExportArtifact.task_id == task.id, ShippingExportArtifact.status.in_({'ready', 'uploaded'}), - ShippingExportArtifact.file_path == task.export_file_path, ).order_by( ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), ).first() @@ -315,7 +391,7 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str def task_export_error_message(task: ShippingNotice | None) -> str: """导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。""" - if not task or task.id is None or not task.export_file_path: + if not task or task.id is None: return "export file not found" resolved = resolve_task_export_download(task) if resolved is None: @@ -334,7 +410,7 @@ def resolve_task_from_payload( payload: dict[str, Any], *, allow_conversation_fallback: bool = True, -) -> ShippingNotice | None: +) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。 @@ -362,9 +438,9 @@ def resolve_task_from_payload( conv_id = str(payload.get("conversation_id") or "").strip() if conv_id: candidates = ( - ShippingNotice.query.filter_by(conversation_id=conv_id) - .filter(ShippingNotice.lifecycle_status == "active") - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query.filter_by(conversation_id=conv_id) + .filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'})) + .order_by(ShippingOrderTask.id.desc()) .limit(2) .all() ) @@ -375,39 +451,81 @@ def resolve_task_from_payload( def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: """Tool data 基础字段(裁剪前)。""" + if isinstance(task, ShippingOrderTask): + header, lines, _field_display = _order_values_for_projection(task) + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(task.id).values()) + customer = _order_task_customer_projection(task) + inventory = _order_task_inventory_projection(task) + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + shortage = {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]} + return { + 'task_no': task.task_no, + 'order_task_no': task.task_no, + 'current_step': task.stage, + 'stage': task.stage, + 'status': task.status, + 'customer_name': header.get('customer_name'), + 'customer_code': header.get('customer_code'), + 'customer_resolution_status': customer['status'], + 'customer_resolution_method': customer['resolution_method'], + 'customer_id': customer['customer_id'], + 'customer_name_snapshot': customer['customer_name_snapshot'], + 'customer_short_code_snapshot': customer['customer_short_code_snapshot'], + 'ship_to': header.get('ship_to') or header.get('ship_to_address'), + 'po_number': header.get('po_number'), + 'required_date': header.get('required_date'), + 'lines': lines, + 'shortage': shortage, + 'line_results': match_facts, + 'pending_human_reason': task_blocking_reason(task), + 'error_message': task.error_message, + 'conversation_id': task.conversation_id, + 'step_payload': task.step_payload_json or {}, + **inventory, + 'inventory_snapshot': _serialize_inventory_snapshot(task), + } from app.services.shipping_notice.notice_upload import max_notice_chars from app.services.shipping_notice.rpa import rpa_runtime_mode - step_payload = task.step_payload_json or {} - header = current_header_field_values_or_empty(task) + workflow_owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if getattr(task, 'order_task_id', None) else task + ) + match_projection = _current_match_projection(workflow_owner) + artifact, upload_attempt = _latest_export_upload_facts(task) + step_payload = getattr(workflow_owner, 'step_payload_json', None) or {} + header = current_header_field_values_or_empty(workflow_owner) + customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {} payload: dict[str, Any] = { "task_no": task.task_no, - "business_no": task.business_no, - "current_step": task.current_step, - "review_status": task.review_status, - "match_status": task.match_status, - "pending_human_reason": task.pending_human_reason, - "customer_name": header.get('customer_name') or header.get('bill_to_customer'), + "business_no": getattr(task, 'business_no', None), + "current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None), + "review_status": getattr(workflow_owner, 'review_status', None), + "match_status": match_projection['match_status'], + "pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None), + "customer_name": header.get('customer_name'), "customer_code": header.get('customer_code'), - "customer_resolution_status": task.customer_resolution_status, - "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.customer_id, - "customer_name_snapshot": task.customer_name_snapshot, - "customer_short_code_snapshot": task.customer_short_code_snapshot, + "customer_resolution_status": customer_projection.get('status'), + "customer_resolution_method": customer_projection.get('resolution_method'), + "customer_id": customer_projection.get('customer_id'), + "customer_name_snapshot": customer_projection.get('customer_name_snapshot'), + "customer_short_code_snapshot": customer_projection.get('customer_short_code_snapshot'), "ship_to": header.get('ship_to') or header.get('ship_to_address'), "po_number": header.get('po_number'), "required_date": header.get('required_date'), - "lines": current_line_field_values_or_empty(task), - "shortage": task.shortage_json, - "line_results": task.line_results_json, - "export_file_name": task.export_file_name, - "freight_ref_no": task.freight_ref_no, - "error_message": task.error_message, + "lines": current_line_field_values_or_empty(workflow_owner), + "shortage": match_projection['shortage'], + "line_results": match_projection['line_results'], + "export_file_name": getattr(artifact, 'file_name', None), + "freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None), + "error_message": getattr(workflow_owner, 'error_message', None), "conversation_id": task.conversation_id, - "step_payload": step_payload, + "step_payload": getattr(workflow_owner, 'step_payload_json', None) or {}, "rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None), } - raw_content = str(task.raw_content or "").strip() + raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip() lines = payload["lines"] from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link @@ -421,6 +539,84 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: return payload +def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: + """从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。""" + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + rows = list(load_current_match_facts_by_task(task_id).values()) + shortage_rows = [ + row for row in rows + if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + or str(row.get('match_result') or '').strip().lower() != 'matched' + ] + return { + 'match_status': 'unfulfillable' if shortage_rows else ('fulfillable' if rows else None), + 'shortage': {'lines': shortage_rows}, + 'line_results': rows, + } +def _latest_export_upload_facts(task: ShippingNotice) -> tuple[Any | None, Any | None]: + """读取最新导出 Artifact 与上传 Attempt,作为正式 Notice 的只读运行投影。""" + artifact = latest_export_artifact(task) + attempt = ( + ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)) + .order_by(ShippingUploadAttempt.attempt_no.desc(), ShippingUploadAttempt.id.desc()).first() + if artifact is not None else None + ) + return artifact, attempt + + +def _snapshot_order_values(snapshot: ShippingOrderSnapshot) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]: + """按冻结时的 Schema 还原订单头、订单行及展示契约,禁止回读可变 Extraction。""" + fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or []) + header_configs = [item for item in fields if item.get('scope') == 'header'] + line_configs = [item for item in fields if item.get('scope') == 'line'] + + def _display(config: dict[str, Any]) -> dict[str, Any]: + return { + 'field_code': str(config.get('field_code') or ''), + 'display_name': str(config.get('display_name') or config.get('field_code') or ''), + 'scope': str(config.get('scope') or ''), + 'value_type': str(config.get('value_type') or 'string'), + 'sequence': int(config.get('sequence') or 0), + } + + header_values = dict(snapshot.header_values_json or {}) + header = { + str(config.get('field_code') or ''): header_values.get(str(config.get('field_id') or '')) + for config in header_configs + if str(config.get('field_code') or '') + } + lines = [ + { + str(config.get('field_code') or ''): dict(line.field_values_json or {}).get(str(config.get('field_id') or '')) + for config in line_configs + if str(config.get('field_code') or '') + } + for line in sorted(snapshot.lines, key=lambda item: (int(item.position), int(item.id))) + ] + return header, lines, { + 'header_fields': [_display(config) for config in header_configs], + 'line_fields': [_display(config) for config in line_configs], + } + + +def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]: + """冻结后统一读取 Snapshot;冻结前才允许读取当前已接受的 Extraction。""" + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + if snapshot is not None: + return _snapshot_order_values(snapshot) + return ( + current_header_field_values_or_empty(owner), + current_line_field_values_or_empty(owner), + current_order_field_display_or_empty(owner), + ) + + def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None: """工作台任务摘要中的库存快照投影。""" from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link @@ -428,6 +624,47 @@ def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None return serialize_inventory_snapshot_link(task) +def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]: + """从正式客户识别结果读取 OT 客户确认事实。""" + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + + facts = customer_resolution_facts(task) + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None + resolution = facts['resolution'] + return { + 'customer_id': facts['customer_id'], + 'customer_name_snapshot': getattr(customer, 'standard_name', None), + 'customer_short_code_snapshot': getattr(customer, 'short_code', None), + 'status': facts['status'], + 'resolution_method': getattr(resolution, 'confirmation_method', None), + } + + +def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]: + """从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。""" + from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts + + facts = project_inventory_candidate_facts(task) + sources = list(facts.get('sources') or []) + source_codes = [str(item.get('source_code') or '').strip().upper() for item in sources] + source_codes = [item for item in source_codes if item] + single_source = source_codes[0] if len(source_codes) == 1 else None + versions = { + str(item.get('source_config_version') or '').strip() + for item in sources if str(item.get('source_config_version') or '').strip() + } + return { + 'inventory_source_code': single_source, + 'inventory_source_status': 'candidates_frozen' if facts.get('current_set') else 'unresolved', + 'inventory_source_method': 'candidate_set' if facts.get('current_set') else None, + 'inventory_source_config_version': next(iter(versions)) if len(versions) == 1 else None, + 'inventory_routing_fingerprint': ( + (facts.get('current_set') or {}).get('input_fingerprint') + if isinstance(facts.get('current_set'), dict) else None + ), + } + + def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: """ 组装任务版本链与重复决策投影字段。 @@ -450,6 +687,7 @@ def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: src = db.session.get(ShippingNotice, int(task.duplicate_source_task_id)) if src is not None: duplicate_source_task_no = src.task_no + candidate = db.session.get(ShippingOrderCandidate, task.source_candidate_id) if getattr(task, 'source_candidate_id', None) else None return { 'document_version': int(task.document_version or 1), 'supersedes_task_no': supersedes_task_no, @@ -457,8 +695,8 @@ def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: 'duplicate_source_task_no': duplicate_source_task_no, 'duplicate_resolution_type': task.duplicate_resolution_type, 'duplicate_override_reason': task.duplicate_override_reason, - 'business_fingerprint': task.business_fingerprint, - 'fingerprint_version': task.fingerprint_version, + 'business_fingerprint': getattr(candidate, 'business_fingerprint', None), + 'fingerprint_version': getattr(candidate, 'fingerprint_version', None), } @@ -485,7 +723,7 @@ def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, An 并投影当前字段裁决与不可变 Observation 历史; Candidate 已清理或不存在时返回 None,不阻断 Task Detail。 """ - if not task.source_candidate_id: + if not getattr(task, 'source_candidate_id', None): return None candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) if candidate is None: @@ -518,6 +756,11 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str """按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。""" from app.services.shipping_notice.rpa import rpa_runtime_mode + workflow_owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if getattr(task, 'order_task_id', None) else task + ) + if projection == TaskProjection.TOOL: from app.services.shipping_notice.user_facing_status import strip_internal_task_fields @@ -525,55 +768,139 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str if projection == TaskProjection.TOOL_INTERNAL: return _task_tool_payload(task) if projection == TaskProjection.SUMMARY: - step_payload = task.step_payload_json or {} - header = current_header_field_values_or_empty(task) + if isinstance(task, ShippingOrderTask): + header, _lines, _field_display = _order_values_for_projection(task) + customer = _order_task_customer_projection(task) + inventory = _order_task_inventory_projection(task) + from app.services.shipping_notice.task_disposition_service import task_disposition_capability + disposition_capabilities = { + action: { + 'allowed': result.allowed, + 'code': result.code, + 'reason': result.reason, + } + for action in ('delete', 'void', 'archive', 'restore') + for result in (task_disposition_capability(task, action),) + } + step_payload = task.step_payload_json or {} + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(task.id).values()) + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + has_shortage = any( + str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + or str(row.get('match_result') or '').strip().lower() != 'matched' + for row in match_facts + ) + return { + 'id': task.id, + 'task_no': task.task_no, + 'order_task_no': task.task_no, + 'source_type': task.source_type, + 'customer_name': header.get('customer_name'), + 'customer_id': customer['customer_id'], + 'customer_name_snapshot': customer['customer_name_snapshot'], + 'customer_short_code_snapshot': customer['customer_short_code_snapshot'], + 'current_step': task.stage, + 'stage': task.stage, + 'status': task.status, + 'lifecycle_status': str(getattr(task, 'lifecycle_status', 'active') or 'active'), + 'deleted_at': task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None, + 'voided_at': task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None, + 'void_reason': getattr(task, 'void_reason', None), + 'archived_at': task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None, + 'match_status': ('unfulfillable' if has_shortage else ('fulfillable' if match_facts else None)), + 'pending_human_reason': task_blocking_reason(task), + 'error_message': task.error_message, + 'conversation_id': task.conversation_id, + 'step_payload': step_payload, + 'destination_code': header.get('destination_code'), + 'destination_city': header.get('destination_city'), + 'destination_country': header.get('destination_country'), + 'warehouse_hint': header.get('warehouse_hint'), + **inventory, + 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, + 'line_results': match_facts, + 'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None), + 'progress_version': task.progress_version, + 'created_at': task.created_at.isoformat() if task.created_at else None, + 'updated_at': task.updated_at.isoformat() if task.updated_at else None, + 'disposition_capabilities': disposition_capabilities, + } + workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {} + step_payload = workflow_payload + header = current_header_field_values_or_empty(workflow_owner) + from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + inventory_facts = active_inventory_runtime_facts(workflow_owner) + source_codes = task_frozen_inventory_source_codes(workflow_owner) + routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {}) + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + match_task_id = getattr(workflow_owner, 'id', None) or task.id + match_facts = list(load_current_match_facts_by_task(match_task_id).values()) + match_status_projection = ( + 'unfulfillable' if any( + str(row.get('match_result') or '').strip().lower() != 'matched' + or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + for row in match_facts + ) else ('fulfillable' if match_facts else None) + ) + artifact, upload_attempt = _latest_export_upload_facts(task) + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + upload_status_projection = project_notice_upload_status(task) + customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {} + source_candidate = db.session.get(ShippingOrderCandidate, workflow_owner.candidate_id) if isinstance(workflow_owner, ShippingOrderTask) and workflow_owner.candidate_id else None + source_document = db.session.get(ShippingOrderDocument, source_candidate.primary_document_id) if source_candidate and source_candidate.primary_document_id else None data = { "id": task.id, "task_no": task.task_no, "business_no": task.business_no, "source_type": task.source_type, - "source_file_name": task.source_file_name, - "source_file_type": task.source_file_type, - "customer_name": header.get('customer_name') or header.get('bill_to_customer'), - "customer_resolution_status": task.customer_resolution_status, - "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.customer_id, - "customer_name_snapshot": task.customer_name_snapshot, - "customer_short_code_snapshot": task.customer_short_code_snapshot, - "current_step": task.current_step, - "review_status": task.review_status, - "match_status": task.match_status, - "upload_status": task.upload_status, - "upload_mode": task.upload_mode, - "upload_attempt": task.upload_attempt, - "pending_human_reason": task.pending_human_reason, - "error_message": task.error_message or task.upload_error_message, + "source_file_name": getattr(source_document, 'filename', None), + "source_file_type": getattr(workflow_owner, 'source_type', None), + "customer_name": header.get('customer_name'), + "customer_resolution_status": customer_projection.get('status'), + "customer_resolution_method": customer_projection.get('resolution_method'), + "customer_id": customer_projection.get('customer_id'), + "customer_name_snapshot": customer_projection.get('customer_name_snapshot'), + "customer_short_code_snapshot": customer_projection.get('customer_short_code_snapshot'), + "current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None), + "review_status": getattr(workflow_owner, 'review_status', None), + "match_status": match_status_projection, + "upload_status": upload_status_projection, + "upload_mode": getattr(upload_attempt, 'mode', None), + "upload_attempt": getattr(upload_attempt, 'attempt_no', None), + "pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None), + "error_message": getattr(workflow_owner, 'error_message', None) or getattr(upload_attempt, 'error_message', None), "lifecycle_status": str(getattr(task, 'lifecycle_status', 'active') or 'active'), "deleted_at": task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None, "voided_at": task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None, "void_reason": getattr(task, 'void_reason', None), "archived_at": task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None, "conversation_id": task.conversation_id, - "export_file_name": task.export_file_name, - "freight_ref_no": task.freight_ref_no, + "export_file_name": getattr(artifact, 'file_name', None), + "freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None), + "export_version": getattr(artifact, 'id', None), + "idempotency_key": getattr(upload_attempt, 'idempotency_key', None), "step_payload": step_payload, "rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None), "rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None, "inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None, - "destination_code": task.destination_code, - "destination_city": task.destination_city, - "destination_country": task.destination_country, - "warehouse_hint": task.warehouse_hint, - "inventory_source_code": task.inventory_source_code, - "inventory_connector_type": task.inventory_connector_type, - "inventory_warehouse_id": task.inventory_warehouse_id, - "inventory_source_status": task.inventory_source_status, - "inventory_source_method": task.inventory_source_method, - "inventory_source_config_version": task.inventory_source_config_version, - "inventory_routing_fingerprint": task.inventory_routing_fingerprint, - "inventory_snapshot": _serialize_inventory_snapshot(task), - "shortage": task.shortage_json, - "line_results": task.line_results_json or [], + "destination_code": header.get('destination_code'), + "destination_city": header.get('destination_city'), + "destination_country": header.get('destination_country'), + "warehouse_hint": header.get('warehouse_hint'), + "inventory_source_code": source_codes[0] if len(source_codes) == 1 else None, + "inventory_warehouse_id": (_serialize_inventory_snapshot(workflow_owner) or {}).get("warehouse_id"), + "inventory_source_status": 'resolved' if len(source_codes) == 1 else ('candidates_frozen' if source_codes else 'unresolved'), + "inventory_source_method": routing.get('adjudication_method'), + "inventory_source_config_version": inventory_facts.get('source_config_version'), + "inventory_routing_fingerprint": routing.get('routing_fingerprint'), + "inventory_snapshot": _serialize_inventory_snapshot(workflow_owner), + "shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, + "line_results": match_facts, "created_at": task.created_at.isoformat() if task.created_at else None, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } @@ -591,33 +918,58 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str } return data if projection == TaskProjection.DETAIL: - step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - header = current_header_field_values_or_empty(task) - order_field_display = current_order_field_display_or_empty(task) + if isinstance(task, ShippingOrderTask): + from app.services.shipping_notice.task_disposition_service import task_disposition_capability + data = serialize_task(task, TaskProjection.SUMMARY) + header, lines, field_display = _order_values_for_projection(task) + data.update({ + 'lines': lines, + 'order_header': header, + 'order_header_fields': field_display['header_fields'], + 'order_line_fields': field_display['line_fields'], + 'order_snapshot_id': task.order_snapshot_id, + 'order_data_version': int(task.order_data_version or 1), + 'parse_validation': _dict_or_none((task.step_payload_json or {}).get('parse_validation')), + 'process_field_gate': _dict_or_none((task.step_payload_json or {}).get('process_field_gate')), + }) + data['disposition_capabilities'] = data.get('disposition_capabilities') or { + action: { + 'allowed': result.allowed, + 'code': result.code, + 'reason': result.reason, + } + for action in ('delete', 'void', 'archive', 'restore') + for result in (task_disposition_capability(task, action),) + } + return data + step_payload = getattr(workflow_owner, 'step_payload_json', None) if isinstance(getattr(workflow_owner, 'step_payload_json', None), dict) else {} + header = current_header_field_values_or_empty(workflow_owner) + order_field_display = current_order_field_display_or_empty(workflow_owner) data = serialize_task(task, TaskProjection.SUMMARY) + match_projection = _current_match_projection(task) data.update({ "customer_code": header.get('customer_code'), "ship_to": header.get('ship_to') or header.get('ship_to_address'), "po_number": header.get('po_number'), "required_date": header.get('required_date'), "step_payload": step_payload, - "export_version": task.export_version, - "idempotency_key": task.idempotency_key, - "lines": current_line_field_values_or_empty(task), + "export_version": getattr(_latest_export_upload_facts(task)[0], 'id', None), + "idempotency_key": getattr(_latest_export_upload_facts(task)[1], 'idempotency_key', None), + "lines": current_line_field_values_or_empty(workflow_owner), "order_header": header, "order_header_fields": order_field_display['header_fields'], "order_line_fields": order_field_display['line_fields'], - "shortage": task.shortage_json, - "line_results": task.line_results_json or [], - "parse_confidence": task.parse_confidence, - "error_message": task.error_message, + "shortage": match_projection['shortage'], + "line_results": match_projection['line_results'], + "parse_confidence": getattr(workflow_owner, 'parse_confidence', None), + "error_message": getattr(workflow_owner, 'error_message', None), # [STEP] 稳定顶层投影解析门禁与来源 Candidate 审计,供工作台持久只读展示。 "parse_validation": _dict_or_none(step_payload.get("parse_validation")), "process_field_gate": _dict_or_none(step_payload.get("process_field_gate")), "source_candidate": _serialize_source_candidate_projection(task), # 工作台据此隐藏冻结按钮;是否可冻结仍由写路径重算,不能信任前端状态。 - "order_snapshot_id": task.order_snapshot_id, - "order_data_version": int(task.order_data_version or 1), + "order_snapshot_id": getattr(workflow_owner, 'order_snapshot_id', None), + "order_data_version": int(getattr(workflow_owner, 'order_data_version', 1) or 1), "field_conflicts": _serialize_open_field_conflicts(task), **_fulfillment_timeline(task), "events": [ @@ -631,7 +983,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "after_json": e.after_json, "created_at": e.created_at.isoformat() if e.created_at else None, } - for e in sorted(task.events or [], key=lambda x: x.created_at or "") + for e in sorted(getattr(task, 'events', None) or [], key=lambda x: x.created_at or "") ], }) return data @@ -643,30 +995,153 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]: return serialize_task(task, TaskProjection.TOOL) -def task_todo_category(task: ShippingNotice) -> str: +def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict[str, Any]]: """ - 由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。 + 一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。 - 核心逻辑:wait_manual_upload→manual_upload(含 Excel 导出后待登记); - complete→done;must_human 且属复核入口→review,其余 must_human→exception; - auto_continue→in_progress。 - 筛选 manual_upload 时 SQL 侧亦覆盖 waiting_upload / 有导出文件的任务。 + 核心逻辑:``ShippingProcessExecution.task_id IN (...)``;同 task 多 Execution 时 + 后写入覆盖前写入(调用方若需 active-only 可再滤 status)。 + + Args: + task_ids: OT 主键列表。 + + Returns: + ``{task_id: {'current_gate_code', 'status'}}``;无命中的 id 不出现。 + """ + from app.models import ShippingProcessExecution + + ids = [int(i) for i in task_ids if i is not None] + if not ids: + return {} + rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all() + return { + int(getattr(r, 'task_id', 0)): { + 'current_gate_code': getattr(r, 'current_gate_code', None), + 'status': getattr(r, 'status', None), + } + for r in rows + if getattr(r, 'task_id', None) is not None + } + + +def _user_status_from_gate_pos(gate_pos: dict[str, Any] | None) -> str: + """ + 将 Execution / Gate 摘要 status 粗映射为 derive_user_mode 的 user_status。 + + 核心逻辑:blocked* → waiting_human;completed/done → completed;failed* → failed;其余 running。 + """ + if not isinstance(gate_pos, dict): + return 'running' + status = str(gate_pos.get('status') or '').strip().lower() + if status in {'blocked_manual', 'blocked_retryable', 'blocked'}: + return 'waiting_human' + if status in {'completed', 'done'}: + return 'completed' + if status in {'failed_terminal', 'failed'}: + return 'failed' + return 'running' + + +def _todo_category_from_gate( + gate_pos: dict[str, Any] | None, + review_status: Any, + *, + lifecycle_stage: str | None = None, +) -> str: + """ + 从 Gate 位置推导 todo_category(替代 user_mode 路径)。 + + 核心逻辑:derive_user_mode + derive_position → derive_todo_category。 + + Args: + gate_pos: ``{'current_gate_code', 'status'}``;可为 None(仅靠 review_status)。 + review_status: 任务复核处置。 + lifecycle_stage: 可选生命周期,供 wait_manual_upload 判定。 Returns: review | exception | manual_upload | in_progress | done """ + from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, + ) + + pos_payload = gate_pos if isinstance(gate_pos, dict) else {} + user_mode = derive_user_mode( + user_status=_user_status_from_gate_pos(pos_payload), + gate_code=pos_payload.get('current_gate_code'), + review_status=review_status, + lifecycle_stage=lifecycle_stage, + ) + position = derive_position( + gate_code=pos_payload.get('current_gate_code'), + review_status=review_status, + ) + return derive_todo_category(user_mode=user_mode, position=position) + + +def _todo_category_from_process_gate( + process_gate: dict[str, Any] | None, + review_status: Any, +) -> str | None: + """ + 从用户 Gate 摘要推导 todo_category;无 current_gate_code 时返回 None 供回退。 + + 核心逻辑:优先 current_blocking_gate.status,否则摘要 status / current_gate。 + """ + if not isinstance(process_gate, dict) or not process_gate.get('current_gate_code'): + return None + gate_view = process_gate.get('current_blocking_gate') or process_gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = ( + gate_view.get('status') + or process_gate.get('status') + or process_gate.get('gate_status') + ) + return _todo_category_from_gate( + { + 'current_gate_code': process_gate.get('current_gate_code') or gate_view.get('gate_code'), + 'status': status, + }, + review_status, + lifecycle_stage=process_gate.get('lifecycle_stage'), + ) + + +def task_todo_category(task: ShippingNotice) -> str: + """ + 推导待办分类(服务端唯一口径):优先 Gate,无 Execution 回退 position/user_mode。 + + 核心逻辑:wait_manual_upload→manual_upload;complete→done; + must_human 且属复核入口→review,其余 must_human→exception; + auto_continue→in_progress。 + SQL CASE 仍为粗筛近似。 + + Returns: + review | exception | manual_upload | in_progress | done + """ + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gated = _todo_category_from_process_gate( + _process_gate_user_summary_for_task(task), + getattr(task, 'review_status', None), + ) + if gated is not None: + return gated ui = resolve_task_ui_state(task) - return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) + return _todo_category_from_ui(ui.position, ui.user_mode) -def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str: - """将 checkpoint_kind(及复核入口集合)映射为 todo_category。""" - if kind == CheckpointKind.WAIT_MANUAL_UPLOAD: +def _todo_category_from_ui(position: str | None, kind: UserMode) -> str: + """将 user_mode(及复核入口位置集合)映射为 todo_category(无 Gate 时回退)。""" + if kind == UserMode.WAIT_MANUAL_UPLOAD: return "manual_upload" - if kind == CheckpointKind.COMPLETE: + if kind == UserMode.COMPLETE: return "done" - if kind == CheckpointKind.MUST_HUMAN: - if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS: + if kind == UserMode.MUST_HUMAN: + if str(position or "") in _REVIEW_TODO_POSITIONS: return "review" return "exception" return "in_progress" @@ -676,32 +1151,33 @@ def _todo_category_from_task_row( row: Any, *, extractions_with_lines: set[int], + gate_pos: dict[str, Any] | None = None, ) -> str: """ 用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。 - 核心逻辑:委托 resolve_task_ui_state_from_fields;has_dynamic_order_lines 查批量集合。 + 核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退。 """ - extraction_id = getattr(row, "current_order_extraction_id", None) - has_lines = ( - extraction_id is not None - and int(extraction_id) in extractions_with_lines + del extractions_with_lines # 领域行事实不再参与位置裁决 + if gate_pos is not None and gate_pos.get('current_gate_code'): + return _todo_category_from_gate( + gate_pos, + getattr(row, 'review_status', None), + ) + from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, ) - upload_status = str(getattr(row, "upload_status", None) or "").strip().lower() - if upload_status in {"uploaded", "succeeded", "success"}: - return "done" - ui = resolve_task_ui_state_from_fields( - review_status=getattr(row, "review_status", None), - pending_human_reason=getattr(row, "pending_human_reason", None), - customer_resolution_status=getattr(row, "customer_resolution_status", None), - order_snapshot_id=getattr(row, "order_snapshot_id", None), - inventory_lines_json=getattr(row, "inventory_lines_json", None), - match_status=getattr(row, "match_status", None), - export_file_path=getattr(row, "export_file_path", None), - has_dynamic_order_lines=has_lines, - upload_req_options=[], + review_status = getattr(row, 'review_status', None) + position = derive_position(gate_code=None, review_status=review_status) + user_mode = derive_user_mode( + user_status=None, + gate_code=None, + review_status=review_status, + lifecycle_stage=None, ) - return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) + return derive_todo_category(user_mode=user_mode, position=position) def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]: @@ -755,7 +1231,7 @@ def _latest_task_event_summary(task: ShippingNotice) -> dict[str, Any] | None: 核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。 """ - if task.id is None: + if isinstance(task, ShippingOrderTask) or task.id is None: return None event = ( ShippingTaskEvent.query.filter_by(task_id=task.id) @@ -776,10 +1252,11 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: """ 投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。 - 核心逻辑:优先读任务上的 export_file_*;有路径或文件名即视为有摘要。 + 核心逻辑:只读取 ShippingExportArtifact;Notice 不保存导出文件投影。 """ - file_name = str(task.export_file_name or "").strip() or None - file_path = str(task.export_file_path or "").strip() or None + artifact = latest_export_artifact(task) + file_name = str(getattr(artifact, 'file_name', '') or "").strip() or None + file_path = str(getattr(artifact, 'file_path', '') or "").strip() or None if not file_name and not file_path: return None return { @@ -792,47 +1269,62 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: """ 投影发货通知列表需要的项次、料号、数量与当前库存事实。 - 核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次(line_no)经 - order_line_no_resolver 统一解析(字段真实值 → 客户 PO 行号 → 展示序号), - 并附 line_no_source 标注,禁止前端按 position 或序号自行推导业务项次。 + 核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次直接读取 + ShippingNoticeLine.line_no。该值在通知创建时按本通知从 1 开始编号, + 不允许由订单字段、客户 PO 行号或展示序号派生。 当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确 返回 null,禁止由前端估算库存。 """ if task.id is None: return [] - matches_by_line_key = { - str(item.line_key): item + if isinstance(task, ShippingOrderTask): + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None + return [{ + 'line_no': int(line.line_no), + 'part_number': line.part_number, + 'customer_part_number': (line.field_values_json or {}).get('customer_part_number'), + 'reservation_id': line.reservation_id, + 'shipment_qty': str(line.qty) if line.qty is not None else None, + 'available_qty': None, + 'shortage_qty': None, + 'inventory_status': None, + } for line in (getattr(snapshot, 'lines', None) or [])] + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) if getattr(task, 'order_task_id', None) else None + snapshot = db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id)) if owner and owner.order_snapshot_id else None + if snapshot is not None: + matches_by_snapshot_line_id = { + int(item.snapshot_line_id): item + for item in ShippingNoticeLineInventoryMatch.query.filter( + ShippingNoticeLineInventoryMatch.task_id == int(owner.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ).all() + if item.snapshot_line_id is not None + } + # Snapshot 仅提供订单冻结事实;正式通知的项次、料号、发运数量和预约号 + # 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。 + matches_by_snapshot_line_id = { + int(item.snapshot_line_id): item for item in ShippingNoticeLineInventoryMatch.query.filter( ShippingNoticeLineInventoryMatch.task_id == int(task.id), ShippingNoticeLineInventoryMatch.is_current.is_(True), ).all() - if item.line_key + if item.snapshot_line_id is not None } rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), ).all() - from app.services.shipping_notice.order_line_no_resolver import ( - notice_line_field_id_map, - resolve_order_line_no_projection, - ) - - field_id_by_code = notice_line_field_id_map(task) return [{ - **resolve_order_line_no_projection( - field_values=item.field_values_json, - field_id_by_code=field_id_by_code, - fallback_sequence=(int(item.position) + 1) if item.position is not None else None, - ), + 'line_no': int(item.line_no), 'part_number': item.part_number, 'customer_part_number': (item.field_values_json or {}).get('customer_part_number'), 'reservation_id': item.reservation_id, 'shipment_qty': str(item.required_qty) if item.required_qty is not None else None, - 'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty - if matches_by_line_key.get(str(item.line_key or '')) is not None else None, - 'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty - if matches_by_line_key.get(str(item.line_key or '')) is not None else None, - 'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status - if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + 'available_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).available_qty + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, + 'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, + 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, } for item in rows] @@ -840,14 +1332,17 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] """ 将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。 - 核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用领域事实 - 映射为 shipping_processing_status(与 shipping_processing_projection 同源), + 核心逻辑:实体本身若是 ShippingOrderTask,直接以自身为 OT(禁止再经 + order_task_id 反查——OT 无该字段,否则会把 SUMMARY 已写入的 order_task_no + 冲成 null,导致工作台右卡 work-item 投影永不启动);Notice 则经 + order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为 + shipping_processing_status(与 shipping_processing_projection 同源), 并注入 shipping_processing_stage / progress_version / order_task_no; 另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run), 供任务中心「进入订单处理」深链。 Args: - task: ShippingNotice(正式发货任务)。 + task: ShippingNotice 或 ShippingOrderTask。 data: 就地写入的序列化字典。 """ from app.models import ShippingOrderProcessingRun, ShippingOrderTask @@ -855,20 +1350,17 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] _notice_domain_progress_stage, ) - order_task = None - order_task_id = getattr(task, 'order_task_id', None) - if order_task_id is not None: - order_task = db.session.get(ShippingOrderTask, int(order_task_id)) - if order_task is None: - # 回退:OT.shipping_notice_id → Notice(双向挂接未齐时)。 - order_task = ( - db.session.query(ShippingOrderTask) - .filter(ShippingOrderTask.shipping_notice_id == int(task.id)) - .order_by(ShippingOrderTask.id.asc()) - .first() - ) - - status, stage = _notice_domain_progress_stage(task) + # [STEP 1] 解析权威 OT:OT 实体即自身;Notice 经 order_task_id 反查。 + order_task: ShippingOrderTask | None = None + if isinstance(task, ShippingOrderTask): + order_task = task + status = str(getattr(task, 'status', '') or '').strip() or 'processing' + stage = str(getattr(task, 'stage', '') or '').strip() or None + else: + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is not None: + order_task = db.session.get(ShippingOrderTask, int(order_task_id)) + status, stage = _notice_domain_progress_stage(task) data['shipping_processing_status'] = status data['shipping_processing_stage'] = ( str(getattr(order_task, 'stage', None) or '').strip() or stage @@ -878,6 +1370,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] or getattr(task, 'progress_version', None) or 1 ) + # [STEP 2] order_task_no 必须恒为 OT 编号;OT 自序列化时不得落成 null。 data['order_task_no'] = ( str(getattr(order_task, 'task_no', None) or '').strip() or None ) @@ -936,13 +1429,19 @@ def _enrich_task_center_fields( ui_state = build_task_ui_state(task, include_stage_context=include_stage_context) data["ui_state"] = ui_state - # [PERF] todo_category 与 ui_state 同源(均由 resolve_task_ui_state 推导):直接在 - # 已构建的 ui_state 上推导,避免 task_todo_category 在请求内对同一任务再算一次 - # resolve_task_ui_state(每次含 has_dynamic_order_lines 的取数),削减重复查询。 - data["todo_category"] = _todo_category_from_ui( - ui_state.get("checkpoint_code"), - CheckpointKind(str(ui_state.get("checkpoint_kind"))), + # [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution); + # 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。 + gated = _todo_category_from_process_gate( + ui_state.get("process_gate") if isinstance(ui_state, dict) else None, + ui_state.get("review_status") if isinstance(ui_state, dict) else getattr(task, 'review_status', None), ) + if gated is not None: + data["todo_category"] = gated + else: + data["todo_category"] = _todo_category_from_ui( + ui_state.get("position") if isinstance(ui_state, dict) else None, + UserMode(str((ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE)), + ) _inject_unified_processing_fields(task, data) # [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。 data['workflow_item'] = None @@ -969,6 +1468,46 @@ def serialize_task_summary( ) +def _serialize_task_workbench_shell(task: ShippingNotice) -> dict[str, Any]: + """ + 订单生命周期工作台身份壳:不跑 SUMMARY/DETAIL 重投影。 + + 核心逻辑:工作台只消费 task_no / business_no / export_artifacts 等身份字段, + 以及 enrich 写入的 ui_state(含 stage_context)与行摘要;禁止先算 DETAIL 再 pop。 + + Args: + task: ShippingNotice 或 ShippingOrderTask。 + + Returns: + 供 ``_enrich_task_center_fields`` 就地补全的最小字典。 + """ + created_at = getattr(task, 'created_at', None) + updated_at = getattr(task, 'updated_at', None) + stage = getattr(task, 'stage', None) or getattr(task, 'current_step', None) + data: dict[str, Any] = { + 'id': getattr(task, 'id', None), + 'task_no': task.task_no, + 'source_type': getattr(task, 'source_type', None), + 'status': getattr(task, 'status', None), + 'stage': stage, + 'current_step': getattr(task, 'current_step', None) or stage, + 'progress_version': getattr(task, 'progress_version', None), + 'conversation_id': getattr(task, 'conversation_id', None), + 'created_at': created_at.isoformat() if created_at else None, + 'updated_at': updated_at.isoformat() if updated_at else None, + } + if isinstance(task, ShippingOrderTask): + data['order_task_no'] = task.task_no + data['order_snapshot_id'] = getattr(task, 'order_snapshot_id', None) + data['order_data_version'] = int(getattr(task, 'order_data_version', 1) or 1) + data['business_no'] = None + return data + data['business_no'] = getattr(task, 'business_no', None) + # Notice 人工上传弹窗仍读 export_artifacts;比整份 DETAIL 轻一个数量级。 + data.update(_fulfillment_timeline(task)) + return data + + def serialize_task_detail( task: ShippingNotice, *, @@ -986,20 +1525,14 @@ def serialize_task_detail( is_admin: 是否管理员视图。 include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。 view: 投影视图。``full`` 返回完整详情(含复核编辑器数据);``workbench`` 为 - 订单生命周期工作台首屏裁剪版:工作台只消费 ui_state + 进度/产物/行摘要, - 不读取行明细/订单头/事件/字段冲突等复核编辑器重字段。把这些字段从响应剔除, - 避免每次进入工作台都拉取 67KB 级详情(对应 /shipping-tasks/:task_no 的大响应)。 + 订单生命周期工作台首屏投影:只建身份壳再 enrich(ui_state / 行摘要 / 产物), + **不**进入 SUMMARY/DETAIL 重投影,避免先算 lines/header/match 再剔除。 """ - data = serialize_task(task, TaskProjection.DETAIL) + # [PERF] workbench:算之前就轻;禁止 DETAIL 后再 pop。 if view == 'workbench': - # [PERF] 工作台首屏不消费以下复核编辑器字段,剔除后显著缩小响应体与序列化耗时。 - # 仅剔除编辑重字段;ui_state(含 stage_context)、notice_line_summary、 - # artifact_summary、_fulfillment_timeline(export_artifacts) 与进度字段原样保留。 - for key in ( - 'lines', 'order_header', 'order_header_fields', 'order_line_fields', - 'events', 'field_conflicts', - ): - data.pop(key, None) + data = _serialize_task_workbench_shell(task) + else: + data = serialize_task(task, TaskProjection.DETAIL) return _enrich_task_center_fields( task, data, viewer_user_id=viewer_user_id, is_admin=is_admin, include_stage_context=include_stage_context, @@ -1012,10 +1545,33 @@ def list_tasks_for_user( limit: int = 100, ) -> list[dict[str, Any]]: """列出用户可见任务摘要。""" - q = ShippingNotice.query.filter( - (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) - ) - rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all() + safe_limit = max(1, min(limit, 500)) + notice_refs = ShippingNotice.query.filter( + (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)), + ShippingNotice.deleted_at.is_(None), + ).with_entities( + literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'), + ShippingNotice.created_at.label('sort_at'), ShippingNotice.task_no.label('sort_ref'), + ).statement + ot_refs = ShippingOrderTask.query.filter( + ShippingOrderTask.user_id == int(user_id), + ShippingOrderTask.deleted_at.is_(None), + ).with_entities( + literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'), + ShippingOrderTask.created_at.label('sort_at'), ShippingOrderTask.task_no.label('sort_ref'), + ).statement + combined = union_all(notice_refs, ot_refs).subquery('task_refs') + refs = db.session.execute( + select(combined.c.kind, combined.c.entity_id) + .order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id)) + .limit(safe_limit) + ).all() + notice_ids = [int(entity_id) for kind, entity_id in refs if kind == 'shipping_notice'] + ot_ids = [int(entity_id) for kind, entity_id in refs if kind == 'order_task'] + notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {} + ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {} + rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in refs] + rows = [row for row in rows if row is not None] return [ serialize_task_summary(c, viewer_user_id=user_id) for c in rows @@ -1037,36 +1593,60 @@ def list_tasks_page_for_user( """ normalized_page = max(1, int(page)) normalized_page_size = max(1, min(int(page_size), 100)) - q = ShippingNotice.query.filter( + notice_q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if lifecycle_status: - normalized_lifecycle = str(lifecycle_status).strip().lower() - if normalized_lifecycle == 'deleted': - q = q.filter(ShippingNotice.deleted_at.is_not(None)) - elif normalized_lifecycle == 'active': - q = q.filter( - ShippingNotice.deleted_at.is_(None), - ShippingNotice.lifecycle_status == 'active', - db.or_( - ShippingNotice.upload_status.is_(None), - db.func.lower(ShippingNotice.upload_status).notin_(('uploaded', 'succeeded', 'success')), - ), - ) - elif normalized_lifecycle == 'voided': - # 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。 - q = q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle) - else: - q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == normalized_lifecycle) + ot_q = ShippingOrderTask.query.filter(ShippingOrderTask.user_id == int(user_id)) + normalized_lifecycle = str(lifecycle_status or 'active').strip().lower() + if normalized_lifecycle == 'deleted': + notice_q = notice_q.filter(ShippingNotice.deleted_at.is_not(None)) + ot_q = ot_q.filter(ShippingOrderTask.deleted_at.is_not(None)) + elif normalized_lifecycle == 'active': + notice_upload_success = exists(select(1).select_from(ShippingUploadAttempt).join( + ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, + ).where( + ShippingExportArtifact.task_id == ShippingNotice.id, + ShippingUploadAttempt.status == 'succeeded', + )) + notice_q = notice_q.filter( + ShippingNotice.deleted_at.is_(None), + ShippingNotice.lifecycle_status == 'active', + ~notice_upload_success, + ) + ot_q = ot_q.filter( + ShippingOrderTask.deleted_at.is_(None), + ShippingOrderTask.lifecycle_status == 'active', + ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}), + ) else: - q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == 'active') - total = q.order_by(None).count() - rows = ( - q.order_by(desc(ShippingNotice.created_at)) - .offset((normalized_page - 1) * normalized_page_size) - .limit(normalized_page_size) - .all() - ) + notice_q = notice_q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle) + ot_q = ot_q.filter(ShippingOrderTask.lifecycle_status == normalized_lifecycle) + + union_stmt = union_all( + notice_q.with_entities( + literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'), + func.coalesce(ShippingNotice.created_at, ShippingNotice.updated_at).label('sort_at'), + ShippingNotice.task_no.label('sort_ref'), + ).statement, + ot_q.with_entities( + literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'), + func.coalesce(ShippingOrderTask.created_at, ShippingOrderTask.updated_at).label('sort_at'), + ShippingOrderTask.task_no.label('sort_ref'), + ).statement, + ).subquery('task_union') + total = int(db.session.execute(select(func.count()).select_from(union_stmt)).scalar_one() or 0) + offset = (normalized_page - 1) * normalized_page_size + page_refs = db.session.execute( + select(union_stmt.c.kind, union_stmt.c.entity_id) + .order_by(desc(union_stmt.c.sort_at), desc(union_stmt.c.sort_ref), desc(union_stmt.c.entity_id)) + .offset(offset).limit(normalized_page_size) + ).all() if offset < total else [] + notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'shipping_notice'] + ot_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'order_task'] + notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {} + ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {} + rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in page_refs] + rows = [row for row in rows if row is not None] return { "items": [ serialize_task_summary(item, viewer_user_id=user_id) @@ -1078,7 +1658,7 @@ def list_tasks_page_for_user( } -def get_task_for_user(task_no: str, user_id: int) -> ShippingNotice | None: +def get_task_for_user(task_no: str, user_id: int) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_no 查找任务并校验写路径归属(严格创建者)。 @@ -1098,7 +1678,7 @@ def get_task_visible_to_user( user_id: int, *, is_admin: bool = False, -) -> ShippingNotice | None: +) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_no 查找当前用户可见的任务(创建者或管理员只读)。 @@ -1170,17 +1750,31 @@ def list_freight_notice_groups_for_task( # [STEP] upload_mode/upload_attempt 从 ShippingUploadAttempt 权威事实解析。 # denormalized Notice.upload_mode 恒为 None,不能作为「人工/RPA」展示来源。 upload_mode, upload_attempt = _task_upload_attempt_facts(notice.id) + latest_attempt = ( + ShippingUploadAttempt.query + .join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id) + .filter(ShippingExportArtifact.task_id == int(notice.id)) + .order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()) + .first() + ) + artifact = ( + ShippingExportArtifact.query + .filter(ShippingExportArtifact.task_id == int(notice.id)) + .order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()) + .first() + ) + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status items.append({ 'business_no': business_no, 'po_number': po_number, - 'upload_status': notice.upload_status, + # Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。 + 'upload_status': project_notice_upload_status(notice), 'upload_mode': upload_mode, 'upload_attempt': upload_attempt, - 'upload_error_code': notice.upload_error_code, + 'upload_error_code': getattr(latest_attempt, 'error_code', None), # 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。 - 'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None, - 'pending_human_reason': notice.pending_human_reason, - 'export_file_name': notice.export_file_name, + 'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None, + 'export_file_name': getattr(artifact, 'file_name', None), 'available_actions': available_actions, 'lines': _notice_line_summary_for_task(notice), }) @@ -1231,9 +1825,11 @@ def _notice_po_number(notice: ShippingNotice) -> str: if normalized: return normalized + owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None snapshot = None - if notice.order_snapshot_id: - snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id) + snapshot_id = getattr(owner, 'order_snapshot_id', None) + if snapshot_id: + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot: for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')): normalized = normalize_po_number(value) @@ -1249,18 +1845,25 @@ def _notice_po_number(notice: ShippingNotice) -> str: def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: - """待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。""" + """待办列表客户关键字过滤:匹配确认客户快照、来源文档或当前订单头证据。""" needle = str(customer or "").strip().lower() if not needle: return True candidates: list[str] = [] - for value in (task.customer_name_snapshot, task.customer_short_code_snapshot): - if value: - candidates.append(str(value)) - if task.source_file_name: - candidates.append(str(task.source_file_name)) + owner = task if isinstance(task, ShippingOrderTask) else ( + db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else None + ) + if owner is not None: + customer = _order_task_customer_projection(owner) + for value in (customer['customer_name_snapshot'], customer['customer_short_code_snapshot']): + if value: + candidates.append(str(value)) + docs = db.session.query(ShippingOrderDocument.filename).join( + ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id, + ).filter(ShippingOrderCandidate.id == owner.candidate_id).all() if owner.candidate_id else [] + candidates.extend(str(row[0]) for row in docs if row[0]) header = current_header_field_values_or_empty(task) - for key in ("customer_name", "bill_to_customer", "ship_to_customer", "customer_code"): + for key in ("customer_name", "ship_to_customer", "customer_code"): value = header.get(key) if value: candidates.append(str(value)) @@ -1268,7 +1871,7 @@ def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): - """构造「我的待办」可见任务基础查询(活跃生命周期)。""" + """构造正式 ShippingNotice 的待办查询;OT 由 `_visible_order_tasks_query_for_todos` 提供。""" q = ShippingNotice.query.filter( ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == "active", @@ -1279,6 +1882,173 @@ def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): return q +def _visible_order_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): + """构造库存准备前 OT 待办查询;OT 是正式 Notice 创建前唯一可见根实体。""" + query = ShippingOrderTask.query.filter( + ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}), + ~exists( + select(1).select_from(ShippingNotice).where( + ShippingNotice.order_task_id == ShippingOrderTask.id, + ) + ), + ) + if not is_admin: + query = query.filter(ShippingOrderTask.user_id == int(user_id)) + return query + + +def _latest_process_execution_field_sql(task_id_column, field_name: str): + """ + 最新非 superseded Execution 的指定列(scalar subquery),供待办 SQL Gate-first。 + + Args: + task_id_column: OT 主键列表达式(Notice.order_task_id 或 OrderTask.id)。 + field_name: ``current_gate_code`` 或 ``status``。 + """ + column = getattr(ShippingProcessExecution, field_name) + return ( + select(column) + .where( + ShippingProcessExecution.task_id == task_id_column, + ShippingProcessExecution.status != 'superseded', + ) + .order_by(ShippingProcessExecution.id.desc()) + .limit(1) + .scalar_subquery() + ) + + +def _gate_todo_category_sql_whens(task_id_column): + """ + Gate 优先的 todo_category CASE when 列表(对齐 derive_todo_category)。 + + 核心逻辑:复核 gate→review;人工上传 handoff→manual_upload; + 短缺/失败类 gate→exception;准备/匹配运行中→in_progress。 + """ + gate_code = _latest_process_execution_field_sql(task_id_column, 'current_gate_code') + gate_exec_status = _latest_process_execution_field_sql(task_id_column, 'status') + return [ + ( + gate_code.in_(('order_field_extraction', 'customer_resolution', 'reservation_validation')), + literal('review'), + ), + ( + gate_code.in_(('manual_upload_handoff',)), + literal('manual_upload'), + ), + ( + db.and_( + gate_code.in_(('artifact_generation',)), + gate_exec_status.in_(('blocked', 'completed')), + ), + literal('manual_upload'), + ), + ( + db.and_( + gate_code.in_( + ( + 'inventory_sufficiency', + 'freight_upload_rpa', + 'inventory_source_routing', + 'excel_readiness', + ) + ), + gate_exec_status.in_(('blocked', 'failed')), + ), + literal('exception'), + ), + ( + gate_code.in_( + ( + 'inventory_preparation', + 'inventory_matching', + 'inventory_field_mapping', + 'order_freeze_readiness', + 'artifact_generation', + ) + ), + literal('in_progress'), + ), + ] + + +def _order_task_todo_category_sql_expr(): + """按 Gate 优先、再领域事实投影 OT 待办,禁止读取库存 JSON 投影。""" + stage = db.func.lower(db.func.coalesce(ShippingOrderTask.stage, "")) + reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, "")) + ready_file = exists( + select(1) + .select_from(ShippingTaskInventoryLink) + .join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id) + .where( + ShippingTaskInventoryLink.task_id == ShippingOrderTask.id, + ShippingTaskInventoryLink.is_active.is_(True), + ShippingTaskInventoryLink.invalidated_at.is_(None), + ShippingInventoryFile.snapshot_status == 'ready', + ShippingInventoryFile.invalidated_at.is_(None), + ShippingInventoryFile.line_count > 0, + ) + ) + incomplete_match = exists( + select(1) + .select_from(ShippingOrderSnapshotLine) + .where( + ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id, + ~exists( + select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result != 'preparing', + ) + ), + ) + ) + has_shortage = exists( + select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + db.or_( + ShippingNoticeLineInventoryMatch.match_result != 'matched', + db.and_( + ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None), + ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), + ), + ), + ) + ) + manual_gate = exists( + select(1) + .select_from(ShippingProcessExecution) + .join(ShippingProcessGate, ShippingProcessGate.execution_id == ShippingProcessExecution.id) + .where( + ShippingProcessExecution.task_id == ShippingOrderTask.id, + ShippingProcessExecution.status.notin_(('completed', 'cancelled', 'superseded')), + ShippingProcessGate.status.in_(('blocked_manual', 'failed_terminal')), + ) + ) + return case( + *_gate_todo_category_sql_whens(ShippingOrderTask.id), + ( + db.or_( + reason.in_((PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_INVENTORY_SOURCE_UNRESOLVED, PH_SHORTAGE)), + manual_gate, + db.and_(ShippingOrderTask.order_snapshot_id.isnot(None), ~incomplete_match, has_shortage), + ), + literal("exception"), + ), + ( + db.and_( + ShippingOrderTask.order_snapshot_id.isnot(None), + ready_file, + incomplete_match, + ), + literal("in_progress"), + ), + (stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")), + else_=literal("in_progress"), + ) + def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False): """ 构造建单前开放 Review Case 查询(尚未确认建单)。 @@ -1397,19 +2167,18 @@ def serialize_review_case_todo( "lifecycle_stage": lifecycle_stage, "lifecycle_entries": lifecycle_entries, "intake_parse_authorized": lifecycle_stage == "intake_parse", - "checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']}, + "position": lifecycle_stage, + "user_mode": str(UserMode.MUST_HUMAN), "todo": {"title": current_todo, "message": current_todo}, "actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []}, "reason": {"code": f"review_case_{case.status}", "message": current_todo}, "lifecycle_status": "active", "process_gate": None, - "checkpoint_code": lifecycle_stage, - "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "summary": { "title": "待人工复核", "message": current_todo, "stage": "待人工复核", - "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), + "user_mode": str(UserMode.MUST_HUMAN), "current_todo": current_todo, "pause_reason": current_todo, "pause_reason_code": ( @@ -1563,24 +2332,21 @@ def serialize_intake_todo( # Intake 尚未有当前有效订单 Candidate;只能进入对话查看解析,不能进入生命周期工作台。 "lifecycle_stage": "intake_parse", "lifecycle_entries": [], - "checkpoint": {"code": "order_field_extraction", "kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE - ), "label": "订单解析"}, + "position": "order_field_extraction", + "user_mode": str( + UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE + ), "todo": {"title": title, "message": message}, "actions": {"primary": ({"code": "retry_parse", "label": "重新解析", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if failed else None), "secondary": []}, "reason": ({"code": str(intake.error_code or "intake_parse_failed"), "message": message} if failed else None), "lifecycle_status": "active", "process_gate": None, - "checkpoint_code": "order_field_extraction", - "checkpoint_kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE - ), "summary": { "title": title, "message": message, "stage": title, - "checkpoint_kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE + "user_mode": str( + UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE ), "current_todo": title, "pause_reason": message if failed else None, @@ -1609,17 +2375,30 @@ def _todo_category_sql_filter(allowed: frozenset[str]): 核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。 """ + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed', + ) + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown')))) clauses = [] if "manual_upload" in allowed: # wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。 clauses.append( db.or_( - ShippingNotice.upload_status.in_(("pending", "uploading", "failed")), + upload_pending, db.and_( - ShippingNotice.export_file_path.isnot(None), + artifact_exists, db.or_( - ShippingNotice.upload_status.is_(None), - db.func.lower(ShippingNotice.upload_status).notin_(("uploaded", "succeeded", "success")), + ~upload_success, ), ShippingNotice.lifecycle_status == "active", ), @@ -1629,27 +2408,31 @@ def _todo_category_sql_filter(allowed: frozenset[str]): # 已上传/关闭/驳回终态(不含待人工上传登记)。 clauses.append( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), ) ) if "review" in allowed: clauses.append( db.or_( - ShippingNotice.review_status.isnot(None), - ShippingNotice.pending_human_reason.isnot(None), + workflow_review_status.isnot(None), + workflow_pending_reason.isnot(None), ) ) if "exception" in allowed: - clauses.append(ShippingNotice.pending_human_reason.isnot(None)) + clauses.append(workflow_pending_reason.isnot(None)) if "in_progress" in allowed: clauses.append( db.or_( - ShippingNotice.current_step.isnot(None), - ShippingNotice.inventory_snapshot_id.isnot(None), - ShippingNotice.export_file_path.isnot(None), - ShippingNotice.upload_status.isnot(None), + workflow_current_step.isnot(None), + exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + )), + artifact_exists, + upload_pending, ) ) if not clauses: @@ -1667,7 +2450,9 @@ def _task_has_dynamic_order_lines_sql(): select(1) .select_from(ShippingOrderExtraction) .where( - ShippingOrderExtraction.id == ShippingNotice.current_order_extraction_id, + ShippingOrderExtraction.id == select(ShippingOrderTask.current_order_extraction_id).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery(), ShippingOrderExtraction.status == "accepted", exists( select(1) @@ -1696,81 +2481,108 @@ def _sql_str_blank(column): def _task_todo_category_sql_expr(): """ - 将 resolve_task_ui_state_from_fields 同序映射为 todo_category SQL CASE。 + 待办 todo_category 的 SQL CASE:Gate 优先,再 review_status / 领域标量回退。 - 核心逻辑:分支顺序与状态机一致;直接产出 review|exception|manual_upload|in_progress|done, - 供 UNION 分页与徽标 COUNT 在数据库内过滤,避免轻量全量索引。 + 核心逻辑:不再与 resolve_task_ui_state「同序」;与 ORM + ``task_todo_category`` / ``derive_todo_category`` 对齐,供 UNION 分页与徽标 COUNT。 """ has_lines = _task_has_dynamic_order_lines_sql() - reason = ShippingNotice.pending_human_reason - upload_status = db.func.lower(db.func.coalesce(ShippingNotice.upload_status, "")) - match_status = db.func.lower(db.func.coalesce(ShippingNotice.match_status, "")) + reason = select(ShippingOrderTask.pending_human_reason).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + review_status = select(ShippingOrderTask.review_status).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + snapshot_id = select(ShippingOrderTask.order_snapshot_id).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed', + ) + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded")))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown")))) + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + )) return case( - (upload_status.in_(("uploaded", "succeeded", "success")), literal("done")), + (upload_success, literal("done")), (ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")), ( db.or_( - ShippingNotice.review_status == RS_REJECTED, + review_status == RS_REJECTED, ), literal("done"), ), + # [STEP] Gate-first(经 order_task_id 关联最新 Execution) + *_gate_todo_category_sql_whens(ShippingNotice.order_task_id), ( - db.or_(reason == PH_RSV_REQ, ShippingNotice.review_status == RS_RSV_REQ), + db.or_(reason == PH_RSV_REQ, review_status == RS_RSV_REQ), literal("review"), ), ( - db.or_(reason == PH_LOW_CONF, ShippingNotice.review_status == RS_PARSE_REVIEW), + db.or_(reason == PH_LOW_CONF, review_status == RS_PARSE_REVIEW), literal("review"), ), (reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")), ( db.and_( - ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")), + customer_pending, ), literal("exception"), ), ( - db.and_(ShippingNotice.order_snapshot_id.is_(None), has_lines), + db.and_(snapshot_id.is_(None), has_lines), literal("in_progress"), ), (reason == PH_RPA_EXHAUSTED, literal("exception")), # Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。 - (ShippingNotice.export_file_path.isnot(None), literal("manual_upload")), + (artifact_exists, literal("manual_upload")), ( db.and_( - _sql_str_blank(ShippingNotice.review_status), + _sql_str_blank(review_status), _sql_str_blank(reason), - _sql_json_falsy(ShippingNotice.inventory_lines_json), + ~exists().where( + ShippingTaskInventoryLink.task_id == ShippingNotice.order_task_id, + ShippingTaskInventoryLink.is_active.is_(True), + ShippingTaskInventoryLink.invalidated_at.is_(None), + ), ), literal("in_progress"), ), ( db.and_( - _sql_str_blank(ShippingNotice.review_status), + _sql_str_blank(review_status), _sql_str_blank(reason), - _sql_str_blank(ShippingNotice.match_status), + ~match_exists, has_lines, ), literal("in_progress"), ), ( db.and_( - match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), literal("manual_upload"), ), - (match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), literal("in_progress")), + (match_exists, literal("in_progress")), (reason == PH_INV_UNAVAIL, literal("exception")), (reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")), ( - db.or_(reason == PH_SHORTAGE, ShippingNotice.review_status == RS_SHORTAGE_REVIEW), + db.or_(reason == PH_SHORTAGE, review_status == RS_SHORTAGE_REVIEW), literal("exception"), ), ( db.or_( reason == PH_UPLOAD_RPA_FAILED, - upload_status == "failed", + exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status == "failed")), ), literal("exception"), ), @@ -1778,11 +2590,10 @@ def _task_todo_category_sql_expr(): (reason == PH_RPA_PENDING, literal("exception")), (reason == PH_UPLOAD_RPA_PENDING, literal("exception")), # Excel 后待人工上传登记。 - (upload_status.in_(("pending", "uploading")), literal("manual_upload")), + (upload_pending, literal("manual_upload")), else_=literal("in_progress"), ) - def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]: """待办排序键:updated_at 降序 + 稳定引用(测试/调试辅助)。""" if hasattr(value, "isoformat"): @@ -1811,6 +2622,30 @@ def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, custome ) +def _verified_upload_success_sql_expr(): + """以当前 Excel Artifact 已上传这一唯一事实判定 Notice 已完成。""" + artifact = aliased(ShippingExportArtifact) + current_artifact_id = ( + select(artifact.id) + .where( + artifact.task_id == ShippingNotice.id, + artifact.status.in_(("ready", "uploading", "uploaded")), + ) + .order_by(artifact.created_at.desc(), artifact.id.desc()) + .limit(1) + .correlate(ShippingNotice) + .scalar_subquery() + ) + return exists( + select(1) + .select_from(ShippingExportArtifact) + .where( + ShippingExportArtifact.id == current_artifact_id, + ShippingExportArtifact.status == "uploaded", + ) + ) + + def _todo_tasks_base_query( user_id: int, *, @@ -1827,40 +2662,75 @@ def _todo_tasks_base_query( 核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。 """ q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin) + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where(ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed') + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown')))) + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: q = q.filter( db.or_( - ShippingNotice.customer_name_snapshot.ilike(customer_like), - ShippingNotice.customer_short_code_snapshot.ilike(customer_like), - ShippingNotice.source_file_name.ilike(customer_like), + exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status == 'confirmed', + db.or_( + ShippingCustomer.standard_name.ilike(customer_like), + ShippingCustomer.short_code.ilike(customer_like), + ), + ) + ), + exists( + select(1).select_from(ShippingOrderDocument) + # Candidate 使用 primary_document_id 关联来源文档;不能读取已移除的 document_id 投影。 + .join(ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingOrderCandidate.id) + .where(ShippingOrderTask.id == ShippingNotice.order_task_id, ShippingOrderDocument.filename.ilike(customer_like)) + ), ) ) + category_clause = _todo_category_sql_filter(allowed) if category_clause is not None: q = q.filter(category_clause) if normalized_bucket in {"pending", "processing"}: q = q.filter( db.or_( - ShippingNotice.pending_human_reason.isnot(None), - ShippingNotice.review_status.isnot(None), - ShippingNotice.export_file_path.isnot(None), - ShippingNotice.current_step.isnot(None), - ShippingNotice.inventory_snapshot_id.isnot(None), - ShippingNotice.upload_status.isnot(None), + workflow_pending_reason.isnot(None), + workflow_review_status.isnot(None), + artifact_exists, + workflow_current_step.isnot(None), + exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + )), + upload_pending, ) ) elif normalized_bucket == "done": # Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。 q = q.filter( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), db.and_( - ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), ) ) @@ -1972,6 +2842,37 @@ def list_my_todos( ) ) + # 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败任务会从任务中心消失。 + ot_allowed = frozenset(cat for cat in task_allowed if cat in {"exception", "in_progress"}) + if ot_allowed: + ot_q = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) + if task_no: + ot_q = ot_q.filter(ShippingOrderTask.task_no == str(task_no).strip()) + if customer_needle: + ot_q = ot_q.filter( + exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id) + .where( + ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id, + ShippingCustomerShadowResolution.status == 'confirmed', + db.or_( + ShippingCustomer.standard_name.ilike(customer_like), + ShippingCustomer.short_code.ilike(customer_like), + ), + ) + ) + ) + ot_q = ot_q.filter(_order_task_todo_category_sql_expr().in_(tuple(sorted(ot_allowed)))) + branches.append( + ot_q.with_entities( + literal("order_task").label("kind"), + ShippingOrderTask.id.label("entity_id"), + func.coalesce(ShippingOrderTask.updated_at, ShippingOrderTask.created_at).label("sort_at"), + ShippingOrderTask.task_no.label("sort_ref"), + ) + ) + if not branches: return { "items": [], @@ -2004,7 +2905,8 @@ def list_my_todos( # [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。 page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"] page_intake_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_intake"] - page_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"] + page_notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"] + page_order_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_task"] cases_by_id: dict[int, ShippingOrderReviewCase] = {} if page_case_ids: for case in ShippingOrderReviewCase.query.filter( @@ -2017,10 +2919,14 @@ def list_my_todos( ShippingOrderIntake.id.in_(page_intake_ids), ).all(): intakes_by_id[int(intake.id)] = intake - tasks_by_id: dict[int, ShippingNotice] = {} - if page_task_ids: - for task in ShippingNotice.query.filter(ShippingNotice.id.in_(page_task_ids)).all(): - tasks_by_id[int(task.id)] = task + notices_by_id: dict[int, ShippingNotice] = {} + if page_notice_ids: + for notice in ShippingNotice.query.filter(ShippingNotice.id.in_(page_notice_ids)).all(): + notices_by_id[int(notice.id)] = notice + order_tasks_by_id: dict[int, ShippingOrderTask] = {} + if page_order_task_ids: + for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(page_order_task_ids)).all(): + order_tasks_by_id[int(task.id)] = task page_rows: list[dict[str, Any]] = [] for kind, entity_id in page_refs: @@ -2045,12 +2951,13 @@ def list_my_todos( ) ) continue - task = tasks_by_id.get(entity_id_int) - if task is None: - continue - page_rows.append( - serialize_task_summary(task, viewer_user_id=user_id, is_admin=is_admin) - ) + notice = notices_by_id.get(entity_id_int) + if kind == "order_task": + order_task = order_tasks_by_id.get(entity_id_int) + if order_task is not None: + page_rows.append(serialize_task_summary(order_task, viewer_user_id=user_id, is_admin=is_admin)) + elif notice is not None: + page_rows.append(serialize_task_summary(notice, viewer_user_id=user_id, is_admin=is_admin)) return { "items": page_rows, @@ -2069,23 +2976,31 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: Returns: {pending, processing, done, total_pending_badge} """ + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count() pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count() category_expr = _task_todo_category_sql_expr() active = _active_todo_tasks_scope(user_id, is_admin=is_admin) task_pending_cats = tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})) pending += active.filter(category_expr.in_(task_pending_cats)).count() + ot_active = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) + ot_category = _order_task_todo_category_sql_expr() + pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse", "manual_upload"})))).count() processing = active.filter(category_expr == "in_progress").count() + processing += ot_active.filter(ot_category == "in_progress").count() done = ( _visible_tasks_query_for_todos(user_id, is_admin=is_admin) .filter( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), db.and_( - ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), ) ) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 08953eab..22973069 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -92,10 +92,13 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool: if not task_is_active(task): return False - pending_reason = str(task.pending_human_reason or '').strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending_reason = str(task_blocking_reason(task) or '').strip() + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + return ( pending_reason == PH_RPA_PENDING - and not task.inventory_lines_json + and not has_ready_inventory_file_for_task(task) ) or pending_reason == PH_UPLOAD_RPA_PENDING @@ -107,7 +110,8 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: from app.services.shipping_notice.query_service import get_task_by_ref task = get_task_by_ref(task_no) - if task and str(task.pending_human_reason or '').strip() == PH_RPA_PENDING: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING: from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at scheduled_at = next_inventory_rpa_recheck_at(task) diff --git a/backend/app/services/shipping_notice/reconcile_queries.py b/backend/app/services/shipping_notice/reconcile_queries.py index 1c8b10c2..d541d961 100644 --- a/backend/app/services/shipping_notice/reconcile_queries.py +++ b/backend/app/services/shipping_notice/reconcile_queries.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/reconcile_queries.py 用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。 依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument - / ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、 + / ShippingOrderTask、business_fingerprint.build_business_fingerprint、 duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。 逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询, 不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no / @@ -19,8 +19,8 @@ from typing import Any from app import db from app.models import ( FileAsset, - ShippingNotice, ShippingOrderCandidate, + ShippingOrderTask, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderProcessingUnit, @@ -61,7 +61,7 @@ def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult: def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None: """ - L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。 + L1:Case.confirmed_task_id → 直接查 ShippingOrderTask 拿到 task_no。 【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。 """ steps: list[dict[str, Any]] = [] @@ -70,7 +70,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa # 1a. confirmed_task_id 有值且指向存在的 Task task_id = getattr(case, 'confirmed_task_id', None) if task_id is not None: - task = db.session.get(ShippingNotice, int(task_id)) + task = db.session.get(ShippingOrderTask, int(task_id)) if task is not None and task.task_no: steps.append({'step': 'L1a-confirmed_task_id', 'passed': True, 'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}}) @@ -83,15 +83,15 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa lifecycle=classify_task_lifecycle(task)), ) steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, - 'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no', + 'reason': 'confirmed_task_id 指向的 ShippingOrderTask 不存在或无 task_no', 'evidence': {'task_id': int(task_id)}}) else: steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'}) - # 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性 + # 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingOrderTask 校验存在性 confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip() if confirmed_task_no: - task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first() + task = ShippingOrderTask.query.filter_by(task_no=confirmed_task_no).first() if task is not None: steps.append({'step': 'L1b-confirmed_task_no', 'passed': True, 'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}}) @@ -104,7 +104,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa lifecycle=classify_task_lifecycle(task)), ) steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, - 'reason': 'confirmed_task_no 反向查无 ShippingNotice', + 'reason': 'confirmed_task_no 反向查无 ShippingOrderTask', 'evidence': {'task_no': confirmed_task_no}}) else: steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'}) @@ -141,7 +141,7 @@ def _step_l1cde_downstream_links( ) -> ReconcileMatchResult | None: """ L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。 - L1d: Document → ShippingNotice.source_document_id / document_id 外键。 + L1d: Document → Candidate.primary_document_id → ShippingOrderTask 外键。 L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。 """ steps: list[dict[str, Any]] = [] @@ -151,7 +151,7 @@ def _step_l1cde_downstream_links( if candidate is not None: fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None) if fulfilled_task_id is not None: - task = db.session.get(ShippingNotice, int(fulfilled_task_id)) + task = db.session.get(ShippingOrderTask, int(fulfilled_task_id)) if task is not None and task.task_no: steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True, 'evidence': {'candidate_id': int(candidate.id), @@ -183,7 +183,7 @@ def _step_l1cde_downstream_links( ) wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None] if len(wave_task_ids) == 1: - task = db.session.get(ShippingNotice, wave_task_ids[0]) + task = db.session.get(ShippingOrderTask, wave_task_ids[0]) if task is not None and task.task_no: steps.append({'step': 'L1c-wave_line_task', 'passed': True, 'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}}) @@ -204,14 +204,14 @@ def _step_l1cde_downstream_links( steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'}) steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'}) - # -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)-------- + # -------- L1d:Document 外键链:Unit → Intake → Candidate → OT -------- document_id = int(case.document_id) - # 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联) + # 路径 A:Candidate.primary_document_id == document_id(PDF 级直接关联) doc_task_a = ( - ShippingNotice.query - .filter((ShippingNotice.source_document_id == document_id) | - (ShippingNotice.document_id == document_id)) - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderCandidate.primary_document_id == document_id) + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -240,15 +240,19 @@ def _step_l1cde_downstream_links( intake = db.session.get(ShippingOrderIntake, int(unit.intake_id)) asset_id = getattr(intake, 'asset_id', None) if intake is not None else None if asset_id is not None: - # FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级) + # FileAsset.content_hash == Intake/Document.content_hash(文件哈希级) asset = db.session.get(FileAsset, int(asset_id)) content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower() if content_hash: file_tasks = ( - ShippingNotice.query - .filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderTask.intake_id) + .filter( + ShippingOrderTask.user_id == int(case.owner_user_id), + ShippingOrderIntake.asset_id == int(asset_id), + ) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -400,11 +404,12 @@ def _step_l2_structural_match( if (payload['business_fingerprint'] and payload['fingerprint_strength'] in {'strong', 'medium'}): same_fp_tasks = ( - ShippingNotice.query - .filter(ShippingNotice.user_id == int(case.owner_user_id), - ShippingNotice.business_fingerprint == payload['business_fingerprint']) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(case.owner_user_id), + ShippingOrderCandidate.business_fingerprint == payload['business_fingerprint']) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -435,21 +440,21 @@ def _step_l2_structural_match( # L2b:同用户 + PO 精确一致 + customer_code 精确一致 if payload['po_numbers'] and payload['customer_code']: - # ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code + # Candidate 结构化摘要:查 structured_result_json.business_summary.po_numbers / customer_code # 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向 same_customer_tasks = ( - ShippingNotice.query - .filter_by(user_id=int(case.owner_user_id)) - .filter(ShippingNotice.customer_code == payload['customer_code'] - if hasattr(ShippingNotice, 'customer_code') else True) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(case.owner_user_id)) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(20) .all() ) - po_matched: list[ShippingNotice] = [] + po_matched: list[ShippingOrderTask] = [] for task in same_customer_tasks: - structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None + candidate_row = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(task.id)).order_by(ShippingOrderCandidate.id.desc()).first() + structured = getattr(candidate_row, 'structured_result_json', None) if candidate_row is not None else None summary = structured.get('business_summary') if isinstance(structured, dict) else None task_pos: set[str] = set() if isinstance(summary, dict): @@ -460,7 +465,7 @@ def _step_l2_structural_match( po_matched.append(task) if len(po_matched) == 1: task = po_matched[0] - steps.append({'step': 'L2b-po_customer_match', 'passed': True, + steps.append({'step': 'L2b-po_customer_identity', 'passed': True, 'evidence': {'customer_code': payload['customer_code'], 'pos_matched': sorted(set(payload['po_numbers']) & {str(x).strip().upper() for x in @@ -474,11 +479,11 @@ def _step_l2_structural_match( confidence=ReconcileConfidence.PROBABLE, evidence=evidence, ) - steps.append({'step': 'L2b-po_customer_match', 'passed': False, + steps.append({'step': 'L2b-po_customer_identity', 'passed': False, 'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)', 'evidence': {'matched_count': len(po_matched)}}) else: - steps.append({'step': 'L2b-po_customer_match', 'passed': False, + steps.append({'step': 'L2b-po_customer_identity', 'passed': False, 'reason': 'PO 或 customer_code 缺失,无法联合匹配', 'evidence': {'pos_count': len(payload['po_numbers']), 'customer_code_empty': not bool(payload['customer_code'])}}) @@ -487,11 +492,11 @@ def _step_l2_structural_match( # 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous document_id = int(case.document_id) doc_tasks_multi = ( - ShippingNotice.query - .filter((ShippingNotice.source_document_id == document_id) | - (ShippingNotice.document_id == document_id)) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderCandidate.primary_document_id == document_id) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index 9f741b0f..3f59c2b9 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -25,8 +25,8 @@ backend/app/services/shipping_notice/reconciliation_projector.py 从 automation.reason_code / blocking_reason 拆出 {code, i18n_key, details} 与 invariants._REASON_TO_I18N_KEY 一致映射。 ⑤ project_case_user_status(case, automation) - 返回七值归一化 completed / cancelled / waiting_human / retryable / - failed / running / idle(与 shipping-processing user_status 同域)。 + 返回 F2 六值 completed / cancelled / waiting_human / retryable / + failed / running(与 USER_FACING_TASK_STATUSES 同域;禁止 idle)。 ⑥ project_case_primary_action(user_status, blocking_reason, available_actions, user_stage) 完整复刻 invariants._compute_primary_action 逻辑(1a~1i)。 ⑦ 总入口 project_review_case_projection_bundle(...) @@ -51,7 +51,7 @@ from app.models import ( UserStatus = Literal[ 'completed', 'cancelled', 'waiting_human', - 'retryable', 'failed', 'running', 'idle', + 'retryable', 'failed', 'running', ] @@ -142,7 +142,11 @@ def project_case_automation_status( job_id / error_code / reason_code / blocking_reason / next_action 的字典(与详情页 automation 同构)。 """ - from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot + from app.services.shipping_notice.order_review_workbench_projection import ( + JOB_FAILURE_STATUS_TOKENS, + project_job_status_outcome, + resolve_formal_ot, + ) from app.services.shipping_notice.order_stp_auto_create_service import ( build_stp_idempotency_key, find_active_stp_job, @@ -281,7 +285,7 @@ def project_case_automation_status( 'can_build': can_build, 'job_id': int(job.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed': result = latest.result_json if isinstance(latest.result_json, dict) else {} raw_retryable = result.get('retryable') if raw_retryable is None: @@ -313,9 +317,7 @@ def project_case_automation_status( 'error_code': result.get('error_code') or blocking_reason_raw, 'retry_of_job_id': int(latest.id), } - if latest is not None and str(latest.status or '').strip().lower() in { - 'succeeded', 'success', 'completed', - }: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded': return { 'status': 'completed', 'retryable': False, @@ -707,7 +709,7 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR # ============================================================ -# [5] user_status(七值归一化) +# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle) # ============================================================ def project_case_user_status( @@ -715,11 +717,12 @@ def project_case_user_status( automation: dict[str, Any] | None, ) -> UserStatus: """ - 与 shipping-processing invariants 的 user_status 七值同域映射。 + 与 USER_FACING_TASK_STATUSES / shipping-processing user_status 同域(F2 六值)。 + Case 草稿待处置默认 waiting_human;禁止再输出 idle。 """ auto_status = str((automation or {}).get('status') or '').strip().lower() case_status = str(case.status or '').strip().lower() - if auto_status in {'completed', 'success'}: + if auto_status == 'completed': return 'completed' if case_status in {'cancelled', 'superseded', 'non_order'}: return 'cancelled' @@ -734,7 +737,7 @@ def project_case_user_status( return 'waiting_human' if auto_status in {'waiting_to_start'}: return 'running' # waiting = 尚未运行,但系统已负责 - return 'idle' + return 'waiting_human' # ============================================================ @@ -815,7 +818,7 @@ def project_case_primary_action( # 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的 # 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。 - if user_status in {'waiting_human', 'idle'}: + if user_status == 'waiting_human': if 'create_draft' in actions: return {'code': 'create_draft', 'variant': 'primary', 'label_key': 'shipping.actions.create_draft'} @@ -861,6 +864,10 @@ def _project_fine_grained_pre_stp_blocking( from app.extensions import db from app.models import Job from app.jobs.types import JobType + from app.services.shipping_notice.order_review_workbench_projection import ( + JOB_FAILURE_STATUS_TOKENS, + project_job_status_outcome, + ) from app.services.shipping_notice.order_stp_auto_create_service import ( build_stp_idempotency_key, ) @@ -948,14 +955,17 @@ def _project_fine_grained_pre_stp_blocking( else: latest_failed = ( next( - (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}), + ( + job for job in prefix_jobs + if project_job_status_outcome(getattr(job, 'status', None)) == 'failed' + ), None, ) if prefix_jobs is not None else ( db.session.query(Job) .filter( Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, - Job.status.in_(('failed', 'dead')), + Job.status.in_(tuple(JOB_FAILURE_STATUS_TOKENS)), Job.business_ref.like(f"{business_ref_prefix}%"), ) .order_by(Job.id.desc()) @@ -1189,10 +1199,17 @@ def project_review_case_projection_bundle( # [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case # 草稿状态重算 order_review_build/idle,会覆盖批次投影已读取的 # field_completeness / required_field_missing,造成同一文件前后端状态冲突。 + # 但该裁决权只适用于已确认(post-OT)的正式 Gate;未确认(unreviewed/draft/ready + # 且无 confirmed_task_id)的 Case 仍停留在建单前,其当前 Gate / 用户态必须由 + # Case 派生事实(order_review_build / waiting_human)裁决,不得被正式 Gate 的 + # reservation_validation / running 反向覆盖。 formal_gate_facts = _project_case_formal_gate_facts( _project_case_formal_gate_summary(case), ) - if formal_gate_facts is not None: + if ( + formal_gate_facts is not None + and str(case.status or '').strip().lower() == 'confirmed' + ): current_gate, blocking_reason, user_status = formal_gate_facts # [STEP 6] primary_action # 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp; diff --git a/backend/app/services/shipping_notice/reconciliation_service.py b/backend/app/services/shipping_notice/reconciliation_service.py index f0da259f..c7f5e5bf 100644 --- a/backend/app/services/shipping_notice/reconciliation_service.py +++ b/backend/app/services/shipping_notice/reconciliation_service.py @@ -34,6 +34,7 @@ from app.jobs.types import JobType from app.models import ( Job, ShippingNotice, + ShippingOrderTask, ShippingOrderCandidate, ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, @@ -326,14 +327,15 @@ def _write_reconcile_audit_and_event( def _write_back_case_task_binding( *, case: ShippingOrderReviewCase, - task: ShippingNotice, + task: ShippingOrderTask, actor_type: str, ) -> None: """ Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。 1. Case.confirmed_task_id / confirmed_task_no 2. Candidate.fulfilled_task_id(若存在当前 Candidate) - 3. Document → Task 外键(ShippingNotice.source_document_id 如空则补) + 3. 来源文档继续由 Case.document_id / Candidate.primary_document_id 承载; + OT 只保存 intake/candidate 指针,不写入已移除的 source_document_id 投影。 """ case.confirmed_task_id = int(task.id) # confirmed_task_no 通常为 property,但实际存字段若可写则同步 @@ -350,12 +352,6 @@ def _write_back_case_task_binding( cand.fulfilled_task_id = int(task.id) except Exception: # noqa: BLE001 — 模型无列则降级 pass - # Document → Task 外键 - if not getattr(task, 'source_document_id', None) and getattr(case, 'document_id', None): - try: - task.source_document_id = int(case.document_id) - except Exception: # noqa: BLE001 - pass # ============================================================ @@ -537,8 +533,8 @@ def reconcile_and_progress( mlvl: str = match_result['match_level'] confidence: str = match_result['confidence'] matched_task_no: str | None = match_result.get('task_no') - matched_task: ShippingNotice | None = ( - ShippingNotice.query.filter_by(task_no=matched_task_no).first() + matched_task: ShippingOrderTask | None = ( + ShippingOrderTask.query.filter_by(task_no=matched_task_no).first() if matched_task_no else None ) @@ -775,12 +771,23 @@ def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCas return rj = latest.result_json if isinstance(latest.result_json, dict) else {} retryable_flag = bool(rj.get('retryable', True)) + error_code = str(rj.get('error_code') or '').strip() blocking_reason_raw = rj.get('blocking_reason') blocking_reason = ( {'code': str(blocking_reason_raw)} if isinstance(blocking_reason_raw, str) and blocking_reason_raw else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None ) + # 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false, + # 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通 + # retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。 + effective_error_code = error_code or ( + blocking_reason.get('code') + if isinstance(blocking_reason, dict) + else str(blocking_reason or '').strip() + ) + if not retryable_flag and effective_error_code == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED': + return if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason): raise ConflictError( 'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create', diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index eece70f1..ce987717 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -4,11 +4,13 @@ services/shipping_notice/recovery_invalidation_service.py 用途:按恢复动作精确失效库存下游事实及正式 Gate。 依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。 逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。 + 行级 scope(source_codes)时:只失效对应源链接与未发通知行的匹配,禁止触碰已有 Notice Artifact。 """ from __future__ import annotations from datetime import datetime +from sqlalchemy import false from app import db from app.models import ( @@ -19,21 +21,72 @@ from app.models import ( ShippingProcessExecution, ShippingTaskInventoryLink, ShippingUploadAttempt, + ShippingNotice, ) from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates +def _noticed_snapshot_line_ids(task_id: int) -> set[int]: + """ + 返回该 OT 下已写入正式发货通知行的 snapshot_line_id 集合。 + + 核心逻辑:ShippingNoticeLine 是「已产生发货通知」的权威事实;行级重抓不得改写这些行。 + """ + from app.models.shipping_notice_line import ShippingNoticeLine + + rows = ( + db.session.query(ShippingNoticeLine.snapshot_line_id) + .join(ShippingNotice, ShippingNotice.id == ShippingNoticeLine.notice_id) + .filter(ShippingNotice.order_task_id == int(task_id)) + .all() + ) + return {int(row[0]) for row in rows if row[0] is not None} + + +def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]: + """从匹配事实抽取规范化库存源集合,供行级失效过滤。""" + codes: set[str] = set() + primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + if primary: + codes.add(primary) + for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []): + code = str(raw or '').strip().upper() + if code: + codes.add(code) + return codes + + def invalidate_inventory_downstream( *, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None, actor_id: int | str | None = None, + source_codes: list[str] | None = None, + snapshot_line_id: int | None = None, ) -> dict[str, list[int] | list[str]]: - """失效库存恢复受影响事实,并返回可审计的对象 ID。""" + """ + 失效库存恢复受影响事实,并返回可审计的对象 ID。 + + 核心逻辑:整单恢复保持原行为;若传入 source_codes(行级重抓),则: + - 只停用对应源的库存链接; + - 只作废「未产生发货通知」且命中该源/该行的匹配事实; + - 禁止 supersede 已有 Notice 的 Artifact/Upload。 + + Args: + execution: 当前 ProcessExecution。 + action_code: 恢复动作码,决定失效深度。 + attempt_id: 可选 Gate Attempt ID。 + actor_id: 可选操作人。 + source_codes: 行级库存源;有值即进入行级收窄模式。 + snapshot_line_id: 可选被点击的冻结行 ID,用于精确命中该行匹配事实。 + + Returns: + 各类被失效对象 ID 列表。 + """ task_id = int(execution.task_id or 0) if not task_id: return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} now = datetime.utcnow() - from app.models import ShippingNotice - task = db.session.get(ShippingNotice, task_id) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, task_id) result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} change_type = { 'retry_inventory_preparation': 'inventory_file_changed', @@ -42,26 +95,43 @@ def invalidate_inventory_downstream( 'retry_inventory_from_matching': 'inventory_matching_changed', }.get(action_code, 'inventory_matching_changed') result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id) + scoped_codes = { + str(code).strip().upper() + for code in (source_codes or []) + if str(code).strip() + } + line_scoped = bool(scoped_codes) + protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set() + scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}: links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() for link in links: + link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper() + if line_scoped and link_code and link_code not in scoped_codes: + continue + if line_scoped and not link_code: + # 无源码的历史链接在行级重抓时不误伤;整单路径仍会停用。 + continue link.is_active = False link.invalidated_at = now link.invalidated_by_attempt_id = attempt_id link.invalidation_reason = action_code result['links'].append(int(link.id)) - active_file_ids = [ + affected_file_ids = [ int(link.inventory_file_id) for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all() - if link.inventory_file_id + if link.inventory_file_id and ( + not line_scoped + or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes + ) ] if action_code in { 'retry_inventory_preparation', 'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', - } and active_file_ids: + } and affected_file_ids: mappings = ShippingInventoryMapping.query.filter( - ShippingInventoryMapping.inventory_file_id.in_(active_file_ids), + ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids), ShippingInventoryMapping.status == 'active', ).with_for_update().all() for mapping in mappings: @@ -69,47 +139,40 @@ def invalidate_inventory_downstream( result['mappings'].append(int(mapping.id)) matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() for row in matches: + row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0) + if line_scoped and row_line_id in protected_line_ids: + continue + if line_scoped: + row_codes = _match_row_source_codes(row) + hit_scoped_line = scoped_snapshot_line_id is not None and row_line_id == scoped_snapshot_line_id + hit_scoped_source = bool(row_codes.intersection(scoped_codes)) + if not hit_scoped_line and not hit_scoped_source: + continue row.is_current = False row.invalidated_at = now row.invalidated_by_attempt_id = attempt_id row.invalidation_reason = action_code result['matches'].append(int(row.id)) - verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() - for verification in verifications: - verification.status = 'superseded' - result['verifications'].append(int(verification.id)) - artifacts = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task_id, - ShippingExportArtifact.status.in_({'ready', 'uploading'}), - ).with_for_update().all() - for artifact in artifacts: - artifact.status = 'superseded' - result['artifacts'].append(int(artifact.id)) - uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter( - ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}), + if not line_scoped: + verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() + for verification in verifications: + verification.status = 'superseded' + result['verifications'].append(int(verification.id)) + notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()] + artifacts = ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(), + ShippingExportArtifact.status.in_({'ready', 'uploading'}), ).with_for_update().all() - for upload in uploads: - upload.invalidated_at = now - upload.invalidation_reason = action_code - result['uploads'].append(int(upload.id)) - if task is not None and action_code in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', - 'retry_inventory_from_matching', - }: - # [BE-放行-恢复] 本动作已把当前匹配行置 is_current=False(上方),必须同步清空任务级 - # 派生状态,否则 UI 与 Gate 在下一轮重匹配前仍读到旧 match_status/shortage/line_results, - # 出现"已重试却仍显示旧缺货"的矛盾。 - task.match_status = None - task.shortage_json = None - task.line_results_json = None - if task is not None and ( - action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'} - ): - # 仅库存文件级重试才清空导出指针;匹配/字段映射级重试只作废匹配,不改已生成文件。 - task.export_file_path = None - task.export_file_name = None + for artifact in artifacts: + artifact.status = 'superseded' + result['artifacts'].append(int(artifact.id)) + uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter( + ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}), + ).with_for_update().all() + for upload in uploads: + upload.invalidated_at = now + upload.invalidation_reason = action_code + result['uploads'].append(int(upload.id)) db.session.flush() return result @@ -132,15 +195,16 @@ def invalidate_excel_regeneration_only( if not task_id: return result - from app.models import ShippingNotice, ShippingReservation + from app.models import ShippingOrderTask, ShippingReservation from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - task = db.session.get(ShippingNotice, task_id) + task = db.session.get(ShippingOrderTask, task_id) if task is None: return result now = datetime.utcnow() + notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()] artifacts = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task_id, + ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(), ShippingExportArtifact.status.in_({'ready', 'uploading'}), ).with_for_update().all() for artifact in artifacts: @@ -195,9 +259,6 @@ def invalidate_excel_regeneration_only( metadata={'execution_no': execution.execution_no, 'attempt_id': attempt_id}, source='process_gate', ) - if artifacts: - task.export_file_path = None - task.export_file_name = None result['gates'] = invalidate_downstream_gates( execution=execution, change_type='excel_regeneration_only', diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index efd049fe..a54ce91a 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -97,12 +97,21 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No if not task_no: return None - review_status = _clean_text(getattr(task, "review_status", None)).lower() - match_status = _clean_text(getattr(task, "match_status", None)).lower() - pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower() - upload_status = _clean_text(getattr(task, "upload_status", None)).lower() + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + from app import db + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + review_status = _clean_text(getattr(owner, "review_status", None)).lower() + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower() + pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower() + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + upload_attempt = latest_upload_attempt(task) if isinstance(task, ShippingNotice) else None + upload_status = _clean_text(getattr(upload_attempt, "status", None)).lower() - if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None): + if match_status == "shortage" or pending_reason == "shortage": return { "reason": "shortage", "label": "异常:库存不足", @@ -120,7 +129,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No "label": "异常:上传失败", "summary": f"{task_no} 上传失败", } - if _clean_text(getattr(task, "error_message", None)): + if _clean_text(getattr(owner, "error_message", None)): return { "reason": "error", "label": "异常:处理失败", diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 271630c2..8aea5a1a 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -19,8 +19,10 @@ INTERNAL_UUID_RE = re.compile( r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE, ) -# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351 -RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{10}|\d{5})\b") +# Reservation 本体后可带一段半角或全角括号备注;普通尾随文本不属于合法值。 +RESERVATION_VALUE_RE = re.compile(r"^(\d{10}|\d{5})(?!\d)\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$") +# ``@`` 是预约号与前缀说明的显式分隔,后缀复用 Reservation 值的括号备注契约。 +RESERVATION_AT_SUFFIX_RE = re.compile(r"@\s*(\d{10}|\d{5})(?!\d)(?=\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$)") PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, @@ -57,29 +59,36 @@ def normalize_reservation_id(value: Any) -> str: def extract_reservation_id(value: Any) -> str: - """从原值提取 Reservation ID 候选;合法性必须另由 `is_valid_reservation_id` 判断。""" + """标准化 Reservation ID,并识别 ``@`` 后带可选括号备注的预约号。 + + Args: + value: Reservation ID 字段原始值;仅允许整体纯数字,或明确 ``@`` 分隔后可带括号备注的纯数字。 + + Returns: + str: 已确认的五位或十位纯数字 Reservation ID;普通尾随文本或金额文本返回空字符串。 + """ text = str(value or "").strip() if not text: return "" direct = normalize_reservation_id(text) - if looks_like_reservation_id(direct): - return direct + direct_match = RESERVATION_VALUE_RE.fullmatch(direct) + if direct_match: + return direct_match.group(1) match = RESERVATION_AT_SUFFIX_RE.search(text) - if match: - return match.group(1) - - if "@" in text: - tail = normalize_reservation_id(text.rsplit("@", 1)[-1]) - if looks_like_reservation_id(tail): - return tail - - return direct + return match.group(1) if match else "" def find_reservation_id_in_document(text: str) -> str: - """扫描全文 PR Number 行或 @1000140351 后缀,提取文档级 Reservation ID。""" + """扫描全文 PR Number 行或 ``@`` 分隔、可带括号备注的 Reservation ID。 + + Args: + text: 文档原始文本;仅接受 ``@`` 后可带括号备注的完整五位或十位纯数字。 + + Returns: + str: 已验证的五位或十位纯数字 Reservation ID;无明确分隔证据时返回空字符串。 + """ body = str(text or "") if not body.strip(): return "" diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 372b92ed..c9e1f718 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -19,6 +19,7 @@ from app.models import ( ShippingInventoryVerification, ShippingInventoryVerificationLine, ShippingOrderSnapshot, + ShippingOrderTask, ShippingReservation, ShippingNotice, ) @@ -38,7 +39,7 @@ def _decimal(value: Any) -> Decimal: return result -def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: +def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]: """由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。""" snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None if snapshot is None: @@ -72,11 +73,18 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: code='SHIPPING.RESERVATION_PO_CONFLICT', details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized}, ) - elif row.task_id != task.id or row.snapshot_line_id != line.id: + elif ( + row.task_id != task.id + or row.snapshot_line_id != line.id + or row.part_number != part_number + or row.required_qty != _decimal(line.qty) + ): if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}: raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED') if row.part_number != part_number or row.required_qty != _decimal(line.qty): - if task.supersedes_task_id == row.task_id: + # 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version), + # Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。 + if row.task_id == task.id: _transfer_confirmed_revision(row, task=task, line=line, part_number=part_number) registered.append(row) continue @@ -96,20 +104,40 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: return registered +def _owner_task(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask: + """将 Notice/OT 输入统一解析为该任务所属的 OT(shipping_order_tasks 聚合根)。""" + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id is not None else None + if owner is None: + raise ConflictError('Shipping notice has no order task', code='SHIPPING.ORDER_TASK_REQUIRED') + return owner + + def _transfer_confirmed_revision( reservation: ShippingReservation, - *, task: ShippingNotice, + *, task: ShippingOrderTask, line: Any, part_number: str, ) -> None: - """仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。""" + """ + 同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。 + + 核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``, + Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。 + """ + owner = _owner_task(task) previous = { 'task_id': reservation.task_id, 'snapshot_line_id': reservation.snapshot_line_id, 'part_number': reservation.part_number, 'qty': str(reservation.required_qty), } - reservation.task_id = task.id + # 保留同一 ShippingOrderTask:版本 bump,Reservation/事件仍指向该 OT。 + owner.order_data_version = int(owner.order_data_version or 1) + 1 + owner.progress_version = int(owner.progress_version or 0) + 1 + reservation.task_id = owner.id reservation.snapshot_line_id = line.id reservation.part_number = part_number reservation.required_qty = _decimal(line.qty) @@ -119,16 +147,13 @@ def _transfer_confirmed_revision( 'reservation_id': reservation.reservation_id, 'previous': previous, 'proposed': { - 'task_id': task.id, + 'task_id': owner.id, 'snapshot_line_id': line.id, 'part_number': part_number, 'qty': str(reservation.required_qty), }, } - log_task_event(task, 'reservation_revision_confirmed', details) - parent = db.session.get(ShippingNotice, task.supersedes_task_id) - if parent is not None: - log_task_event(parent, 'reservation_revision_superseded', details) + log_task_event(owner, 'reservation_revision_confirmed', details) def record_inventory_verification( @@ -204,7 +229,7 @@ def reserve_available_for_artifact( released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() @@ -220,7 +245,7 @@ def reserve_available_for_artifact( } rows = ( ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.status.in_({'available', 'pending'}), ShippingReservation.id.in_(set(verification_lines)), ) @@ -268,7 +293,7 @@ def current_available_snapshot_line_ids( (最新核验轮次, 本次可导出的冻结订单行 ID)。 """ verification = ( - ShippingInventoryVerification.query.filter_by(task_id=task.id, status='completed') + ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') .order_by(ShippingInventoryVerification.id.desc()).first() ) if verification is None: @@ -278,7 +303,7 @@ def current_available_snapshot_line_ids( released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() @@ -293,7 +318,7 @@ def current_available_snapshot_line_ids( ) } reservations = ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(reservation_ids), ShippingReservation.status.in_({'available', 'pending'}), ).all() if reservation_ids else [] @@ -305,3 +330,7 @@ def current_available_snapshot_line_ids( if not line_ids: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') return verification, line_ids +def _inventory_task_id(task: Any) -> int: + """返回库存事实所属 OT ID;正式 Notice 通过 order_task_id 关联 OT。""" + linked = getattr(task, 'order_task_id', None) + return int(linked) if linked is not None else int(task.id) diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index eb9cbf02..1c08cb35 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -201,6 +201,56 @@ def inventory_rpa_batch_enabled() -> bool: return str(raw).strip().lower() in {"1", "true", "yes", "on"} +def build_on_demand_inventory_trigger_source( + task_no: str, + rpa_source: dict[str, Any], + *, + body: dict[str, Any], +) -> dict[str, Any]: + """ + 构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。 + 【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造, + 保证两条路径投递给 Worker 的输入契约完全一致。 + + Args: + task_no: 发货任务号。 + rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。 + body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。 + + Returns: + 可直接传入 write_inventory_export_batch_trigger 的单源条目。 + """ + from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source + + source_code = str(rpa_source.get('source_code') or '').strip() + rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source + # Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。 + rpa_source = dict(rpa_source) + business_connector = str(rpa_source.get('connector_type') or '').strip().lower() + rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector)) + rpa_source.setdefault('entry_url', rpa_source.get('login_url')) + rpa_source.setdefault('credential_envelope', {}) + source_item = dict(rpa_source) + source_item.update({ + "source_code": source_code, + "callback_id": body.get("callback_id") or ( + f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None + ), + "task_no": task_no, + # 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致 + # Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。 + "attempt_no": body.get("attempt_no") or body.get("attempt"), + "source_run_no": body.get("source_run_no"), + "candidate_set_id": body.get("candidate_set_id"), + "candidate_set_version": body.get("candidate_set_version"), + "execution_id": body.get("execution_id"), + "gate_id": body.get("gate_id"), + "expected_warehouse_id": body.get("expected_warehouse_id"), + "lease_token": body.get("lease_token"), + }) + return source_item + + def write_inventory_export_trigger_for_task( task_no: str, rpa_source: dict[str, Any], @@ -214,36 +264,10 @@ def write_inventory_export_trigger_for_task( 核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed, 不再生成 legacy inventory_export trigger。 """ - from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source - - source_code = str(rpa_source.get('source_code') or '').strip() - rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source - # Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。 - rpa_source = dict(rpa_source) - business_connector = str(rpa_source.get('connector_type') or '').strip().lower() - rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector)) - rpa_source.setdefault('entry_url', rpa_source.get('login_url')) - rpa_source.setdefault('credential_envelope', {}) body = dict(payload or {}) if inventory_rpa_batch_enabled(): run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") - source_item = dict(rpa_source) - source_item.update({ - "callback_id": body.get("callback_id") or ( - f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None - ), - "task_no": task_no, - # 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致 - # Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。 - "attempt_no": body.get("attempt_no") or body.get("attempt"), - "source_run_no": body.get("source_run_no"), - "candidate_set_id": body.get("candidate_set_id"), - "candidate_set_version": body.get("candidate_set_version"), - "execution_id": body.get("execution_id"), - "gate_id": body.get("gate_id"), - "expected_warehouse_id": body.get("expected_warehouse_id"), - "lease_token": body.get("lease_token"), - }) + source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body) return write_inventory_export_batch_trigger( run_no, [source_item], diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index 7c1d1a03..d03bdb00 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -12,7 +12,8 @@ from __future__ import annotations import json from typing import Any -from app.models import ShippingNotice +from app import db +from app.models import ShippingNotice, ShippingOrderIntake, ShippingOrderTask from app.services.agent_runtime_context.builder import build_agent_runtime_context from app.services.shipping_notice.reference_context import build_shipping_reference_context @@ -74,7 +75,9 @@ def _build_refs( """ refs: dict[str, str] = {} task_no = _task_no(task) - file_name = _clean_text(getattr(task, "source_file_name", None)) + file_name = '' + if getattr(task, 'source_intake_id', None): + file_name = _clean_text(getattr(db.session.get(ShippingOrderIntake, int(task.source_intake_id)), 'filename', None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: refs["task_no"] = task_no @@ -114,16 +117,26 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: state_hint["focus_task_no"] = task_no if task is not None: + owner = task + if isinstance(task, ShippingNotice) and task.order_task_id: + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or '' + upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip() for attr, key in ( ("current_step", "current_step"), ("review_status", "review_status"), - ("match_status", "match_status"), - ("pending_human_reason", "pending_human_reason"), - ("upload_status", "upload_status"), + (None, "match_status"), + (None, "upload_status"), ): - value = _clean_text(getattr(task, attr, None)) + value = match_status if key == 'match_status' else upload_status if key == 'upload_status' else _clean_text(getattr(owner, attr, None)) if value: state_hint[key] = value + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending_reason = _clean_text(task_blocking_reason(task)) + if pending_reason: + state_hint['pending_human_reason'] = pending_reason return state_hint @@ -145,10 +158,16 @@ def _build_summary( Returns: 200 字以内的现场摘要。 """ + owner = task + if isinstance(task, ShippingNotice) and task.order_task_id: + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task pieces: list[str] = [] task_no = _task_no(task) - file_name = _clean_text(getattr(task, "source_file_name", None)) - current_step = _clean_text(getattr(task, "current_step", None)) + file_name = '' + if getattr(owner, 'intake_id', None): + intake = db.session.get(ShippingOrderIntake, int(owner.intake_id)) + file_name = _clean_text(getattr(intake, 'filename', None)) + current_step = _clean_text(getattr(owner, "current_step", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: pieces.append(f"当前任务 {task_no}") diff --git a/backend/app/services/shipping_notice/schema_edit_policy.py b/backend/app/services/shipping_notice/schema_edit_policy.py index c149500e..2bfd08bf 100644 --- a/backend/app/services/shipping_notice/schema_edit_policy.py +++ b/backend/app/services/shipping_notice/schema_edit_policy.py @@ -62,55 +62,32 @@ def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any } -def is_excel_ready_for_task(task: ShippingNotice) -> bool: +def is_excel_ready_for_task(task: ShippingNotice | Any) -> bool: """ 判断发货 Excel 是否已成功生成并仍绑定当前订单数据版本。 - 核心逻辑:须存在 export_file_path,且 shipping_notice_export_artifacts 中有 - status=ready 且 file_path 匹配的 Artifact;若 step_payload.export_meta 记录了 - order_data_version,则须与当前 order_data_version 一致,否则视为 stale。 + 核心逻辑:必须存在当前任务的 ready Artifact,并且 Artifact 记录的订单解析版本 + 与 OT.current_order_extraction_id 一致;不再读取 OT.step_payload_json 中的旧导出投影。 Args: - task: 目标 ShippingNotice。 + task: 目标 ShippingNotice 或其所属 ShippingOrderTask。 Returns: True 表示正式字段应全局冻结。 """ - path = str(getattr(task, 'export_file_path', None) or '').strip() + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + artifact = latest_export_artifact(task) + path = str(getattr(artifact, 'file_path', None) or '').strip() if not path: return False task_id = getattr(task, 'id', None) if task_id is None: return False # [BE-09] 路径 alone 不足;必须存在当前 ready Artifact。 - from app.models import ShippingExportArtifact - - artifact = ( - ShippingExportArtifact.query.filter_by( - task_id=int(task_id), - status='ready', - file_path=path, - ) - .order_by( - ShippingExportArtifact.created_at.desc(), - ShippingExportArtifact.id.desc(), - ) - .first() - ) - if artifact is None: + if artifact is None or artifact.status != 'ready' or str(artifact.file_path or '') != path: return False - step_payload = dict(getattr(task, 'step_payload_json', None) or {}) - export_meta = step_payload.get('export_meta') if isinstance(step_payload.get('export_meta'), dict) else {} - raw_version = export_meta.get('order_data_version') - if raw_version is None or raw_version == '': - # 有 ready Artifact 但无版本指纹:仍冻结(fail-closed)。 - return True - try: - exported_version = int(raw_version) - except (TypeError, ValueError): - return True - current_version = int(getattr(task, 'order_data_version', None) or 1) - return exported_version == current_version + current_extraction_id = getattr(task, 'current_order_extraction_id', None) + return current_extraction_id is None or int(artifact.order_extraction_id or 0) == int(current_extraction_id) def is_field_editable_for_formal_task( diff --git a/backend/app/services/shipping_notice/shipping_notice_creation_service.py b/backend/app/services/shipping_notice/shipping_notice_creation_service.py new file mode 100644 index 00000000..ff3606fe --- /dev/null +++ b/backend/app/services/shipping_notice/shipping_notice_creation_service.py @@ -0,0 +1,160 @@ +""" +backend/app/services/shipping_notice/shipping_notice_creation_service.py + +用途:在库存准备与匹配门禁通过后创建正式 ShippingNotice。 +依赖:ShippingOrderTask、ShippingOrderSnapshot、ShippingNoticeLine、库存匹配事实。 +逻辑:OT/Snapshot 承载复核与库存准备;本模块是首次创建正式 Notice 的唯一入口, + 创建 NoticeLine 后才允许进入 Excel 导出。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import ConflictError +from app.models import ( + ShippingCustomer, + ShippingNotice, + ShippingNoticeLine, + ShippingOrderTask, + ShippingOrderSnapshot, +) +from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot +from app.services.shipping_notice.tool_common import generate_task_no + + +def create_shipping_notice_after_inventory_gate( + order_task: ShippingOrderTask, + *, + snapshot_line_ids: set[int] | None = None, + source_type: str = "inventory_gate", +) -> ShippingNotice: + """ + 库存门禁通过后创建或复用正式发货通知。 + + 【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。 + 不得在接收解析或订单复核确认阶段调用。 + + Args: + order_task: 已冻结订单快照的 OT。 + snapshot_line_ids: 可选的本次通知行集合;为空表示整单。 + source_type: Notice 来源标记。 + + Returns: + 已 flush 的正式 ShippingNotice。 + + Raises: + ConflictError: OT、Snapshot、客户或库存门禁事实不完整。 + """ + if order_task is None or order_task.id is None: + raise ConflictError("Order task is required before creating a shipping notice", code="SHIPPING.ORDER_TASK_REQUIRED") + snapshot_id = getattr(order_task, "order_snapshot_id", None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + if snapshot is None: + raise ConflictError("Order snapshot is required before creating a shipping notice", code="SHIPPING.ORDER_SNAPSHOT_REQUIRED") + customer_id = int(snapshot.customer_id or 0) + if not customer_id: + raise ConflictError("Confirmed customer is required before creating a shipping notice", code="SHIPPING.CUSTOMER_REQUIRED") + customer = db.session.get(ShippingCustomer, customer_id) + if customer is None or customer.status != 'active': + raise ConflictError("Confirmed customer is unavailable", code="SHIPPING.CUSTOMER_REQUIRED") + + selected_ids = {int(item) for item in (snapshot_line_ids or set())} + if selected_ids and not selected_ids.issubset({int(line.id) for line in snapshot.lines}): + raise ConflictError("Selected snapshot lines are invalid", code="SHIPPING.SNAPSHOT_LINE_INVALID") + + existing = ( + ShippingNotice.query + .filter_by(order_task_id=int(order_task.id)) + .order_by(ShippingNotice.id.desc()) + .first() + ) + if existing is not None: + existing_lines = { + int(line.snapshot_line_id) + for line in ShippingNoticeLine.query.filter_by(notice_id=int(existing.id)).all() + if line.snapshot_line_id is not None + } + if not selected_ids or existing_lines == selected_ids: + return existing + raise ConflictError( + "An existing shipping notice already owns a different snapshot line set", + code="SHIPPING.NOTICE_LINE_SET_CONFLICT", + ) + + # 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时, + # OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。 + from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink + fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by( + task_id=int(order_task.id), is_current=True, + ).all() + target_ids = selected_ids or {int(line.id) for line in snapshot.lines} + by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None} + from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task + released_ids = _released_snapshot_line_ids_for_task(order_task) + if not target_ids or any( + int(line_id) not in by_line + or ( + not ( + str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched' + and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready' + ) + and int(line_id) not in released_ids + ) + for line_id in target_ids + ): + raise ConflictError( + "Inventory matching must pass before creating a shipping notice", + code="SHIPPING.INVENTORY_GATE_NOT_PASSED", + ) + + inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {} + for snapshot_line_id in target_ids: + match = by_line[int(snapshot_line_id)] + inventory_file = ( + db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id)) + if match.inventory_snapshot_id is not None + else None + ) + link = ( + ShippingTaskInventoryLink.query.filter_by( + task_id=int(order_task.id), + inventory_file_id=int(inventory_file.id), + matched_source_code=match.inventory_source_code, + is_active=True, + ).order_by(ShippingTaskInventoryLink.id.desc()).first() + if inventory_file is not None + else None + ) + inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = { + 'inventory_source_code': match.inventory_source_code, + 'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None, + 'inventory_warehouse_id': ( + str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper() + or str(getattr(inventory_file, 'warehouse_id', '') or '').strip().upper() + or None + ), + } + + source_codes = sorted({ + str(fact['inventory_source_code'] or '').strip().upper() + for fact in inventory_facts_by_snapshot_line_id.values() + if str(fact['inventory_source_code'] or '').strip() + }) + notice = ShippingNotice( + task_no=generate_task_no(), + order_task_id=int(order_task.id), + user_id=order_task.user_id, + conversation_id=order_task.conversation_id, + source_type=str(source_type or "inventory_gate"), + source_intake_id=order_task.intake_id, + source_candidate_id=order_task.candidate_id, + ) + db.session.add(notice) + db.session.flush() + replace_notice_lines_from_snapshot( + notice_id=int(notice.id), + snapshot=snapshot, + snapshot_line_ids=selected_ids, + inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id, + ) + return notice diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index e6509640..671c86ee 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -9,12 +9,13 @@ services/shipping_notice/shipping_processing_projection.py ShippingProcessExecution / FileAsset / Job。 逻辑:由 GET /shipping-processing/conversations/{id} 与 work-items 路由调用; 直接以 ShippingOrderTask 为 order_task 来源,Stage 1 Intake 作 order_intake; - Intake/OT 均填充 current_gate(优先真实 ProcessExecution)与 source_summary; - 输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / Excel Artifact - 写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖); - 已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task); - **只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no; - work_items 构建后由 _conversation_processing_from_work_items 构建正式 conversation_processing; + Intake/OT 均填充 current_gate(优先真实 ProcessExecution,含无 Notice 时 OT 活跃 Execution) + 与 source_summary;输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / + Excel Artifact 写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准 + (BE-07,禁止 Notice 覆盖);已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage + 同源(project_stage_for_task);**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert); + 已建 Notice 时填 shipping_notice_no;work_items 构建后由 + _conversation_processing_from_work_items 构建正式 conversation_processing; 不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。 """ @@ -25,6 +26,7 @@ from dataclasses import dataclass from datetime import datetime from typing import Any +from sqlalchemy import or_ from sqlalchemy.orm import load_only, selectinload from app import db @@ -77,12 +79,27 @@ from app.services.shipping_notice.progress_audit_contract import ( logger = logging.getLogger(__name__) +def _latest_notice_for_order_task(order_task: ShippingOrderTask | None) -> ShippingNotice | None: + """按正式 Notice 的 order_task_id 反查最近一张通知单;OT 不保存反向通知指针。""" + if order_task is None or getattr(order_task, 'id', None) is None: + return None + return ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(order_task.id)) + .order_by(ShippingNotice.id.desc()) + .first() + ) + + @dataclass(frozen=True) class _ConversationProjectionLoadContext: """会话投影的一次性只读预取结果,避免 EML 附件按 Intake 重复查询。""" documents_by_intake_id: dict[int, list[ShippingOrderDocument]] intakes_by_no: dict[str, ShippingOrderIntake] + # 冻结选择计划中每个 Intake 的附件项(含已选/跳过状态),用于把尚未物化的 + # 「已选但未识别」附件展示出来,便于排查未识别原因。 + planned_attachments_by_intake_no: dict[str, list[dict[str, Any]]] prefetched_gate_attempts: list[ShippingProcessGateAttempt] read_cache: dict[str, Any] @@ -91,9 +108,18 @@ _CONVERSATION_PROJECTION_READ_CACHE_KEY = 'shipping_conversation_projection_read def _conversation_projection_read_cache() -> dict[str, Any] | None: - """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。""" + """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。 + + 该会话键会被下游 process_gate_projection / order_review_projection 复用并以不同 + 形状覆盖(只写 latest_attempt_by_id / gates_by_execution_id 等子集)。因此只有 + 确实由 _conversation_projection_load_context 赋予 load_context 形状(含 + current_case_by_document_id 标记键)时才视为会话投影缓存;否则按无缓存处理, + 让消费方回退到只读查询,避免读取到缺少 runs_by_id 等键的不完整字典。 + """ cached = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) - return cached if isinstance(cached, dict) else None + if isinstance(cached, dict) and 'current_case_by_document_id' in cached: + return cached + return None def _conversation_projection_load_context( @@ -309,14 +335,86 @@ def _conversation_projection_load_context( and case.confirmed_task_id is None for case in conversation_stream_cases ) + # 冻结选择计划仅用于 EML 附件(展示已选但未物化/未识别的附件行);直传 PDF + # 不消费该计划,读取它只会多扫一次 runs 快照。非 EML 会话直接跳过,保持 + # 首屏摘要零 runs 查询(否则空白/刚上传首屏会随历史 Run 数量线性变慢)。 + has_eml_intake = any( + str(getattr(intake, 'source_type', '') or '').strip().lower() == 'eml' + for intake in intakes + ) return _ConversationProjectionLoadContext( documents_by_intake_id=documents_by_intake_id, intakes_by_no={str(intake.intake_no): intake for intake in intakes}, + planned_attachments_by_intake_no=( + _frozen_attachment_plan_by_intake(intake_ids) if has_eml_intake else {} + ), prefetched_gate_attempts=prefetched_gate_attempts, read_cache=read_cache, ) +def _frozen_attachment_plan_by_intake( + intake_ids: list[int], +) -> dict[str, list[dict[str, Any]]]: + """读取当前(未被替代)Run 的冻结选择计划,按 Intake 归集附件项。 + + 核心逻辑:选择计划是发送时冻结的可审计事实,包含每个附件的 selected 结论与 + skip_reason_codes;供投影把「已选但尚未物化/未识别」的附件一并展示,便于排查 + 未识别原因。只读取选择计划本身,不触碰附件正文 / Document / 布局。 + """ + if not intake_ids: + return {} + run_rows = ( + ShippingOrderProcessingRun.query.with_entities( + ShippingOrderProcessingRun.input_snapshot_json, + ShippingOrderProcessingRun.request_snapshot_json, + ) + .join( + ShippingOrderProcessingRunIntake, + ShippingOrderProcessingRunIntake.run_id == ShippingOrderProcessingRun.id, + ) + .filter( + ShippingOrderProcessingRunIntake.intake_id.in_(intake_ids), + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), + ) + .all() + ) + planned_by_key: dict[str, dict[str, dict[str, Any]]] = {} + for row in run_rows: + snapshot = ( + row.input_snapshot_json + if isinstance(row.input_snapshot_json, dict) + else row.request_snapshot_json + ) + if not isinstance(snapshot, dict): + continue + selection = snapshot.get('attachment_selection') + if not isinstance(selection, dict): + continue + for item in selection.get('items') or []: + if not isinstance(item, dict): + continue + intake_no = str(item.get('intake_no') or '').strip() + if not intake_no: + continue + attachment_key = str(item.get('attachment_key') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + filename = str(item.get('filename') or '').strip().lower() + item_key = attachment_key or content_hash or filename + if not item_key: + continue + entries = planned_by_key.setdefault(intake_no, {}) + current = entries.get(item_key) + # 重解析 Run 可能保留同一附件的旧 selected=True 与新 selected=False 快照; + # 展示和计数以用户曾明确选择过该附件为准,避免把实际提交的文件反向隐藏。 + if current is None or (item.get('selected') is True and current.get('selected') is not True): + entries[item_key] = dict(item) + return { + intake_no: list(entries.values()) + for intake_no, entries in planned_by_key.items() + } + + def _has_reparseable_batch_documents_for_projection( *, run: ShippingOrderProcessingRun, load_context: _ConversationProjectionLoadContext | None = None, @@ -560,7 +658,7 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str: source_type = str(intake.source_type or '').strip().lower() if extraction_status in {'failed', 'error', 'fatal'}: return 'failed' - if extraction_status in {'cancelled', 'canceled'}: + if extraction_status == 'cancelled': return 'cancelled' if parse_status == 'parse_failed': return 'failed' @@ -903,6 +1001,14 @@ def project_intake_work_item( unit_by_document_id=unit_by_document_id, load_context=load_context, ) + aggregate_children = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=aggregate_children, + planned_by_intake_no=( + load_context.planned_attachments_by_intake_no + if load_context is not None else {} + ), + ) aggregate_states = [ str(child.get('user_status') or child.get('status') or '').strip().lower() for child in aggregate_children @@ -913,6 +1019,8 @@ def project_intake_work_item( if isinstance(child.get('facts'), dict) ] failed_count = sum(state in {'failed', 'retryable'} for state in aggregate_states) + # [AUTHORITY] 未确认 Candidate Review Case 投影为 waiting_human(等用户处置), + # 属待人工而不是系统处理中。 waiting_count = sum(state == 'waiting_human' for state in aggregate_states) completed_count = sum( state == 'completed' and upload_state == 'succeeded' @@ -945,7 +1053,7 @@ def project_intake_work_item( if any(state in {'failed', 'retryable'} for state in aggregate_states): payload['user_status'] = 'failed' payload['user_group'] = 'failed' - elif any(state in {'waiting_human', 'idle'} for state in aggregate_states): + elif any(state == 'waiting_human' for state in aggregate_states): payload['user_status'] = 'waiting_human' payload['user_group'] = 'waiting_human' elif all(state == 'completed' for state in aggregate_states): @@ -955,7 +1063,7 @@ def project_intake_work_item( payload['user_status'] = 'running' payload['user_group'] = 'processing' representative = next( - (child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human', 'idle'}), + (child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human'}), aggregate_children[0], ) payload['user_stage'] = str(representative.get('user_stage') or representative.get('stage') or payload.get('user_stage') or '') @@ -1024,15 +1132,29 @@ def _latest_intake_run_unit_outcomes( return outcomes -def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: - """ - 从 Run 关联的首个 Intake 推断 source_type。 +_RUN_PRIMARY_INTAKE_CACHE_KEY = 'shipping_run_primary_intake_cache' - 核心逻辑:优先 active RunIntake → Intake.source_type;再回退快照 intakes。 + +def _run_primary_intake(run: ShippingOrderProcessingRun) -> ShippingOrderIntake | None: """ + 取 Run 关联的首个未释放 Intake;请求内按 run_id 记忆化。 + + 核心逻辑:单工作项/会话投影会在一次请求内多次调用 `_source_type_for_run` / + `_first_intake_no_for_run` / `_submission_no_for_run`,此前每次都重复查询 + RunIntake 链接。此处将「Run → 主 Intake」这一事实按 run_id 缓存到当前 + SQLAlchemy 会话(请求级),避免 N 次重复 SQL。快照 fallback 仍由调用方兜底。 + """ + cache = db.session.info.get(_RUN_PRIMARY_INTAKE_CACHE_KEY) + if not isinstance(cache, dict): + cache = {} + db.session.info[_RUN_PRIMARY_INTAKE_CACHE_KEY] = cache + run_id = int(run.id) + if run_id in cache: + return cache[run_id] + intake: ShippingOrderIntake | None = None link = ( ShippingOrderProcessingRunIntake.query.filter( - ShippingOrderProcessingRunIntake.run_id == int(run.id), + ShippingOrderProcessingRunIntake.run_id == run_id, ShippingOrderProcessingRunIntake.released_at.is_(None), ) .order_by(ShippingOrderProcessingRunIntake.position.asc()) @@ -1040,10 +1162,21 @@ def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: ) if link is not None: intake = db.session.get(ShippingOrderIntake, int(link.intake_id)) - if intake is not None: - source = str(intake.source_type or '').strip().lower() or None - if source in ORDER_INTAKE_SOURCE_TYPES: - return source + cache[run_id] = intake + return intake + + +def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: + """ + 从 Run 关联的首个 Intake 推断 source_type。 + + 核心逻辑:优先 active RunIntake → Intake.source_type;再回退快照 intakes。 + """ + intake = _run_primary_intake(run) + if intake is not None: + source = str(intake.source_type or '').strip().lower() or None + if source in ORDER_INTAKE_SOURCE_TYPES: + return source snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for row in snapshot.get('intakes') or []: if not isinstance(row, dict): @@ -1064,18 +1197,9 @@ def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: def _first_intake_no_for_run(run: ShippingOrderProcessingRun) -> str: """取 Run 首个关联 Intake 编号;无则空串。""" - link = ( - ShippingOrderProcessingRunIntake.query.filter( - ShippingOrderProcessingRunIntake.run_id == int(run.id), - ShippingOrderProcessingRunIntake.released_at.is_(None), - ) - .order_by(ShippingOrderProcessingRunIntake.position.asc()) - .first() - ) - if link is not None: - intake = db.session.get(ShippingOrderIntake, int(link.intake_id)) - if intake is not None: - return str(intake.intake_no) + intake = _run_primary_intake(run) + if intake is not None: + return str(intake.intake_no) snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for row in snapshot.get('intakes') or []: if isinstance(row, dict) and row.get('intake_no'): @@ -1088,7 +1212,9 @@ def _submission_no_for_run(run: ShippingOrderProcessingRun) -> str: intake_no = _first_intake_no_for_run(run) if not intake_no: return '' - intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).first() + intake = _run_primary_intake(run) + if intake is None or str(intake.intake_no) != intake_no: + intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).first() if intake is None or not intake.order_submission_id: return '' submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id)) @@ -1291,7 +1417,7 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S return None cache = _conversation_projection_read_cache() if cache is not None: - case = cache['current_case_by_document_id'].get(int(document_id)) + case = (cache.get('current_case_by_document_id') or {}).get(int(document_id)) return case if case is not None and str(case.status or '') in {'unreviewed', 'draft', 'ready'} and case.confirmed_task_id is None else None return ( ShippingOrderReviewCase.query.join( @@ -1306,6 +1432,65 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S ) +def _gate_dict_from_order_task_execution( + order_task: ShippingOrderTask, +) -> dict[str, Any] | None: + """ + 从 OT 活跃 ProcessExecution 投影轻量 current_gate(含完整 process_gate 摘要)。 + + 核心逻辑:优先 active_process_execution_id,校验 task_id/非 superseded 后 + 回退按 task_id 取最新活跃 Execution;无有效 Gate 时返回 None。 + + Args: + order_task: 已绑定履约 Execution 的 ShippingOrderTask。 + + Returns: + 含 gate_code/status/next_action_code/_process_gate_summary 的 dict;无 Execution 时 None。 + """ + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import ( + project_user_gate_summary, + ) + + execution = None + active_execution_id = getattr(order_task, 'active_process_execution_id', None) + if active_execution_id is not None: + execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) + if execution is not None and ( + int(getattr(execution, 'task_id', 0) or 0) != int(order_task.id) + or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' + ): + execution = None + if execution is None: + execution = ( + ShippingProcessExecution.query.filter_by(task_id=int(order_task.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return None + summary = project_user_gate_summary(execution) + blocking = summary.get('current_blocking_gate') or summary.get('current_gate') + if not isinstance(blocking, dict) or not blocking.get('gate_code'): + return None + return { + 'gate_code': str(blocking.get('gate_code') or ''), + 'status': str(blocking.get('status') or 'blocked'), + 'next_action_code': ( + summary.get('next_action_code') + or blocking.get('next_action_code') + ), + 'blocking_reason_code': ( + summary.get('blocking_reason_code') + or blocking.get('blocking_reason_code') + ), + 'attempt_no': int(blocking.get('attempt_no') or 0), + # 写动作的 execution_no / Gate version 只能来自正式摘要。 + '_process_gate_summary': summary, + } + + def _order_task_current_gate( run: ShippingOrderProcessingRun, order_task: ShippingOrderTask | None, @@ -1313,8 +1498,9 @@ def _order_task_current_gate( """ 为 order_task 构造统一 current_gate 摘要。 - 核心逻辑:优先开放 Review Case 上的真实 ProcessExecution 门禁投影; - 无 Execution 时回退 Review Case / Run·OT 失败合成摘要;处理中不造假门禁。 + 核心逻辑:优先开放 Review Case 上的真实 ProcessExecution;其次 OT 活跃 Execution + (含尚未创建 Notice 的履约门禁,如库存满足性);无 Execution 时回退 Run·OT + 失败/waiting_review 合成摘要;处理中不造假门禁。 Args: run: Processing Run。 @@ -1388,49 +1574,12 @@ def _order_task_current_gate( 'attempt_no': 0, } - if order_task is not None and order_task.shipping_notice_id: - from app.models import ShippingProcessExecution - from app.services.shipping_notice.process_gate_projection import ( - project_user_gate_summary, - ) - - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) - if notice is not None: - execution = None - active_execution_id = getattr(notice, 'active_process_execution_id', None) - if active_execution_id is not None: - execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) - if execution is not None and ( - int(getattr(execution, 'task_id', 0) or 0) != int(notice.id) - or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' - ): - execution = None - if execution is None: - execution = ( - ShippingProcessExecution.query.filter_by(task_id=int(notice.id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() - ) - if execution is not None: - summary = project_user_gate_summary(execution) - blocking = summary.get('current_blocking_gate') or summary.get('current_gate') - if isinstance(blocking, dict) and blocking.get('gate_code'): - return { - 'gate_code': str(blocking.get('gate_code') or ''), - 'status': str(blocking.get('status') or 'blocked'), - 'next_action_code': ( - summary.get('next_action_code') - or blocking.get('next_action_code') - ), - 'blocking_reason_code': ( - summary.get('blocking_reason_code') - or blocking.get('blocking_reason_code') - ), - 'attempt_no': int(blocking.get('attempt_no') or 0), - # 写动作的 execution_no / Gate version 只能来自正式摘要。 - '_process_gate_summary': summary, - } + # [STEP] OT 活跃 Execution 优先于 status 启发式:正式 Notice 可能尚未创建 + # (库存匹配/满足性仍挂在 OT),不得把 waiting_review 误合成 open_order_review。 + if order_task is not None: + from_ot_execution = _gate_dict_from_order_task_execution(order_task) + if from_ot_execution is not None: + return from_ot_execution status = ( str(getattr(order_task, 'status', None) or '').strip().lower() @@ -1485,11 +1634,26 @@ def _child_order_tasks_for_run( .order_by(ShippingOrderTask.id.asc()) .all() ) + # [PERF] 批量预取兄弟 OT 的 Candidate,避免逐一 Lo 循环内 N+1 查询。 + candidate_ids = [ + int(sibling.candidate_id) + for sibling in siblings + if sibling.candidate_id + ] + candidates_by_id: dict[int, ShippingOrderCandidate] = {} + if candidate_ids: + candidates_by_id = { + int(candidate.id): candidate + for candidate in ShippingOrderCandidate.query.filter( + ShippingOrderCandidate.id.in_(candidate_ids), + ).all() + } rows: list[dict[str, Any]] = [] for sibling in siblings: - candidate = None - if sibling.candidate_id: - candidate = db.session.get(ShippingOrderCandidate, int(sibling.candidate_id)) + candidate = ( + candidates_by_id.get(int(sibling.candidate_id)) + if sibling.candidate_id else None + ) status = str(sibling.status or '').strip() or 'processing' if status not in SHIPPING_PROCESSING_STATUSES: status = map_run_status_to_processing_status(status) @@ -1512,10 +1676,8 @@ def _child_order_tasks_for_run( def _notice_no_for_order_task(order_task: ShippingOrderTask | None) -> str | None: - """若 OT 已挂正式 Notice,返回 notice.task_no(业务编号)。""" - if order_task is None or not order_task.shipping_notice_id: - return None - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + """若 OT 已创建正式 Notice,返回最近一张通知单 task_no。""" + notice = _latest_notice_for_order_task(order_task) if notice is None: return None return str(notice.task_no or '').strip() or None @@ -1571,8 +1733,8 @@ def _project_order_task_work_item( # [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。 stage_label_key = None notice_for_stage = None - if order_task.shipping_notice_id: - notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + if order_task is not None: + notice_for_stage = _latest_notice_for_order_task(order_task) if notice_for_stage is not None: from app.services.shipping_notice.order_review_workbench_projection import ( project_stage_for_task, @@ -1582,7 +1744,8 @@ def _project_order_task_work_item( if shared_code in SHIPPING_PROCESSING_STAGES: stage = shared_code stage_label_key = str(shared.get('label_key') or '').strip() or None - active_execution_id = getattr(notice_for_stage, 'active_process_execution_id', None) + # ProcessExecution 属于 OT;正式 Notice 不保存执行指针。 + active_execution_id = getattr(order_task, 'active_process_execution_id', None) if active_execution_id is not None: from app.models import ShippingProcessExecution active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) @@ -1620,13 +1783,17 @@ def _project_order_task_work_item( ) # 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留 # completed/uploaded;缺少成功 Attempt 时必须停在货代上传,不能进入完成统计。 - from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import ( + has_verified_upload_success, + project_notice_upload_status, + ) verified_upload_success = bool( notice_for_stage is not None and has_verified_upload_success(notice_for_stage) ) - notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else '' - notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else '' + projected_upload = ( + project_notice_upload_status(notice_for_stage) if notice_for_stage is not None else None + ) notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else '' if verified_upload_success: status = 'completed' @@ -1635,8 +1802,7 @@ def _project_order_task_work_item( elif notice_for_stage is not None and ( status == 'completed' or stage == 'completed' - or notice_process_status in {'uploaded', 'closed', 'completed'} - or notice_upload_status in {'uploaded', 'succeeded', 'success'} + or projected_upload == 'uploaded' ): status = 'waiting_human' stage = 'freight_uploading' @@ -1656,8 +1822,8 @@ def _project_order_task_work_item( notice = None invalidated_from_stage = None excel_ready = False - if order_task.shipping_notice_id: - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + if order_task is not None: + notice = _latest_notice_for_order_task(order_task) if notice is not None: from app.services.shipping_notice.task_workflow import ( read_notice_invalidated_from_stage, @@ -1711,11 +1877,7 @@ def _project_order_task_work_item( case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None notice_no_for_task = _notice_no_for_order_task(order_task) - has_formal_ot = bool( - order_task is not None - and getattr(order_task, 'shipping_notice_id', None) is not None - and notice_no_for_task is not None - ) + has_formal_ot = bool(order_task is not None and notice_no_for_task is not None) current_gate = _order_task_current_gate(run, order_task) process_gate = None if isinstance(current_gate, dict): @@ -1800,7 +1962,7 @@ def _project_order_task_work_item( post_confirm=post_confirm_snapshot, is_admin=False, ) - # 建单前 Case 的 STP 事实优先于旧 OT/Run checkpoint。旧 stage 可能仍是 + # 建单前 Case 的 STP 事实优先于 OT/Run 遗留 stage。旧 stage 可能仍是 # document_parsing/customer_resolving,但不可重试 STP 失败实际已经停在 task_creation。 pre_ot_stp = str(bundle.get('user_stage') or '').strip().lower() == 'pre_ot_stp' if pre_ot_stp: @@ -1866,7 +2028,7 @@ def _project_order_task_work_item( child['current_gate'] = dict(payload.get('current_gate') or {}) except Exception: # noqa: BLE001 # Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到 - # 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。 + # 遗留 notice 字段,避免前端展示可继续执行的过时动作。 payload['user_status'] = 'waiting_human' payload.pop('retryable', None) payload['primary_action'] = None @@ -1883,9 +2045,10 @@ def _project_order_task_work_item( try: from app.models import ShippingInventoryPreparationAttempt + preparation_task_id = getattr(order_task, 'id', None) if order_task is not None else getattr(notice, 'order_task_id', None) preparation = ( ShippingInventoryPreparationAttempt.query - .filter_by(task_id=int(notice.id)) + .filter_by(task_id=int(preparation_task_id)) .filter(ShippingInventoryPreparationAttempt.status != 'superseded') .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) .first() @@ -1905,13 +2068,6 @@ def _project_order_task_work_item( } for row in source_attempts } - # 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared) - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task - - if active_inventory_lines_for_task(notice) and notice.inventory_snapshot_id: - for code in required_sources: - if code and code not in prepared_sources and code not in pending_sources: - prepared_sources.append(code) inventory_preparation = { 'attempt_id': int(preparation.id) if preparation else None, 'attempt_no': int(preparation.attempt_no) if preparation else None, @@ -2068,6 +2224,9 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> """ 将 work_item 状态映射为会话任务卡 status_label(前端 i18n 键)。 + 核心逻辑:status_label 与 F2 user_status 对齐;人工等待只发 waiting_human, + 禁止再用 pending_review 冒充 status(waiting_review 仅属 stage)。 + Args: item: order_task 工作项 dict。 @@ -2078,9 +2237,9 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> status = str(item.get('status') or '').strip().lower() stage = str(item.get('stage') or '').strip().lower() if item.get('verified_upload_success') is False and user_status == 'completed': - return 'pending_review' + return 'waiting_human' if user_status == 'waiting_human': - return 'pending_review' + return 'waiting_human' if user_status == 'retryable': return 'failed' if user_status in {'completed', 'cancelled', 'failed'}: @@ -2090,7 +2249,7 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> if status == 'failed': return 'failed' if status == 'waiting_review' or stage == 'waiting_review': - return 'pending_review' + return 'waiting_human' if status == 'completed' or stage == 'completed': return 'completed' if status == 'blocked': @@ -2111,7 +2270,7 @@ def _eml_aggregate_user_group( """ if any(state in {'failed', 'retryable'} for state in states): return 'failed' - if any(state in {'waiting_human', 'idle'} for state in states): + if any(state == 'waiting_human' for state in states): return 'waiting_human' if any(state not in {'completed', 'cancelled'} for state in states): return 'processing' @@ -2142,6 +2301,133 @@ def _intake_parse_case_primary_action(*, reparse_authorized: bool) -> dict[str, } +def _eml_leaf_processing_stage( + *, unit_status: str, parse_status: str, source_type: str | None, +) -> str: + """EML 无 OrderTask 叶子的统一 15 阶 stage 推进。 + + 识别主链顺序:document_parsing(材料解析/模板匹配/字段提取)→ + email_adjudicating(交叉裁决/邮件补充合并)→ candidate_creating(生成候选)。 + 仅作用于仍处于接收解析阶段的处理中叶子;失败/需人工/非订单由调用方先行裁决, + 因此这里只返回合法 SHIPPING_PROCESSING_STAGES 成员。 + """ + source = str(source_type or '').strip().lower() or None + unit = str(unit_status or '').strip().lower() + parsed = str(parse_status or '').strip().lower() + if unit == 'merging_supplement': + return 'email_adjudicating' if source == 'eml' else 'candidate_creating' + if unit in {'routing', 'matching_profile', 'extracting'}: + return 'document_parsing' + if unit == 'candidate_ready': + return 'candidate_creating' + # 尚无单元裁决:仍处于材料解析/版面对齐时显示文件解析;已解析则进入候选生成。 + if parsed in {'created', 'queued', 'parsing'}: + return 'document_parsing' + return 'candidate_creating' + + +def _planned_attachment_leaf( + plan_item: dict[str, Any], + *, + intake_no: str, + source_type: str | None = None, +) -> dict[str, Any]: + """把冻结选择计划里尚未物化的附件投影为「未识别」诊断叶子。 + + 核心逻辑:附件的真实识别结果以物化 `ShippingOrderDocument` 为准;计划中已选却 + 尚未物化的附件以 `facts.recognized=False` 标记,用于展示「待识别/处理中」,也用于 + 在文件统计中被排除(不计入已识别 total_files,但仍计入提交基 submitted_files)。 + `source_type` 沿用 Intake 真实来源(eml / direct_pdf),不写死为 eml。 + """ + filename = str(plan_item.get('filename') or '').strip() or None + attachment_key = str(plan_item.get('attachment_key') or '').strip() + return { + 'work_item_type': 'order_intake', + 'work_item_no': f'PLAN:{intake_no}:{attachment_key or filename or "unknown"}', + 'source_type': source_type or 'eml', + 'intake_no': intake_no, + 'status': 'processing', + 'user_status': 'processing', + 'user_stage': 'intake_parse', + 'stage': 'intake_parse', + 'user_group': 'processing', + 'source_summary': { + 'filename': filename, + 'document_count': 0, + 'document_id': None, + 'content_hash': str(plan_item.get('content_hash') or '').strip() or None, + 'attachment_key': attachment_key or None, + }, + 'facts': { + 'recognized': False, + 'plan_state': 'selected_pending', + }, + } + + +def _append_unrecognized_plan_attachments( + *, + intake: ShippingOrderIntake | None, + aggregate_children: list[dict[str, Any]], + planned_by_intake_no: dict[str, list[dict[str, Any]]], +) -> list[dict[str, Any]]: + """在 EML 聚合叶子后追加「已选但尚未物化/未识别」的附件诊断行。 + + 核心逻辑:已物化附件以其 document_id / content_hash / filename 与计划项匹配, + 匹配到的计划项不再重复;仅把计划中 selected=True 且尚未物化的附件追加为未识别行, + 便于排查「为什么这份没识别」。跳过项(duplicate/budget 等)不属于批次提交范围, + 不在此机械追加,避免与 submitted_files 口径冲突。 + + 摘要与详情/工作项路径共用本函数(传入各自的 `planned_by_intake_no`),保证 + 「全空窗期」也能把已选但尚未物化的附件列出,而非只有 submitted/total 计数。 + """ + if intake is None: + return aggregate_children + planned = planned_by_intake_no.get( + str(intake.intake_no or '').strip(), [], + ) + if not planned: + return aggregate_children + recognized_keys: set[str] = set() + for child in aggregate_children: + summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {} + content_hash = str(summary.get('content_hash') or '').strip().lower() + if content_hash: + recognized_keys.add(f'hash:{content_hash}') + document_id = int(summary.get('document_id') or 0) + if document_id > 0: + recognized_keys.add(f'doc:{document_id}') + filename = str(summary.get('filename') or '').strip().lower() + if filename: + recognized_keys.add(f'fn:{filename}') + attachment_key = str(summary.get('attachment_key') or '').strip().lower() + if attachment_key: + recognized_keys.add(f'ak:{attachment_key}') + result = list(aggregate_children) + seen: set[str] = set() + for item in planned: + if item.get('selected') is not True: + continue + filename = str(item.get('filename') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + attachment_key = str(item.get('attachment_key') or '').strip().lower() + key = ( + f'hash:{content_hash}' if content_hash + else f'fn:{filename}' if filename + else f'ak:{attachment_key}' if attachment_key + else f'plan:{attachment_key}' + ) + if key in recognized_keys or key in seen: + continue + seen.add(key) + result.append(_planned_attachment_leaf( + item, + intake_no=str(intake.intake_no or ''), + source_type=str(getattr(intake, 'source_type', None) or '').strip().lower() or None, + )) + return result + + def _eml_aggregate_document_children( *, intake: ShippingOrderIntake | None, @@ -2233,10 +2519,17 @@ def _eml_aggregate_document_children( # Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让 # EML 聚合退回「接收解析」。当前 Case 可来自局部重解析后的新 Unit, # 故必须按原 Document 的 Stream 指针查找,不能按旧 unit_id 反查。 + # 会话缓存键会被下游 process_gate_projection 复用并覆盖成不同形状(缺失 + # current_case_by_document_id);只在缓存明确命中时才用它,否则回退查询, + # 避免把真实存在的当前 Case 因缓存形状不匹配而误判为无人工处置。 cache = _conversation_projection_read_cache() + cached_cases = ( + cache.get('current_case_by_document_id') + if isinstance(cache, dict) else None + ) review_case = ( - cache['current_case_by_document_id'].get(int(document.id)) - if cache is not None else ( + cached_cases.get(int(document.id)) + if isinstance(cached_cases, dict) and int(document.id) in cached_cases else ( ShippingOrderReviewCase.query.join( ShippingOrderReviewStream, ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, @@ -2338,6 +2631,13 @@ def _eml_aggregate_document_children( ) ) if review_case is not None else unit_run ) + # [PROGRESS] 仍处接收解析的处理中叶子按真实单元/解析状态推进统一 15 阶, + # 避免整批折叠为 candidate_creating(解析/交叉裁决/生成候选应可区分)。 + leaf_stage = _eml_leaf_processing_stage( + unit_status=unit_status, + parse_status=parse_status, + source_type='eml', + ) leaf = { 'work_item_type': 'document', 'work_item_no': f'DOCUMENT:{document.id}', @@ -2353,8 +2653,8 @@ def _eml_aggregate_document_children( 'submission_no': '', 'intake_no': str(intake.intake_no), 'status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing', - 'stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', - 'stage_label_key': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', + 'stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, + 'stage_label_key': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, 'progress_version': int(getattr(intake, 'progress_version', None) or 1), 'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '', 'current_gate': review_gate if review_case is not None else None, @@ -2367,7 +2667,7 @@ def _eml_aggregate_document_children( ), 'primary_action': review_primary if (review_case is not None or unit_failed) else None, 'user_status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running', - 'user_stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', + 'user_stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, 'user_group': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing', 'facts': {'upload_state': 'not_required' if non_order_completed else 'not_created'}, # 接收解析阶段入口由后端裁决:开放 Case 可进入处置;尚无 Case 的失败 @@ -2459,10 +2759,20 @@ def _aggregate_eml_order_task_work_items( ), load_context=load_context, ) + # 追加「已选但尚未物化/未识别」的计划附件诊断行,使列表与 submitted_files + # 口径一致,并把未识别原因暴露给用户排查。 + aggregate_children = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=aggregate_children, + planned_by_intake_no=( + load_context.planned_attachments_by_intake_no + if load_context is not None else {} + ), + ) states = [_state(item) for item in aggregate_children] upload_states = [_upload_state(item) for item in aggregate_children] failed_count = sum(state in {'failed', 'retryable'} for state in states) - waiting_count = sum(state in {'waiting_human', 'idle'} for state in states) + waiting_count = sum(state == 'waiting_human' for state in states) # 用户视角的完成必须同时满足任务完成,且已货代上传或已正式裁决无需上传; # 候选已生成等中间态仍在处理中。 completed_count = sum( @@ -2538,7 +2848,7 @@ def _aggregate_eml_order_task_work_items( # 待人工按钮”的矛盾组合。 actionable_states = ( {'failed', 'retryable'} if aggregate_group == 'failed' - else {'waiting_human', 'idle'} if aggregate_group == 'waiting_human' + else {'waiting_human'} if aggregate_group == 'waiting_human' else set() ) actionable_child = next( @@ -2772,11 +3082,33 @@ def _conversation_task_row_from_work_item( # [AUTHORITY] EML 子文件已在后端聚合;会话/批次 UI 直接透传,禁止前端再按 # intake_no、状态或历史 Run 文档列表重新构建。 'aggregate_children': item.get('aggregate_children') or [], + 'source_type': item.get('source_type'), 'user_group': user_group, 'ui_state': _processing_ui_state_from_item(item), } +def _process_gate_allowed_action_codes(item: dict[str, Any]) -> list[str]: + """从 C 摘要(process_gate)提取原始 Gate 动作码,供 A 的 ui_state 透传(§2.5 归一)。 + + 优先级:allowed_actions(原始码列表)→ action_presentation[].code(含展示元数据)。 + C 的这些码已是与写契约(request_gate_action/PROCESS_GATE_ACTION_CODES)对齐的原始码; + A 不再用 available_actions 的展示别名覆盖它们,避免 mark_manual_uploaded→open_manual_upload 漂移。 + """ + process_gate = item.get('process_gate') + if not isinstance(process_gate, dict): + return [] + allowed = list(process_gate.get('allowed_actions') or []) + if allowed: + return [str(c or '').strip() for c in allowed if str(c or '').strip()] + presentation = process_gate.get('action_presentation') or [] + return [ + str(p.get('code') or '').strip() + for p in presentation + if isinstance(p, dict) and str(p.get('code') or '').strip() + ] + + def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: """将最终 Processing 投影封装为用户展示状态与已授权动作。 @@ -2790,6 +3122,16 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: 可被聊天卡、批次中心和工作台直接渲染的 ui_state。 """ primary_raw = item.get('primary_action') + # 正式 OT 的 Gate 摘要是恢复动作唯一来源;工作项兼容投影可能没有同步顶层 + # primary_action,但 current_blocking_gate/next_action_code 仍已明确授权。 + # 回填到 A(ui_state) 后,右侧任务卡才能展示并提交该恢复动作。 + if not isinstance(primary_raw, dict): + process_gate = item.get('process_gate') if isinstance(item.get('process_gate'), dict) else {} + gate_view = process_gate.get('current_blocking_gate') or process_gate.get('current_gate') or {} + gate_status = str(gate_view.get('status') or '').strip().lower() + gate_code = str(process_gate.get('next_action_code') or gate_view.get('next_action_code') or '').strip() + if gate_status in {'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal'} and gate_code: + primary_raw = {'code': gate_code, 'variant': 'primary'} primary = dict(primary_raw) if isinstance(primary_raw, dict) else None source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} lifecycle = project_lifecycle( @@ -2808,7 +3150,7 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: # 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。 has_intake_parse_context=bool(item.get('intake_parse_authorized')), verified_upload_success=bool(item.get('verified_upload_success')), - processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, + processing_stage=str(item.get('stage') or item.get('user_stage') or '').strip() or None, ) lifecycle_stage = lifecycle['lifecycle_stage'] if lifecycle_stage == 'upload_complete': @@ -2826,7 +3168,11 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: primary['target_lifecycle_stage'] = action_target primary_code = str((primary or {}).get('code') or '').strip() if lifecycle_stage != 'upload_complete': - for raw_code in item.get('available_actions') or []: + # [§2.5 差异① 归一] 次动作码透传 C 的原始 Gate 码(allowed_actions/action_presentation), + # 不再经 available_actions 的展示别名(如 mark_manual_uploaded→open_manual_upload)。 + # 使 A == B == C 动作码逐字一致,前端从 A 读到的码能与写契约(request_gate_action)对齐。 + raw_codes = list(_process_gate_allowed_action_codes(item)) or list(item.get('available_actions') or []) + for raw_code in raw_codes: code = str(raw_code or '').strip() if not code or code == primary_code: continue @@ -2877,8 +3223,9 @@ def _strip_legacy_action_fields_for_response(value: Any) -> Any: """在 API 边界移除已下线的顶层动作镜像。 内部投影仍可用 ``primary_action`` / ``available_actions`` 选择 EML 当前代表项, - 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离镜像,防止新旧合同再次被 - 客户端混用;递归处理 EML 子附件和会话状态组。 + 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离顶层镜像,防止新旧合同再次被 + 客户端混用;递归处理 EML 子附件和会话状态组。注意:``ui_state`` 是外部动作合同本体, + 其中的 ``primary_action`` / ``secondary_actions`` 必须保留,只剥离聚合/工作项顶层的旧镜像。 Args: value: 已完成全部聚合的公开 DTO 片段。 @@ -2886,15 +3233,21 @@ def _strip_legacy_action_fields_for_response(value: Any) -> Any: Returns: 不含旧顶层动作字段、其余结构不变的公开 DTO。 """ - if isinstance(value, list): - return [_strip_legacy_action_fields_for_response(item) for item in value] - if not isinstance(value, dict): - return value - return { - key: _strip_legacy_action_fields_for_response(item) - for key, item in value.items() - if key not in {'primary_action', 'available_actions'} - } + def _inner(item: Any, *, inside_ui_state: bool = False) -> Any: + if isinstance(item, list): + return [_inner(entry, inside_ui_state=inside_ui_state) for entry in item] + if not isinstance(item, dict): + return item + result: dict[str, Any] = {} + for key, sub in item.items(): + if not inside_ui_state and key in {'primary_action', 'available_actions'}: + continue + if key == 'ui_state': + result[key] = _inner(sub, inside_ui_state=True) + else: + result[key] = _inner(sub, inside_ui_state=inside_ui_state) + return result + return _inner(value) def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None: @@ -2934,7 +3287,7 @@ def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None: has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')), has_intake_parse_context=bool(item.get('intake_parse_authorized')), verified_upload_success=bool(item.get('verified_upload_success')), - processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, + processing_stage=str(item.get('stage') or item.get('user_stage') or '').strip() or None, )['lifecycle_stage'] @@ -3047,7 +3400,7 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> ) actionable_states = ( {'failed', 'retryable'} if group == 'failed' else - {'waiting_human', 'idle'} if group == 'waiting_human' else set() + {'waiting_human'} if group == 'waiting_human' else set() ) representative = next( (child for child in current_children if _state(child) in actionable_states), @@ -3085,11 +3438,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> for state, upload_state in zip(states, upload_states) ), 'processing': sum( - state not in {'failed', 'retryable', 'waiting_human', 'idle', 'completed'} + state not in {'failed', 'retryable', 'waiting_human', 'completed'} or (state == 'completed' and upload_state != 'succeeded') for state, upload_state in zip(states, upload_states) ), - 'needs_action': sum(state in {'waiting_human', 'idle'} for state in states), + 'needs_action': sum(state == 'waiting_human' for state in states), 'failed': sum(state in {'failed', 'retryable'} for state in states), 'stages': sorted({ str(child.get('user_stage') or child.get('stage') or '').strip() @@ -3158,6 +3511,10 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A for code in LIFECYCLE_STAGE_CODES } for item in ranked_items: + facts = item.get('facts') if isinstance(item.get('facts'), dict) else {} + # 已选但未识别的诊断附件仅用于解释提交文件差异,不能进入业务五阶段。 + if facts.get('recognized') is False: + continue lifecycle_stage = _lifecycle_stage_from_item(item) if lifecycle_stage is None: continue @@ -3226,8 +3583,7 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, if not task_no or task_no in seen: continue task = ShippingOrderTask.query.filter_by(task_no=task_no).first() - notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None - notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None + notice = _latest_notice_for_order_task(task) resolved = resolve_task_export_download(notice) if resolved is None: continue @@ -3267,6 +3623,8 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An return { 'status': str(selected.get('user_status') or selected.get('status') or 'running'), 'stage': str(selected.get('user_stage') or selected.get('stage') or ''), + # 5 业务阶段:与右侧批次中心轨道、工作台导航同源(前端只读做 i18n,禁止再映射)。 + 'lifecycle_stage': _lifecycle_stage_from_item(selected), 'blocking_reason': ( dict(selected['blocking_reason']) if isinstance(selected.get('blocking_reason'), dict) @@ -3287,11 +3645,186 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An def _batch_user_group(item: dict[str, Any]) -> str: - """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。""" + """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。 + + work_item 未携带显式 ``user_group``(例如直接由 ``_project_order_task_work_item`` + 投影、未经过 EML 聚合)时,以权威 ``user_status`` / ``status`` / ``stage`` 兜底推导同 + 一状态组,保证 status_groups、批次统计与五阶段与该文件的顶层用户态完全同源。 + """ group = str(item.get('user_group') or '').strip().lower() - if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: - return group - return 'unclassified' + if group: + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', 'unclassified'}: + return group + return 'unclassified' + user_status = str(item.get('user_status') or '').strip().lower() + status = str(item.get('status') or '').strip().lower() + stage = str(item.get('stage') or '').strip().lower() + if user_status in {'failed', 'retryable'}: + return 'failed' + if user_status == 'waiting_human': + return 'waiting_human' + if user_status in {'cancelled', 'archived', 'voided', 'deleted'}: + return 'cancelled' + if user_status == 'completed': + return 'completed' + if user_status == 'running': + return 'processing' + if status in {'failed', 'blocked'}: + return 'failed' + if status == 'waiting_review' or stage == 'waiting_review': + return 'waiting_human' + if status in {'cancelled', 'archived', 'voided', 'deleted'} or stage in { + 'cancelled', 'archived', 'voided', 'deleted', + }: + return 'cancelled' + if status == 'completed' or stage == 'completed': + return 'completed' + return 'processing' + + +def _split_eml_rows_by_leaf_status(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """将混合状态 EML 拆为按 PDF 状态分区的只读展示行。""" + result: list[dict[str, Any]] = [] + for row in rows: + children = row.get('aggregate_children') if isinstance(row.get('aggregate_children'), list) else [] + is_eml = str(row.get('source_type') or '').strip().lower() == 'eml' + grouped: dict[str, list[dict[str, Any]]] = {} + for child in children: + if not isinstance(child, dict): + continue + group = _batch_user_group(child) + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: + grouped.setdefault(group, []).append(child) + if not is_eml or not grouped: + result.append(row) + continue + total = len(children) + for group, grouped_children in grouped.items(): + grouped_row = dict(row) + representative = grouped_children[0] + grouped_row.update({ + 'aggregate_children': grouped_children, + 'file_count': len(grouped_children), + 'user_group': group, + 'group': 'needs_action' if group in {'failed', 'waiting_human'} else ( + 'history' if group in {'cancelled', 'archived'} else group + ), + 'status_label': 'waiting_human' if group == 'waiting_human' else ( + 'processing' if group == 'processing' else group + ), + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': representative.get('user_stage') or representative.get('stage'), + 'ui_state': representative.get('ui_state'), + 'available_actions': list(representative.get('available_actions') or []), + 'primary_action': representative.get('primary_action'), + 'blocking_reason': representative.get('blocking_reason'), + }) + summary = dict(row.get('aggregate_summary') or {}) + summary.update({'total': total, 'in_group': len(grouped_children)}) + grouped_row['aggregate_summary'] = summary + result.append(grouped_row) + return result + + +def _conversation_submitted_file_count( + *, user_id: int, conversation_id: str, +) -> int: + """会话级「本次提交/已选附件数」,来自冻结选择计划,物化前即可用且单调递增。 + + 核心逻辑:直传 PDF(非 EML)的提交基只读授权 ShippingOrderIntake(会话内非 EML + Intake 数),不触碰处理 Run 快照;仅 EML Intake 需要其冻结选择计划(当前未被替代 + Run 的快照)来求已选附件数(随追加 / 扩批增长)。该值是用户在发送时刻就已知的 + 「提交基」事实,绝不随物化进度回落为 0。 + 已识别数(处理中/完成/待办/失败)另由 _batch_file_counts 基于物化文档裁决, + 本函数只负责提交基主计数,两者不能混用。 + """ + normalized = str(conversation_id or '').strip() + if not normalized: + return 0 + # [STEP 1] 授权事实先行:直传 PDF(非 EML)的提交基 = 会话内非 EML Intake 数。 + # 只读 ShippingOrderIntake 即可得出;绝不为直传 PDF 会话回退到处理 Run 的 + # JSON 快照解码,避免首屏摘要重新进入 run 轮询路径(BE:summary 不读 run 快照)。 + intake_rows = ( + ShippingOrderIntake.query.with_entities( + ShippingOrderIntake.id, + ShippingOrderIntake.source_type, + ) + .filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ) + .all() + ) + direct_pdf_count = sum( + 1 + for row in intake_rows + if str(row.source_type or '').strip().lower() != 'eml' + ) + has_eml = any( + str(row.source_type or '').strip().lower() == 'eml' + for row in intake_rows + ) + if not has_eml: + # 无 EML 参与即不存在冻结附件选择,提交基仅由直传 PDF Intake 构成。 + return direct_pdf_count + # [STEP 2] 仅 EML 需要冻结选择计划(当前 Run 快照)来求已选附件数;这是 + # 首屏摘要的唯一例外(见 project_conversation_processing_summary 注释)。 + rows = ( + ShippingOrderProcessingRun.query.with_entities( + ShippingOrderProcessingRun.input_snapshot_json, + ShippingOrderProcessingRun.request_snapshot_json, + ) + .filter( + ShippingOrderProcessingRun.user_id == int(user_id), + ShippingOrderProcessingRun.conversation_id == normalized, + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), + ) + .all() + ) + selected_eml_attachments: set[tuple[str, str]] = set() + active_intake_ids: set[int] = set() + for row in rows: + # input_snapshot_json 是物化/执行快照(扩批后更新);缺失时回退只读审计快照。 + snapshot = ( + row.input_snapshot_json + if isinstance(row.input_snapshot_json, dict) + else row.request_snapshot_json + ) + if not isinstance(snapshot, dict): + continue + selection = snapshot.get('attachment_selection') + if isinstance(selection, dict): + for item in selection.get('items') or []: + if not isinstance(item, dict) or item.get('selected') is not True: + continue + intake_no = str(item.get('intake_no') or '').strip() + attachment_key = str(item.get('attachment_key') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + filename = str(item.get('filename') or '').strip().lower() + item_key = attachment_key or content_hash or filename + if intake_no and item_key: + selected_eml_attachments.add((intake_no, item_key)) + for raw_intake in snapshot.get('intakes') or []: + if isinstance(raw_intake, dict) and int(raw_intake.get('intake_id') or 0): + active_intake_ids.add(int(raw_intake['intake_id'])) + if not active_intake_ids: + return len(selected_eml_attachments) + direct_pdf_count + # 直传 PDF(非 EML):每个当前活动 Intake 即为 1 个业务文件。 + # 注意 source_type 为 NULL(历史/未知)也算非 EML,避免 SQL 的 NULL != 'eml' 过滤掉。 + direct_pdf_count = ( + ShippingOrderIntake.query + .filter( + ShippingOrderIntake.id.in_(active_intake_ids), + ShippingOrderIntake.purpose == 'shipping_notice', + or_( + ShippingOrderIntake.source_type.is_(None), + ShippingOrderIntake.source_type != 'eml', + ), + ) + .count() + ) + return len(selected_eml_attachments) + direct_pdf_count def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: @@ -3299,6 +3832,11 @@ def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: # 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。 groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0} for item in _current_file_representatives(work_items): + # 「已选但尚未物化/未识别」的计划附件只计入提交基 submitted_files, + # 不计入已识别 total_files / 各状态数;否则会把未识别文件误报为已识别。 + facts = item.get('facts') if isinstance(item.get('facts'), dict) else {} + if facts.get('recognized') is False: + continue group = _batch_user_group(item) summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} filename = str(summary.get('filename') or '').strip().lower() @@ -3320,6 +3858,7 @@ def _conversation_processing_from_work_items( *, focused_task_no: str | None = None, recent_task_no: str | None = None, + submitted_files: int | None = None, ) -> dict[str, Any]: """ 由最终 work_items 构建完整详情投影。 @@ -3350,6 +3889,11 @@ def _conversation_processing_from_work_items( continue row = _conversation_task_row_from_work_item(item, focused_task_no=focused) all_rows.append(row) + + # [STEP 1] PDF 是状态主体,EML 仅提供邮件上下文。同一 EML 的不同状态附件 + # 必须分别进入各自状态组,绝不能因父卡优先级把处理中附件混入“已完成”。 + all_rows = _split_eml_rows_by_leaf_status(all_rows) + for row in all_rows: if recent and row['user_task_no'] == recent: row['recently_created'] = True def _sort_key(entry: dict[str, Any]) -> str: @@ -3395,6 +3939,9 @@ def _conversation_processing_from_work_items( 'summary': { 'total_tasks': total, 'total_files': total_files, + # 提交基主计数:来自冻结选择计划,物化前即 ≥1、单调递增。 + # 注意与 total_files 解耦——total_files 仍是「已识别数」,用作完成率分母。 + 'submitted_files': max(0, int(submitted_files or 0)), 'processing': len(status_groups['processing']), 'needs_action': len(status_groups['failed']) + len(status_groups['waiting_human']), 'completed': len(status_groups['completed']), @@ -3426,14 +3973,22 @@ def project_conversation_processing_summary( 首屏只需要后端已裁决的状态→EML→PDF树、统计和已授权动作标识;完整 work_items、Gate 执行上下文与旧四组镜像属于详情读模型,必须按需通过 work-item 接口读取。摘要仅批量读取正式 Gate 的最小状态列,绝不加载 - Attempt、Run JSON 或详情上下文,避免同一任务在首屏响应中重复传输三次。 + Attempt 或详情上下文,避免同一任务在首屏响应中重复传输三次。冻结选择计划 + 是唯一例外:仅用于保留用户已选、但仍未识别的附件诊断行。 + + ProcessExecution / ShippingProcessGate 必须按 OT.id(非 candidate_id)批量加载; + 否则 Gate 查空后叶子会退化,批次中心同时丢失五阶段入口与门禁主按钮。 + + 建单前五阶段权威与 order-review-queue 对齐:开放 Case 只认 Case.candidate_id + 绑定的可复核 Candidate;不得用「Case 存在」或「文档上另有未绑定 Candidate」 + 抬升 candidate_count / waiting_review→order_review。 """ del agent_id normalized = str(conversation_id or '').strip() if not normalized: raise ValidationError('conversation_id is required') - # 首屏严禁加载 Run JSON 快照、Plan/Unit 或 Gate Attempt;它们只属于详情读取。 + # 首屏严禁加载 Plan/Unit 或 Gate Attempt;它们只属于详情读取。 # 摘要只读取状态树和操作裁决所需列;正文、解析结果和重复检测 JSON # 属于详情读模型,禁止在首屏查询中触发 ORM 反序列化。 intakes = ShippingOrderIntake.query.options(load_only( @@ -3453,6 +4008,8 @@ def project_conversation_processing_summary( for document in ShippingOrderDocument.query.options(load_only( ShippingOrderDocument.id, ShippingOrderDocument.intake_id, + ShippingOrderDocument.attachment_key, + ShippingOrderDocument.content_hash, ShippingOrderDocument.filename, ShippingOrderDocument.parse_status, ShippingOrderDocument.classification, @@ -3463,6 +4020,16 @@ def project_conversation_processing_summary( ShippingOrderDocument.document_type != 'email_body', ).order_by(ShippingOrderDocument.intake_id.asc(), ShippingOrderDocument.id.asc()).all(): documents_by_intake.setdefault(int(document.intake_id), []).append(document) + # 冻结选择计划只服务 EML 附件的「已选但未物化」诊断行;直传 PDF 会话无附件选择, + # 不必为了空结果去读处理 Run 快照(摘要禁入 run 轮询路径)。 + has_eml_attachment_selection = any( + str(intake.source_type or '').strip().lower() == 'eml' + for intake in intakes + ) + planned_attachments_by_intake_no = ( + _frozen_attachment_plan_by_intake(intake_ids) + if has_eml_attachment_selection else {} + ) asset_ids = [int(item.asset_id) for item in intakes if item.asset_id] assets = { int(asset.id): asset @@ -3476,10 +4043,16 @@ def project_conversation_processing_summary( ShippingOrderCandidate.primary_document_id, ShippingOrderCandidate.order_extraction_run_id, ShippingOrderCandidate.po_number, + ShippingOrderCandidate.candidate_status, + ShippingOrderCandidate.is_current_version, )).filter( ShippingOrderCandidate.intake_id.in_(intake_ids) if intake_ids else False, ShippingOrderCandidate.is_current_version.is_(True), ).all() + candidate_by_id = { + int(candidate.id): candidate + for candidate in candidates + } candidate_by_document_id = { int(candidate.primary_document_id): candidate for candidate in candidates @@ -3491,12 +4064,12 @@ def project_conversation_processing_summary( for task in ShippingOrderTask.query.options(load_only( ShippingOrderTask.id, ShippingOrderTask.candidate_id, - ShippingOrderTask.shipping_notice_id, ShippingOrderTask.task_no, ShippingOrderTask.extraction_run_id, ShippingOrderTask.status, ShippingOrderTask.stage, ShippingOrderTask.error_code, + ShippingOrderTask.active_process_execution_id, ShippingOrderTask.updated_at, )).filter( ShippingOrderTask.user_id == int(user_id), @@ -3507,49 +4080,36 @@ def project_conversation_processing_summary( } # 正式 Notice / Execution / 当前 Gate 是建单后业务阶段的唯一真相。摘要以 # 固定三次批量查询取得最小列,不触碰 Gate Attempt、详情 JSON 或关系加载。 + # task_ids = OT 主键列表;后续 Notice 与 ProcessExecution 均按 OT.id 过滤。 task_ids = [int(task.id) for task in tasks_by_candidate_id.values()] - direct_notice_ids = { - int(task.shipping_notice_id) - for task in tasks_by_candidate_id.values() - if task.shipping_notice_id is not None - } notices_by_id: dict[int, ShippingNotice] = {} notices_by_order_task_id: dict[int, ShippingNotice] = {} if task_ids: for notice in ShippingNotice.query.options(load_only( ShippingNotice.id, ShippingNotice.order_task_id, - ShippingNotice.active_process_execution_id, )).filter(ShippingNotice.order_task_id.in_(task_ids)).all(): notices_by_id[int(notice.id)] = notice if notice.order_task_id is not None: notices_by_order_task_id[int(notice.order_task_id)] = notice - missing_direct_notice_ids = direct_notice_ids.difference(notices_by_id) - if missing_direct_notice_ids: - for notice in ShippingNotice.query.options(load_only( - ShippingNotice.id, - ShippingNotice.order_task_id, - ShippingNotice.active_process_execution_id, - )).filter(ShippingNotice.id.in_(missing_direct_notice_ids)).all(): - notices_by_id[int(notice.id)] = notice - if notice.order_task_id is not None: - notices_by_order_task_id.setdefault(int(notice.order_task_id), notice) - notice_ids = list(notices_by_id) + # task_ids 必须保持为 OT 主键:ProcessExecution.task_id 绑定 OT.id。 + # 禁止再写成 list(tasks_by_candidate_id)(那是 candidate_id),否则 Gate 整批查空, + # 批次进度中心会丢掉五阶段入口与门禁主按钮。 executions_by_id: dict[int, ShippingProcessExecution] = {} - latest_execution_by_notice_id: dict[int, ShippingProcessExecution] = {} - if notice_ids: + latest_execution_by_task_id: dict[int, ShippingProcessExecution] = {} + if task_ids: for execution in ShippingProcessExecution.query.options(load_only( ShippingProcessExecution.id, ShippingProcessExecution.task_id, ShippingProcessExecution.status, ShippingProcessExecution.current_gate_code, )).filter( - ShippingProcessExecution.task_id.in_(notice_ids), + ShippingProcessExecution.task_id.in_(task_ids), ShippingProcessExecution.status != 'superseded', ).order_by(ShippingProcessExecution.id.desc()).all(): executions_by_id[int(execution.id)] = execution if execution.task_id is not None: - latest_execution_by_notice_id.setdefault(int(execution.task_id), execution) + latest_execution_by_task_id.setdefault(int(execution.task_id), execution) current_gate_codes = { str(execution.current_gate_code).strip() for execution in executions_by_id.values() @@ -3573,17 +4133,10 @@ def project_conversation_processing_summary( """返回摘要所需的正式当前 Gate;只消费当前 Execution 的最小持久化列。""" if task is None: return None - notice = ( - notices_by_id.get(int(task.shipping_notice_id)) - if task.shipping_notice_id is not None - else notices_by_order_task_id.get(int(task.id)) - ) - if notice is None: - return None execution = ( - executions_by_id.get(int(notice.active_process_execution_id)) - if notice.active_process_execution_id is not None - else latest_execution_by_notice_id.get(int(notice.id)) + executions_by_id.get(int(task.active_process_execution_id)) + if task.active_process_execution_id is not None + else latest_execution_by_task_id.get(int(task.id)) ) if execution is None: return None @@ -3615,6 +4168,7 @@ def project_conversation_processing_summary( ShippingOrderReviewCase.status, ShippingOrderReviewCase.current_draft_id, ShippingOrderReviewCase.confirmed_task_id, + ShippingOrderReviewCase.candidate_id, )).filter( ShippingOrderReviewStream.document_id.in_(document_ids) if document_ids else False, ).all() @@ -3691,11 +4245,33 @@ def project_conversation_processing_summary( user_status, stage, reason = _status(document, task, case, current_gate) group = 'processing' if user_status == 'running' else user_status task_no = str(task.task_no).strip() if task is not None else None - candidate = candidate_by_document_id.get(int(document.id)) - candidate_po = str(getattr(candidate, 'po_number', None) or '').strip() if candidate is not None else '' - # 摘要只信任 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。 - # 候选存在不等于关键字段已完成解析;没有 PO 时仍停留在接收解析阶段。 - if not candidate_po and stage in {'waiting_review', 'order_review'}: + from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate + + # [AUTHORITY] 与 order-review-queue / EML 详情叶子一致: + # Case 已物化时只认 Case.candidate_id 绑定的可复核 Candidate; + # 文档上另有未绑定 Candidate(即便带 PO)不能抬升到订单复核。 + # Case 尚未物化时,才回退到文档当前 Candidate,保留建单前安全入口。 + document_candidate = candidate_by_document_id.get(int(document.id)) + case_candidate = ( + candidate_by_id.get(int(case.candidate_id)) + if case is not None and getattr(case, 'candidate_id', None) is not None + else None + ) + candidate = case_candidate if case is not None else document_candidate + has_current_candidate = bool( + is_current_reviewable_candidate(candidate) + and int(getattr(candidate, 'primary_document_id', 0) or 0) == int(document.id) + ) + candidate_po = ( + str(getattr(candidate, 'po_number', None) or '').strip() + if has_current_candidate else '' + ) + # 摘要只信任可复核 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。 + # 空/未绑定 Candidate 的开放 Case 必须降回接收解析,与工作台队列同判词。 + if case is not None and case.confirmed_task_id is None and not has_current_candidate: + if stage in {'waiting_review', 'order_review'}: + stage = 'candidate_creating' + elif not candidate_po and stage in {'waiting_review', 'order_review'}: stage = 'candidate_creating' case_status = str(getattr(case, 'status', None) or '').strip().lower() terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} @@ -3720,8 +4296,8 @@ def project_conversation_processing_summary( } intake_parse_authorized = True elif case is not None and not terminal_case: - if candidate is not None: - # 当前 Candidate 已生成后,Case 进入订单复核;仅用已批量读取的 + if has_current_candidate: + # Case 已绑定可复核 Candidate 后进入订单复核;仅用已批量读取的 # current_draft_id 恢复权威业务动作,避免摘要路径逐文件加载 Case 详情。 available_actions = ['edit_draft' if case.current_draft_id else 'create_draft'] primary_action = project_case_primary_action( @@ -3737,7 +4313,8 @@ def project_conversation_processing_summary( primary_action = _intake_parse_case_primary_action( reparse_authorized=True, ) - elif task is not None or candidate_by_document_id.get(int(document.id)) is not None: + intake_parse_authorized = True + elif task is not None or has_current_candidate: # Candidate 已形成但 Case 尚未物化时,仍保留进入订单生命周期的安全入口; # 详情页会显示当前事实并在服务端决定是否可继续编辑。 available_actions = ['open_order_review'] @@ -3780,9 +4357,16 @@ def project_conversation_processing_summary( 'source_summary': { 'document_id': int(document.id), 'filename': str(document.filename or '').strip() or None, + # 与详情/工作项叶子保持一致:携带 content_hash / attachment_key, + # 供 _append_unrecognized_plan_attachments 按附件身份去重,避免把 + # 已物化附件再补成一份 pending(recognized=false)重复行。 + 'content_hash': str(document.content_hash or '').strip().lower() or None, + 'attachment_key': str(document.attachment_key or '').strip() or None, 'document_count': 1, 'parsed_document_count': int(str(document.parse_status or '').strip().lower() == 'parsed'), - 'candidate_count': 1 if candidate is not None or task is not None or case is not None else 0, + # 禁止用 Case 存在抬升 candidate_count;否则 has_candidate_context 会 + # 错误开放订单复核入口,与工作台队列判词分叉。 + 'candidate_count': 1 if has_current_candidate or task is not None else 0, 'po_number': candidate_po or None, }, 'current_gate': current_gate, @@ -3793,6 +4377,26 @@ def project_conversation_processing_summary( } return _with_processing_ui_state(leaf) + def _is_selected_attachment( + intake: ShippingOrderIntake, + document: ShippingOrderDocument, + ) -> bool: + """判断已物化附件是否属于用户冻结时明确选择的 EML 文件。""" + document_attachment_key = str(document.attachment_key or '').strip().lower() + document_content_hash = str(document.content_hash or '').strip().lower() + for item in planned_attachments_by_intake_no.get(str(intake.intake_no), []): + if item.get('selected') is not True: + continue + if document_attachment_key and document_attachment_key == str( + item.get('attachment_key') or '' + ).strip().lower(): + return True + if document_content_hash and document_content_hash == str( + item.get('content_hash') or '' + ).strip().lower(): + return True + return False + groups: dict[str, list[dict[str, Any]]] = {key: [] for key in ( 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', )} @@ -3805,13 +4409,33 @@ def project_conversation_processing_summary( task = tasks_by_candidate_id.get(int(candidate.id)) if candidate is not None else None case = current_case_by_document_id.get(int(document.id)) # 邮件的 unknown/supporting 附件若没有 Candidate、Review Case 或 OT, - # 只是原始邮件的支撑材料,不是可进入五阶段的业务文件。 + # 仅在其为用户已选文件时保留只读诊断行;未选支撑材料继续隐藏。 classification = str(document.classification or '').strip().lower() if classification in {'unknown', 'supporting'} and candidate is None and case is None and task is None: + if not _is_selected_attachment(intake, document): + continue + leaf = _leaf(document, task, case) + leaf.update({ + 'current_gate': None, + 'blocking_reason': None, + 'primary_action': None, + 'available_actions': [], + 'intake_parse_authorized': False, + 'facts': {'recognized': False, 'plan_state': 'selected_pending'}, + }) + leaves.append(_with_processing_ui_state(leaf)) continue if task is not None: tasks.append(task) leaves.append(_leaf(document, task, case)) + # 冻结选择计划中已选、但尚未物化 Document 的附件,也作为 pending + # (recognized=false)叶子补齐,与详情/工作项路径共用同一契约;否则空窗期 + # 首屏只剩 submitted/total 计数、没有任何文件名可列(前端只能转圈)。 + leaves = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=leaves, + planned_by_intake_no=planned_attachments_by_intake_no, + ) if not leaves: continue states = [str(leaf['user_status']) for leaf in leaves] @@ -3825,9 +4449,13 @@ def project_conversation_processing_summary( groups[group].append({ 'user_task_no': task_no, 'title': title, + # [STEP 1] 保留 Intake 来源,供后续按叶子状态拆分 EML。缺失该字段时 + # _split_eml_rows_by_leaf_status 会把邮件当作普通单文件行,父级状态会 + # 覆盖其中仍在处理的 PDF。 + 'source_type': source_type, 'display_kind': 'multi_document_task' if len(leaves) > 1 else 'single_document_task', 'group': 'needs_action' if group in {'failed', 'waiting_human'} else ('history' if group in {'cancelled', 'archived'} else group), - 'status_label': 'pending_review' if group == 'waiting_human' else ('processing' if group == 'processing' else group), + 'status_label': 'waiting_human' if group == 'waiting_human' else ('processing' if group == 'processing' else group), 'file_count': len(leaves), 'run_no': next((str(leaf.get('run_no') or '').strip() for leaf in leaves if leaf.get('run_no')), None), 'case_no': next((str(leaf.get('case_no') or '').strip() for leaf in leaves if leaf.get('case_no')), None), @@ -3861,6 +4489,15 @@ def project_conversation_processing_summary( # [AUTHORITY] 首屏摘要与详情投影一样,以同一批文件叶子的互斥用户分组 # 生成总数和四个状态数。此前这里只返回 total_files,前端却按 *_files # 渲染批次概览,造成“总文件有数、四个状态全为 0”的合同断裂。 + split_rows = _split_eml_rows_by_leaf_status([ + row for rows in groups.values() for row in rows + ]) + groups = { + group: [row for row in split_rows if row.get('user_group') == group] + for group in groups + } + # EML 被按叶子状态拆分后才计算文件摘要;计数仍按 document_id 去重,不会因 + # 同一封邮件跨状态展示而重复增加。 summary_file_counts = _batch_file_counts([ row for rows in groups.values() @@ -3871,6 +4508,11 @@ def project_conversation_processing_summary( 'summary': { 'total_tasks': sum(len(rows) for rows in groups.values()), **summary_file_counts, + # 提交基主计数:与 total_files(已识别数)解耦,物化前即 ≥1、单调递增。 + 'submitted_files': _conversation_submitted_file_count( + user_id=int(user_id), + conversation_id=normalized, + ), 'processing': len(groups['processing']), 'needs_action': len(groups['failed']) + len(groups['waiting_human']), 'completed': len(groups['completed']), @@ -4081,9 +4723,8 @@ def project_conversation_processing_items( stage_label_key = None invalidated_from_stage = None excel_ready = False - if getattr(order_task, 'shipping_notice_id', None): - nid = int(order_task.shipping_notice_id) - notice_min = db.session.get(ShippingNotice, nid) + notice_min = _latest_notice_for_order_task(order_task) + if notice_min is not None: if notice_min is not None: from app.services.shipping_notice.order_review_workbench_projection import ( project_stage_for_task, @@ -4111,10 +4752,7 @@ def project_conversation_processing_items( stage_label_key = 'waiting_system_start' authorized_actions_min: list[str] = [] notice_no_min = _notice_no_for_order_task(order_task) - has_formal_ot_min = bool( - getattr(order_task, 'shipping_notice_id', None) is not None - and notice_no_min is not None - ) + has_formal_ot_min = bool(notice_no_min is not None) payload_min = reconcile_processing_projection_facts( { 'work_item_type': 'order_task', @@ -4222,6 +4860,10 @@ def project_conversation_processing_items( work_items, focused_task_no=focused_override, recent_task_no=recent_override, + submitted_files=_conversation_submitted_file_count( + user_id=int(user_id), + conversation_id=normalized, + ), ) # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 if recent_decision is not None: @@ -4317,4 +4959,4 @@ def get_shipping_processing_work_item( projected = _project_order_task_work_item(run, order_task=order_task) if projected is None: raise NotFoundError('Order task work item not found') - return projected + return _with_processing_ui_state(projected) diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index 6e146227..1578e8e0 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -14,10 +14,7 @@ import logging from flask import current_app from app import db -from app.models import ( - ShippingNotice, - ShippingTaskInventoryRpaAttempt, -) +from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt _LOGGER = logging.getLogger(__name__) @@ -82,8 +79,8 @@ def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int: total = 0 for task in ( - ShippingNotice.query - .filter(ShippingNotice.task_no.in_(task_nos)) + ShippingOrderTask.query + .filter(ShippingOrderTask.task_no.in_(task_nos)) .all() ): try: diff --git a/backend/app/services/shipping_notice/standard_field_registry.py b/backend/app/services/shipping_notice/standard_field_registry.py index cc0abaed..f6359f64 100644 --- a/backend/app/services/shipping_notice/standard_field_registry.py +++ b/backend/app/services/shipping_notice/standard_field_registry.py @@ -94,7 +94,8 @@ def _spec( ) -# [STEP 1] 锁定的 58 项标准目录。Reservation 可同时位于订单头和订单行, +# [STEP 1] 锁定的 58 项标准目录。line_no 是系统生成且只读的订单项次, +# 不参与 Schema 派生规则配置;Reservation 可同时位于订单头和订单行, # 由行级值覆盖订单头值;所有标准字段均可按 Schema 配置抽取规则。 _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = ( _spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'), @@ -121,12 +122,8 @@ _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = ( _spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'), _spec('order_remark', 'header', 'string', '订单备注', '订单头备注'), _spec('reservation_id', 'header', 'string', '预约单号', '可选的订单级库存占用/预约单标识;明细可覆盖'), - _spec( - 'line_no', 'line', 'string', '内部项次', - '内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;' - '仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关', - ), _spec('reservation_id', 'line', 'string', '预约单号', '可选的行级库存占用/预约单标识;优先于订单头', fulfillment_role='reservation_identity'), + _spec('line_no', 'line', 'integer', '内部项次', '订单明细的系统项次;按订单从 1 开始生成,创建后不可编辑或覆盖'), _spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'), _spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'), _spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'), diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 8b4f550e..ea85d0dc 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -1,18 +1,16 @@ """ services/shipping_notice/state_machine.py -用途:发货通知检查点(checkpoint)与内部流程状态映射,负责任务 DB 字段与流程事实映射。 -依赖:models.ShippingNotice、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。 -逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind; - resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台, - Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。 - -扩展说明(开发者): -- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt` -- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete - (导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记) -- 用户动作的定义、授权与审计统一由 process_gate_contract / Gate Attempt 负责; - checkpoint 不得派生、下发或执行用户按钮。 +用途:发货通知任务 DB 字段迁移(TaskTransition)与位置/用户模式解析(Gate + review 回退)。 +依赖:models.ShippingNotice/ShippingOrderTask、constants(RS_*/PH_*)、 + process_gate_contract.derive_*(Gate-first)。 +逻辑:tools/workspace 经 apply_task_transition 写库;resolve_task_ui_state 仅: + (1) 有活动 Execution 时用 Gate derive_position / derive_user_mode; + (2) 否则仅凭 review_status 做薄回退。 + 禁止领域标量/OT stage 级联裁决;无 checkpoint API 别名;非独立 CP 状态机。 + POSITION_USER_MODE 仅为可选位置→UserMode 查找表,不是状态机。 + build_task_ui_state 可传入已查 Gate 摘要,经 _ui_state_from_process_gate 派生,避免二次查库。 + 履约写操作入口为任务处理工作台;Chat 仅通知与跳转。 """ from __future__ import annotations @@ -21,27 +19,8 @@ from dataclasses import dataclass from enum import StrEnum from typing import Any -from app import db -from app.models import ShippingOrderExtraction, ShippingOrderLine, ShippingNotice +from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_EXPORT_GENERATED, - CP_INVENTORY_PENDING, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_CUSTOMER_REVIEW, - CP_PARSE_REVIEW, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_COMPLETED, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, @@ -52,36 +31,31 @@ from app.services.shipping_notice.constants import ( PH_SHORTAGE, PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_PENDING, - PH_UPLOAD_RESULT_UNKNOWN, - RS_CONFIRMED, RS_PARSE_REVIEW, RS_REJECTED, RS_RSV_REQ, RS_SHORTAGE_REVIEW, + RS_CONFIRMED, ) -def _task_has_dynamic_order_lines(task: ShippingNotice) -> bool: - """判断当前已接受 Extraction 是否有订单行,用于在冻结前显示唯一的冻结入口。""" - extraction_id = task.current_order_extraction_id - if not extraction_id: - return False - extraction = db.session.get(ShippingOrderExtraction, extraction_id) - if extraction is None or extraction.status != "accepted": - return False - return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None +def _workflow_owner(task: ShippingNotice): + """Notice 查询流程状态时统一回到其 OT;Notice 不再作为流程状态事实源。""" + from app import db + + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + return db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else task # --------------------------------------------------------------------------- -# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射) +# 用户模式枚举(与 derive_user_mode 值域对齐;不是 CheckPoint 状态机) # --------------------------------------------------------------------------- -class CheckpointKind(StrEnum): - """STP 检查点分类:自动可继续 / 必须人工 / 待人工上传登记 / 完成。 - - CP_EXPORT_READY/GENERATED 映射为 WAIT_MANUAL_UPLOAD(Excel 后须登记凭据,非终态)。 - """ +class UserMode(StrEnum): + """用户处置粗分类:auto_continue / must_human / wait_manual_upload / complete。""" AUTO_CONTINUE = "auto_continue" MUST_HUMAN = "must_human" @@ -89,188 +63,179 @@ class CheckpointKind(StrEnum): COMPLETE = "complete" -# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue) -CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = { - CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN, - CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN, - CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN, - CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE, - # 库存源由规则自动裁决;未稳定只表示内部重算/治理等待,不能形成用户确认停点。 - CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.AUTO_CONTINUE, - CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE, - CP_RSV_REQ: CheckpointKind.MUST_HUMAN, - RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN, - CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN, - CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN, - CP_WAITING_UPLOAD: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE, - CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE, - CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_REJECTED: CheckpointKind.COMPLETE, - CP_UPLOADED: CheckpointKind.COMPLETE, - CP_COMPLETED: CheckpointKind.COMPLETE, +# 位置标签 → 用户模式(无 Gate 时的可选查找;键为 derive_position 字面量,非状态机) +POSITION_USER_MODE: dict[str, UserMode] = { + 'parse_review': UserMode.MUST_HUMAN, + 'customer_review': UserMode.MUST_HUMAN, + 'upload_req': UserMode.MUST_HUMAN, + 'inventory_pending': UserMode.AUTO_CONTINUE, + 'inventory_source_review': UserMode.AUTO_CONTINUE, + 'order_freeze': UserMode.AUTO_CONTINUE, + 'rsv_req': UserMode.MUST_HUMAN, + 'shortage_review': UserMode.MUST_HUMAN, + 'notice_text_extraction_failed': UserMode.MUST_HUMAN, + 'quality_issue': UserMode.MUST_HUMAN, + 'upload_failed': UserMode.MUST_HUMAN, + 'waiting_upload': UserMode.WAIT_MANUAL_UPLOAD, + 'upload_result_unknown': UserMode.WAIT_MANUAL_UPLOAD, + 'ready_to_match': UserMode.AUTO_CONTINUE, + 'ready_to_export': UserMode.AUTO_CONTINUE, + 'export_ready': UserMode.WAIT_MANUAL_UPLOAD, + 'export_generated': UserMode.WAIT_MANUAL_UPLOAD, + 'rejected': UserMode.COMPLETE, + 'uploaded': UserMode.COMPLETE, + 'completed': UserMode.COMPLETE, } -ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_KIND_REGISTRY.keys()) - @dataclass(frozen=True) class TaskUiState: - """统一任务流程状态:checkpoint + STP kind,不包含用户动作。""" + """位置标签 + 用户模式派生视图(非独立状态机事实)。""" - checkpoint: str | None - checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE + position: str | None + user_mode: UserMode = UserMode.AUTO_CONTINUE -def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind: +def user_mode_for_position(position: str | None) -> UserMode: """ - 按 checkpoint id 解析 STP 检查点分类。 + 按位置标签解析用户模式(查找表,非状态机)。 - 核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。 + 核心逻辑:查 POSITION_USER_MODE;无位置视为 auto_continue;未知位置默认 must_human。 + + Args: + position: derive_position / 位置字符串;可为 None。 + + Returns: + UserMode 枚举值。 """ - if not checkpoint: - return CheckpointKind.AUTO_CONTINUE - return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN) + if not position: + return UserMode.AUTO_CONTINUE + return POSITION_USER_MODE.get(str(position).strip(), UserMode.MUST_HUMAN) -def _task_ui_state(checkpoint: str | None) -> TaskUiState: - """构造只含内部流程事实的 TaskUiState。""" +def _task_ui_state(position: str | None) -> TaskUiState: + """构造位置 + 用户模式派生视图。""" return TaskUiState( - checkpoint=checkpoint, - checkpoint_kind=checkpoint_kind_for(checkpoint), + position=position, + user_mode=user_mode_for_position(position), ) -def resolve_task_ui_state_from_fields( - *, - review_status: str | None, - pending_human_reason: str | None, - customer_resolution_status: str | None, - order_snapshot_id: int | None, - inventory_lines_json: Any, - match_status: str | None, - export_file_path: str | None, - has_dynamic_order_lines: bool, - upload_req_options: list[str] | None = None, - upload_req_task: ShippingNotice | None = None, -) -> TaskUiState: +def _ui_state_from_process_gate( + task: ShippingNotice, + gate: dict[str, Any] | None, +) -> TaskUiState | None: """ - 由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。 + 由已查得的 Gate 用户摘要派生 position/user_mode。 - 核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算, - 供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。 - upload_req_options / upload_req_task 是已废弃的兼容入参;checkpoint 不再解析用户动作。 + 核心逻辑:与 ``_gate_task_ui_state`` 同源;``build_task_ui_state`` 复用同一次 + Gate 查询结果,禁止再调 ``resolve_task_ui_state`` 二次查 Execution。 + + Args: + task: ShippingNotice 或 ShippingOrderTask(取 review_status)。 + gate: ``_process_gate_user_summary_for_task`` 返回值;无 Gate 时为 None。 + + Returns: + 可派生时返回 TaskUiState;否则 None(调用方走 review_status 薄回退)。 """ + from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode - del upload_req_options + if not isinstance(gate, dict) or not gate.get('current_gate_code'): + return None + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = str(gate_view.get('status') or '').strip().lower() + summary_status = str(gate.get('status') or '').strip().lower() + if summary_status in {'completed', 'done'}: + user_status = 'completed' + elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked': + user_status = 'waiting_human' + elif status == 'failed_terminal' or summary_status == 'failed': + user_status = 'failed' + else: + user_status = 'running' + gate_code = gate.get('current_gate_code') or gate_view.get('gate_code') + mode = derive_user_mode( + user_status=user_status, + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + lifecycle_stage=gate.get('lifecycle_stage'), + ) + pos = derive_position( + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + ) + try: + user_mode = UserMode(str(mode)) + except ValueError: + user_mode = user_mode_for_position(pos) + return TaskUiState(position=pos, user_mode=user_mode) - upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower() - has_export = bool(str(export_file_path or "").strip()) - # [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。 - if upload_status in {"uploaded", "succeeded", "success"}: - return _task_ui_state(CP_UPLOADED) - if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}: - return _task_ui_state(CP_COMPLETED) +def _review_status_fallback_ui_state(task: ShippingNotice) -> TaskUiState: + """ + 无活动 Gate 时仅凭 review_status 薄回退派生 position/user_mode。 - if review_status == "rejected": - return _task_ui_state(CP_REJECTED) + 核心逻辑:与 ``resolve_task_ui_state`` 无 Gate 分支同源。 + """ + from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode - # [STEP 2] 先完成订单解析复核,再暴露客户确认节点。 - reason = pending_human_reason - if reason == PH_RSV_REQ or review_status == RS_RSV_REQ: - return _task_ui_state(CP_RSV_REQ) - if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW: - return _task_ui_state(CP_PARSE_REVIEW) - if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: - return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED) + owner = _workflow_owner(task) + review_status = getattr(owner, 'review_status', None) + pos = derive_position(gate_code=None, review_status=review_status) + mode = derive_user_mode( + user_status=None, + gate_code=None, + review_status=review_status, + lifecycle_stage=None, + ) + try: + user_mode = UserMode(str(mode)) + except ValueError: + user_mode = user_mode_for_position(pos) + return TaskUiState(position=pos, user_mode=user_mode) - if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}: - return _task_ui_state(CP_CUSTOMER_REVIEW) - # [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。 - if not order_snapshot_id and has_dynamic_order_lines: - return _task_ui_state(CP_ORDER_FREEZE) +def _gate_task_ui_state(task: ShippingNotice) -> TaskUiState | None: + """ + 有活动 Execution 时用 Gate derive_*;否则 None(调用方走 review_status 薄回退)。 - # Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status, - # 也不能退回“处理中”或丢失下载/登记动作。 - if has_export: - return _task_ui_state(CP_EXPORT_READY) + 懒导入 ui_state,避免与 resolve 循环依赖。 + """ + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task - # [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。 - if reason == PH_RPA_EXHAUSTED: - return _task_ui_state(CP_UPLOAD_REQ) - - if ( - inventory_lines_json - and not review_status - and not pending_human_reason - and not match_status - ): - return _task_ui_state(CP_READY_MATCH) - - if ( - not inventory_lines_json - and not review_status - and not pending_human_reason - and has_dynamic_order_lines - ): - return _task_ui_state(CP_INVENTORY_PENDING) - - # [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。 - if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}: - if has_export: - return _task_ui_state(CP_EXPORT_READY) - return _task_ui_state(CP_READY_EXPORT) - - # [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。 - if reason == PH_INV_UNAVAIL: - return _task_ui_state(CP_UPLOAD_REQ) - if reason == PH_INVENTORY_SOURCE_UNRESOLVED: - return _task_ui_state(CP_INVENTORY_SOURCE_REVIEW) - if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW: - return _task_ui_state(RS_SHORTAGE_REVIEW) - if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed": - return _task_ui_state(CP_UPLOAD_FAILED) - if reason == PH_UPLOAD_RESULT_UNKNOWN: - return _task_ui_state(CP_UPLOAD_RESULT_UNKNOWN) - if reason == PH_RPA_PENDING: - return _task_ui_state(CP_UPLOAD_REQ) - if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}: - return _task_ui_state(CP_WAITING_UPLOAD) - return _task_ui_state(None) + return _ui_state_from_process_gate(task, _process_gate_user_summary_for_task(task)) def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState: """ - 将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind。 + 解析位置 + 用户模式:优先 Gate derive_*,否则仅凭 review_status 薄回退。 - 核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库; - 履约写操作由 Gate 投影生成 ui_state.actions;Chat 不再作为写入口。 + 核心逻辑:无活动 Execution 时调用 derive_position(gate_code=None) / + derive_user_mode(仅 review_status);禁止 match_status / export_file_path / + pending_human / OT stage 级联充当状态机。 + + Args: + task: ShippingNotice 或 ShippingOrderTask。 + + Returns: + TaskUiState(position + user_mode)。 """ - return resolve_task_ui_state_from_fields( - review_status=task.review_status, - pending_human_reason=task.pending_human_reason, - customer_resolution_status=task.customer_resolution_status, - order_snapshot_id=task.order_snapshot_id, - inventory_lines_json=task.inventory_lines_json, - match_status=task.match_status, - export_file_path=task.export_file_path, - has_dynamic_order_lines=_task_has_dynamic_order_lines(task), - upload_req_task=task, - ) + gated = _gate_task_ui_state(task) + if gated is not None: + return gated + return _review_status_fallback_ui_state(task) -def checkpoint_for_task(task: ShippingNotice) -> str | None: - """从 ShippingNotice DB 字段解析当前 checkpoint id。""" - return resolve_task_ui_state(task).checkpoint +def position_for_task(task: ShippingNotice) -> str | None: + """返回当前派生位置标签。""" + return resolve_task_ui_state(task).position def validate_registry() -> list[str]: - """校验每个内部 checkpoint 都有确定的流程分类;测试用。""" - return [] if ALL_CHECKPOINT_IDS == frozenset(CHECKPOINT_KIND_REGISTRY) else ["checkpoint registry mismatch"] + """校验位置→用户模式查找表非空;测试用。""" + return [] if POSITION_USER_MODE else ["POSITION_USER_MODE is empty"] # --------------------------------------------------------------------------- @@ -406,12 +371,15 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N transition: TaskTransition 枚举值。 """ spec = TASK_TRANSITIONS[transition] - if spec.review_status is not _UNSET: - task.review_status = spec.review_status - if spec.pending_human_reason is not _UNSET: - task.pending_human_reason = spec.pending_human_reason - if spec.clear_error_message: - task.error_message = None + owner = _workflow_owner(task) + # 流程状态事实只写入 OT。正式 Notice 仅作为履约实体关联入口, + # 不再动态挂载 review/pending/error 等已删除的历史工作流字段。 + if isinstance(owner, ShippingOrderTask) and spec.review_status is not _UNSET: + owner.review_status = spec.review_status + if isinstance(owner, ShippingOrderTask) and spec.pending_human_reason is not _UNSET: + owner.pending_human_reason = spec.pending_human_reason + if isinstance(owner, ShippingOrderTask) and spec.clear_error_message: + owner.error_message = None # [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。 try: diff --git a/backend/app/services/shipping_notice/stp_inventory_freeze.py b/backend/app/services/shipping_notice/stp_inventory_freeze.py index 96ece045..5458af24 100644 --- a/backend/app/services/shipping_notice/stp_inventory_freeze.py +++ b/backend/app/services/shipping_notice/stp_inventory_freeze.py @@ -1,7 +1,7 @@ """ services/shipping_notice/stp_inventory_freeze.py -用途:建单时将资格服务的行级库存源候选冻结到 Task,供后续库存准备消费。 +用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。 依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。 逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved; 多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review); @@ -62,7 +62,7 @@ def freeze_stp_inventory_candidates_on_task( line_projections: list[dict[str, Any]] | None, ) -> InventorySourceAdjudication: """ - 将建单前候选冻结到任务字段与 step_payload。 + 将建单前候选冻结到 CandidateSet;任务仅保留 CandidateSet 指针。 核心逻辑: - 恰好 1 个有效启用候选 → status=resolved(任务级摘要); @@ -87,7 +87,7 @@ def freeze_stp_inventory_candidates_on_task( 'freeze': 'stp_build', 'line_projections': [ { - 'line_key': item.get('line_key'), + 'draft_line_id': item.get('draft_line_id'), 'line_index': item.get('line_index'), 'candidate_inventory_source_codes': list(item.get('candidate_inventory_source_codes') or []), 'selection_mode': item.get('selection_mode'), @@ -148,36 +148,7 @@ def freeze_stp_inventory_candidates_on_task( line_projections=line_projections, ) - payload = dict(task.step_payload_json or {}) - payload['line_inventory_candidates'] = { - 'source_codes': valid_codes, - 'lines': evidence[0]['line_projections'], - 'frozen_at': 'build', - 'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None), - } - task.step_payload_json = payload - apply_inventory_source_adjudication(task, adjudication) - # 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。 - if adjudication.status == 'candidates_frozen': - payload = dict(task.step_payload_json or {}) - payload['line_inventory_candidates'] = { - 'source_codes': valid_codes, - 'lines': evidence[0]['line_projections'], - 'frozen_at': 'build', - 'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None), - } - resolution = dict(payload.get('inventory_source_resolution') or {}) - resolution['status'] = 'candidates_frozen' - resolution['candidates'] = candidates - resolution['reason'] = adjudication.reason - payload['inventory_source_resolution'] = resolution - task.step_payload_json = payload - task.inventory_source_status = 'candidates_frozen' - task.inventory_source_method = 'stp_build_freeze' - task.inventory_source_config_version = config_version - task.inventory_routing_fingerprint = fingerprint - # [STEP] 仅对真实 ORM 任务写审计事件(单测 SimpleNamespace 跳过)。 if isinstance(task, ShippingNotice): from app.services.shipping_notice.tool_common import log_task_event @@ -227,7 +198,4 @@ def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]: for source in get_active_candidate_sources(task) if str(source.source_code or '').strip() ] - if codes: - return list(dict.fromkeys(codes)) - single = str(task.inventory_source_code or '').strip().upper() - return [single] if single else [] + return list(dict.fromkeys(codes)) diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index 2ee233db..3132401d 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -4,9 +4,10 @@ services/shipping_notice/stp_line_inventory_match.py 用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。 依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、 inventory_source_rules、ShippingOrderSnapshot。 -逻辑:ensure_inventory 合并候选快照行;match 仅在冻结候选集内检索;多文件命中为冲突; - 唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记); - 人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 +逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 + __source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结 + resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后 + forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 """ from __future__ import annotations @@ -123,7 +124,7 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: Returns: status / lines / missing_source_codes / loaded_source_codes / evidence。 """ - from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot current_set = get_active_candidate_set(task) @@ -182,12 +183,10 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: 'required': in_required, }) continue - lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)] - if not lines: - try: - lines, _meta = parse_inventory_snapshot_file(snapshot) - except (OSError, ValueError): - lines = [] + try: + lines, _meta = read_inventory_file_lines(snapshot) + except (OSError, ValueError): + lines = [] if not lines: if in_required: missing.append(code) @@ -213,18 +212,6 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: 'required': in_required, }) - payload = dict(task.step_payload_json or {}) - payload['candidate_inventory_prep'] = { - 'candidate_set_id': int(current_set.id), - 'candidate_set_version': int(current_set.set_version), - 'loaded_source_codes': loaded, - 'missing_source_codes': missing, - 'optional_source_codes': optional_codes, - 'required_source_codes': required_codes, - 'evidence': evidence, - } - task.step_payload_json = payload - if not merged and required_codes: return { 'status': 'missing_files', @@ -286,23 +273,25 @@ def match_order_lines_across_candidates( """ 跨候选库存行按有效 Reservation + Part Number + Unit 匹配。 + 核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定, + 库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。 + Args: order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。 - inventory_lines: 已打 ``__source_code`` 的库存行。 + inventory_lines: 库存行;``__source_code`` 可选(多源合并时用于冲突裁决)。 header_reservation_id: 头级 Reservation,用于行级回退。 Returns: match_status、line_results、shortage_json、resolutions。 """ # [STEP 1] 按 (reservation, part, unit, source) 聚合可用量与样例行。 + # 无 __source_code 时 source='':表示“当前已载入 Excel 内的行”,不得因缺标签跳过。 buckets: dict[tuple[str, str, str, str], dict[str, Any]] = {} for row in inventory_lines: key = _inventory_row_key(row) if key is None: continue source = str(row.get('__source_code') or '').strip().upper() - if not source: - continue bucket_key = (key[0], key[1], key[2], source) bucket = buckets.get(bucket_key) if bucket is None: @@ -350,10 +339,11 @@ def match_order_lines_across_candidates( ] if effective and part else [] # 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。 # 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。 + # 无源标签的库存行视为“当前 Excel 已选源”,不因候选源列表再剔除。 source_hits = [ item for item in all_source_hits if ( - item['source_code'] in allowed_source_codes + (not item['source_code'] or item['source_code'] in allowed_source_codes) if has_candidate_scope else True ) @@ -426,6 +416,10 @@ def match_order_lines_across_candidates( else: hit = source_hits[0] available = hit['available_qty'] + # 库存行无源标签时,回退到该行唯一候选源(选源阶段已确定)。 + resolved_source = hit['source_code'] or ( + allowed_source_codes[0] if len(allowed_source_codes) == 1 else '' + ) if available >= required and required > 0: disposition = 'ok' sample = hit['sample_row'] @@ -439,13 +433,13 @@ def match_order_lines_across_candidates( 'shortage_qty': 0.0, 'line_status': 'ok', 'disposition': disposition, - 'resolved_inventory_source_code': hit['source_code'], + 'resolved_inventory_source_code': resolved_source, 'inventory_file_no': sample.get('__inventory_file_no'), 'inventory_row_ref': { 'reservation_id': effective, 'part_number': part, 'unit': unit or None, - 'source_code': hit['source_code'], + 'source_code': resolved_source, }, } has_ok = True @@ -461,7 +455,7 @@ def match_order_lines_across_candidates( 'shortage_qty': float(max(required - available, Decimal('0'))), 'line_status': 'partial' if available > 0 else 'shortage', 'disposition': disposition, - 'resolved_inventory_source_code': hit['source_code'], + 'resolved_inventory_source_code': resolved_source, } has_block = True has_partial = available > 0 @@ -469,7 +463,7 @@ def match_order_lines_across_candidates( line_results.append(result) resolutions.append({ 'line_index': index, - 'line_key': line.get('line_key'), + 'line_no': int(line.get('line_no') or index + 1), 'disposition': result['disposition'], 'effective_reservation_id': effective, 'part_number': part or None, @@ -503,80 +497,43 @@ def match_order_lines_across_candidates( def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None: """ - 将跨候选匹配结果写入任务并投影汇总库存源。 - - 核心逻辑:全部 ok 时投影 inventory_source_code(多源取首个作 Excel 模板绑定, - 行级 resolved 仍保留在 line_inventory_resolutions);不再因多源成功命中阻断制单。 + 将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。 """ - resolutions = list(match_payload.get('resolutions') or []) - payload = dict(task.step_payload_json or {}) - payload['line_inventory_resolutions'] = resolutions - # 历史阻断标记:全成功多源场景不再阻断,清理以免误伤自动链。 - payload.pop('multi_source_excel_block', None) - task.step_payload_json = payload - task.match_status = str(match_payload.get('match_status') or '') - task.line_results_json = list(match_payload.get('line_results') or []) - task.shortage_json = dict(match_payload.get('shortage_json') or {}) + del task, match_payload - ok_sources = sorted({ - str(item.get('resolved_inventory_source_code') or '').strip().upper() - for item in resolutions - if item.get('disposition') == 'ok' and item.get('resolved_inventory_source_code') - }) - if match_payload.get('match_status') == 'fulfillable' and ok_sources: - primary = ok_sources[0] - source = get_database_inventory_source(primary) - if source is not None: - task.inventory_source_code = primary - task.inventory_connector_type = str(source.get('connector_type') or '') or None - if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed': - task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None - task.inventory_source_status = 'resolved' - task.inventory_source_method = ( - 'stp_line_match' if len(ok_sources) == 1 else 'stp_line_match_multi' - ) - task.inventory_source_config_version = inventory_sources_runtime_version() - task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) - if len(ok_sources) > 1: - payload['resolved_ok_source_codes'] = ok_sources - payload['excel_binding_source_code'] = primary - task.step_payload_json = payload def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]: """ 多文件冲突时可人工指定的库存源编码列表。 - 核心逻辑:仅汇总 multi_file_conflict 行的 candidate_hit_source_codes; - 全成功多源制单场景不再需要人工恢复。 + 核心逻辑:仅汇总 source_conflict 行的候选源,优先取行匹配事实 detail_json 内的 + candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用 + 库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。 """ - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + from app.services.shipping_notice.inventory_source_repository import ( + list_database_inventory_sources, + ) + from app.services.shipping_notice.line_inventory_match_projection import ( + load_current_match_facts_by_task, + ) codes: list[str] = [] - # 兼容历史 multi_source_excel_block 任务。 - if bool(payload.get('multi_source_excel_block')): - for code in payload.get('resolved_ok_source_codes') or []: + for item in load_current_match_facts_by_task(getattr(task, 'id', None)).values(): + if str(item.get('match_result') or item.get('disposition') or '').strip().lower() != 'source_conflict': + continue + detail = dict(item.get('detail_json') or {}) if isinstance(item.get('detail_json'), dict) else {} + candidates = list(detail.get('candidate_hit_source_codes') or []) + if not candidates: + # [STEP] 冲突行未记录候选源时兜底读取全部可用源,避免用户无可选项。 + candidates = [ + str(src.get('source_code') or '').strip().upper() + for src in list_database_inventory_sources() + if str(src.get('source_code') or '').strip() + ] + for code in candidates: normalized = str(code or '').strip().upper() if normalized and normalized not in codes: codes.append(normalized) - if codes: - return codes - resolutions = payload.get('line_inventory_resolutions') - for collection in ( - resolutions, - payload.get('match_line_results'), - (payload.get('shortage_json') or {}).get('lines') if isinstance(payload.get('shortage_json'), dict) else None, - ): - if not isinstance(collection, list): - continue - for item in collection: - if not isinstance(item, dict): - continue - if str(item.get('disposition') or '') != 'multi_file_conflict': - continue - for code in item.get('candidate_hit_source_codes') or []: - normalized = str(code or '').strip().upper() - if normalized and normalized not in codes: - codes.append(normalized) return codes @@ -600,8 +557,17 @@ def apply_forced_match_source_filter( Returns: 过滤后的库存行;无强制源时原样返回。 """ + if task.__class__.__name__ == 'ShippingOrderTask': + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + selected = set() + for row in get_active_candidate_lines(task): + selected.update(str(code or '').strip().upper() for code in (getattr(row, 'source_codes_json', None) or []) if str(code or '').strip()) + if len(selected) == 1: + selected_code = next(iter(selected)) + return [row for row in inventory_lines if not isinstance(row, dict) or not row.get('__source_code') or str(row.get('__source_code')).strip().upper() == selected_code] + return inventory_lines payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - forced = str(payload.get('forced_match_source_code') or task.inventory_source_code or '').strip().upper() + forced = str(payload.get('forced_match_source_code') or '').strip().upper() if not forced: return inventory_lines if not any(isinstance(row, dict) and row.get('__source_code') for row in inventory_lines): diff --git a/backend/app/services/shipping_notice/stp_progress_contract.py b/backend/app/services/shipping_notice/stp_progress_contract.py index 106192fc..669c5204 100644 --- a/backend/app/services/shipping_notice/stp_progress_contract.py +++ b/backend/app/services/shipping_notice/stp_progress_contract.py @@ -87,17 +87,53 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: Returns: [{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。 """ - customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower() - pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower() - match_status = str(getattr(task, 'match_status', '') or '').strip().lower() + from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + # 客户确认 / 人工阻断:迁移后 Task 直传事实字段为权威来源;缺失时回退 DB 投影。 + customer_status = str( + getattr(task, 'customer_resolution_status', None) + or customer_confirmation_facts(task)['status'] + or '' + ).strip().lower() + pending = str( + getattr(task, 'pending_human_reason', None) + or task_blocking_reason(task) + or '' + ).strip().lower() + direct_match_status = getattr(task, 'match_status', None) + if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask': + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values()) + match_status = 'matched' if match_facts and all( + str(row.get('match_result') or '').strip().lower() == 'matched' + and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'} + for row in match_facts + ) else ('shortage' if match_facts else '') + elif direct_match_status is None: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower() + else: + match_status = str(direct_match_status or '').strip().lower() review_status = str(getattr(task, 'review_status', '') or '').strip().lower() - has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip()) - upload_status = str(getattr(task, 'upload_status', '') or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_notice_upload_status, + ) + direct_export_file = getattr(task, 'export_file_name', None) + if direct_export_file: + has_export = True + else: + artifact = latest_export_artifact(task) + has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip()) + projected_upload = project_notice_upload_status(task) + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} else - 'upload_failed' if upload_status == 'failed' else + 'uploaded' if projected_upload == 'uploaded' else + 'upload_failed' if projected_upload == 'failed' else 'matched' if match_status or has_export else - 'inventory_ready' if getattr(task, 'inventory_lines_json', None) else + 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'pending_review' if pending or review_status else 'created' ) diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index 3496cf91..be308e4c 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -89,11 +89,17 @@ def _target_is_safe(task: ShippingNotice) -> bool: 核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。 """ - if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ: return False - if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no: - return False - if task.match_status or task.upload_status: + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_for_task, + has_ready_inventory_file_for_task, + ) + + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + if has_ready_inventory_file_for_task(task) or current_inventory_matches_for_task(task) or latest_export_artifact(task) is not None or latest_upload_attempt(task) is not None: return False return True @@ -334,7 +340,7 @@ def apply_candidate_reconciliation_plan( ], } step_payload['field_conflicts'] = {'open_count': len(open_rows)} - task.step_payload_json = step_payload + task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}}) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) return { 'status': 'conflicted', @@ -385,7 +391,7 @@ def apply_candidate_reconciliation_plan( step_payload.pop('process_field_gate', None) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) task.error_message = None - task.step_payload_json = step_payload + task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}}) return { 'status': 'applied', 'reason': 'fields_backfilled', diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 985aa41e..7157ad02 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -19,12 +19,17 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingExportArtifact, ShippingOrderCandidate, + ShippingOrderExtraction, ShippingOrderIntake, + ShippingOrderTask, + ShippingCustomerShadowResolution, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, ShippingTaskPurgeAudit, + ShippingNoticeLineInventoryMatch, ) +from app.models.shipping_task_line import ShippingTaskFieldConflict TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore'] @@ -43,7 +48,7 @@ class TaskDispositionCapability: reason: str | None = None -def task_is_active(task: ShippingNotice) -> bool: +def task_is_active(task: ShippingNotice | ShippingOrderTask) -> bool: """ 判断任务是否仍可触发履约副作用。 @@ -61,7 +66,7 @@ def task_is_active(task: ShippingNotice) -> bool: ) -def task_execution_block_reason(task: ShippingNotice) -> str | None: +def task_execution_block_reason(task: ShippingNotice | ShippingOrderTask) -> str | None: """ 为异步编排和外部回调提供统一的副作用熔断原因。 @@ -79,7 +84,7 @@ def task_execution_block_reason(task: ShippingNotice) -> str | None: return f'task_lifecycle_{lifecycle or "inactive"}' -def load_task_for_disposition(task_no: str) -> ShippingNotice: +def load_task_for_disposition(task_no: str) -> ShippingNotice | ShippingOrderTask: """ 以行锁加载任务,供同一事务内重新判定并写入处置结果。 @@ -97,27 +102,29 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: if not normalized_task_no: raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED') task = ( - ShippingNotice.query - .filter(ShippingNotice.task_no == normalized_task_no) - .with_for_update() - .first() + ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no) + .with_for_update().first() ) + if task is None: + task = ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no).with_for_update().first() if task is None: raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND') return task -def _has_external_fulfillment(task: ShippingNotice) -> bool: +def _has_external_fulfillment(task: ShippingNotice | ShippingOrderTask) -> bool: """识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。""" - upload_status = str(task.upload_status or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower() return bool( - task.freight_ref_no - or upload_status in _EXTERNAL_UPLOAD_STATUSES + upload_status in _EXTERNAL_UPLOAD_STATUSES ) -def _has_successor(task: ShippingNotice) -> bool: +def _has_successor(task: ShippingNotice | ShippingOrderTask) -> bool: """修订链存在后继时禁止作废旧任务,避免破坏版本追溯。""" + if not isinstance(task, ShippingNotice): + return False return ( db.session.query(ShippingNotice.id) .filter(ShippingNotice.supersedes_task_id == int(task.id)) @@ -127,7 +134,7 @@ def _has_successor(task: ShippingNotice) -> bool: def task_disposition_capability( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, action: TaskDispositionAction, ) -> TaskDispositionCapability: """ @@ -200,7 +207,7 @@ def _disposition_reason_code(event_type: str, detail: dict[str, Any]) -> str | N def _write_disposition_event( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, event_type: str, actor_id: int | None, @@ -216,13 +223,15 @@ def _write_disposition_event( reason_code = _disposition_reason_code(event_type, payload) if reason_code: payload.setdefault('reason_code', reason_code) - db.session.add(ShippingTaskEvent( - task_id=int(task.id), - event_type=event_type, - actor_id=actor_id, - request_id=str(request_id or '').strip()[:64] or None, - detail_json=payload, - )) + from app.services.shipping_notice.tool_common import task_event_task_id + if isinstance(task, ShippingNotice): + db.session.add(ShippingTaskEvent( + task_id=task_event_task_id(task), + event_type=event_type, + actor_id=actor_id, + request_id=str(request_id or '').strip()[:64] or None, + detail_json=payload, + )) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit record_fulfillment_audit( @@ -237,7 +246,12 @@ def _write_disposition_event( result='success', after={ 'lifecycle_status': getattr(task, 'lifecycle_status', None), - 'upload_status': getattr(task, 'upload_status', None), + 'upload_status': getattr( + __import__('app.services.shipping_notice.upload_attempt_service', fromlist=['latest_upload_attempt']) + .latest_upload_attempt(task), + 'status', + None, + ), }, metadata={ 'dual_write': 'shipping_task_event', @@ -281,15 +295,25 @@ def move_task_to_recycle_bin( raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED') # [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。 + owner_task = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if isinstance(task, ShippingNotice) and task.order_task_id else task + ) has_internal_business_record = bool( - task.business_no - or task.customer_id - or task.source_candidate_id - or task.match_status - or task.export_file_path - or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).first() - or db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first() - or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).first() + getattr(task, 'business_no', None) + or ( + db.session.query(ShippingCustomerShadowResolution.id).filter_by( + candidate_id=getattr(owner_task, 'candidate_id', None), status='confirmed', + ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() + ) + or getattr(owner_task, 'candidate_id', None) + or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) + or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first() + or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first() + or ( + isinstance(task, ShippingNotice) + and db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first() + ) ) now = datetime.utcnow() task.deleted_at = now @@ -318,7 +342,7 @@ def move_task_to_recycle_bin( def void_task( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, reason: str, @@ -346,7 +370,7 @@ def void_task( def archive_task( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, request_id: str | None = None, @@ -368,7 +392,7 @@ def archive_task( def restore_task_from_recycle_bin( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, request_id: str | None = None, @@ -390,7 +414,7 @@ def restore_task_from_recycle_bin( def purge_task_permanently( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, reason: str, @@ -414,18 +438,50 @@ def purge_task_permanently( if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active': raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED') - from app.models import ShippingOrderExtraction, ShippingTemporaryInventorySession - from app.models.shipping_task_line import ShippingTaskFieldConflict + # OT 尚未生成 Notice 时只检查其自身的解析/库存/审计引用,禁止访问 Notice 专属字段。 + if isinstance(task, ShippingOrderTask): + blocking_counts = { + 'current_order_extraction': int(bool(task.current_order_extraction_id)), + 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), + 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), + 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), + } + blocking = {key: value for key, value in blocking_counts.items() if value} + if blocking: + raise ConflictError( + 'Order task has business or audit references and cannot be purged', + code='SHIPPING.TASK_PURGE_BLOCKED', + details={'blocking': blocking}, + ) + db.session.delete(task) + db.session.add(ShippingTaskPurgeAudit( + task_no_snapshot=task.task_no, + actor_id=actor_id, + reason=normalized_reason, + snapshot_json={'task_no': task.task_no, 'lifecycle_status': task.lifecycle_status}, + )) + return + + from app.models import ShippingTemporaryInventorySession # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 + owner = task if hasattr(task, 'current_order_extraction_id') else None + customer_confirmed = False + if owner is not None and owner.current_order_extraction_id: + customer_confirmed = db.session.query(ShippingCustomerShadowResolution.id).filter_by( + candidate_id=owner.candidate_id, status='confirmed', + ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() is not None blocking_counts = { 'business_number': int(bool(task.business_no)), - 'customer': int(bool(task.customer_id)), + 'customer': int(customer_confirmed), 'source_asset': int(bool(task.source_asset_id)), 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': int(bool(task.inventory_snapshot_id)), + 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), 'successor': int(_has_successor(task)), 'duplicate_link': int(bool(task.duplicate_source_task_id)), 'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter( diff --git a/backend/app/services/shipping_notice/task_field_conflict_service.py b/backend/app/services/shipping_notice/task_field_conflict_service.py index 1f263d61..6c801033 100644 --- a/backend/app/services/shipping_notice/task_field_conflict_service.py +++ b/backend/app/services/shipping_notice/task_field_conflict_service.py @@ -235,34 +235,37 @@ def resolve_field_conflict( remaining = list_open_field_conflicts(task) issues = task_reservation_gate_issues(task) step_payload = dict(task.step_payload_json or {}) - step_payload['field_conflicts'] = { - 'open_count': len(remaining), - 'last_resolved_id': conflict.id, - } - if idempotency_key: - step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip() - if remaining: - step_payload['process_field_gate'] = { - 'status': 'needs_enrichment', - 'missing_fields': sorted({row.field_name for row in remaining}), - 'issues': [ - { - 'severity': 'blocking', - 'field': row.field_name, - 'line_index': row.position, - 'reason': 'field_conflict', - 'conflict_id': row.id, - } - for row in remaining - ], + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['field_conflicts'] = { + 'open_count': len(remaining), + 'last_resolved_id': conflict.id, } + if idempotency_key: + step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip() + if remaining: + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['process_field_gate'] = { + 'status': 'needs_enrichment', + 'missing_fields': sorted({row.field_name for row in remaining}), + 'issues': [ + { + 'severity': 'blocking', + 'field': row.field_name, + 'line_index': row.position, + 'reason': 'field_conflict', + 'conflict_id': row.id, + } + for row in remaining + ], + } apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) elif issues: - step_payload['process_field_gate'] = { - 'status': 'needs_enrichment', - 'missing_fields': ['reservation_id'], - 'issues': issues, - } + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['process_field_gate'] = { + 'status': 'needs_enrichment', + 'missing_fields': ['reservation_id'], + 'issues': issues, + } apply_task_transition(task, TaskTransition.RSV_REQUIRED) else: step_payload.pop('process_field_gate', None) @@ -273,7 +276,9 @@ def resolve_field_conflict( 'issues': issues, 'resolution_source': 'field_conflict_resolve', } - task.step_payload_json = step_payload + task.step_payload_json = step_payload if task.__class__.__name__ != 'ShippingOrderTask' else { + key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'} + } log_task_event( task, diff --git a/backend/app/services/shipping_notice/task_field_gate.py b/backend/app/services/shipping_notice/task_field_gate.py index b98fb1d5..7e14be0b 100644 --- a/backend/app/services/shipping_notice/task_field_gate.py +++ b/backend/app/services/shipping_notice/task_field_gate.py @@ -74,7 +74,7 @@ def field_conflict_gate_response( 'issues': open_field_conflict_issues(task), }, }, - checkpoint='parse_review', + position='parse_review', stop_agent_turn=True, forbidden_next_tools=blocked, ) diff --git a/backend/app/services/shipping_notice/task_order_field_editor.py b/backend/app/services/shipping_notice/task_order_field_editor.py index ef178146..f2c25545 100644 --- a/backend/app/services/shipping_notice/task_order_field_editor.py +++ b/backend/app/services/shipping_notice/task_order_field_editor.py @@ -152,9 +152,10 @@ def current_line_field_configs(task: ShippingNotice) -> dict[str, dict[str, Any] def _current_extraction(task: ShippingNotice) -> ShippingOrderExtraction: """读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。""" + extraction_id = getattr(task, 'current_order_extraction_id', None) extraction = ( - db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - if task.current_order_extraction_id is not None else None + db.session.get(ShippingOrderExtraction, extraction_id) + if extraction_id is not None else None ) if extraction is None or extraction.status != 'accepted': raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED') @@ -338,7 +339,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A value_json=previous_value.value_json, )) for position, values in enumerate(lines): - line = ShippingOrderLine(extraction_id=replacement.id, position=position) + line = ShippingOrderLine(extraction_id=replacement.id, position=position, line_no=position + 1) db.session.add(line) db.session.flush() for config in configs: diff --git a/backend/app/services/shipping_notice/task_supersession_service.py b/backend/app/services/shipping_notice/task_supersession_service.py index 59a90aa4..3625f139 100644 --- a/backend/app/services/shipping_notice/task_supersession_service.py +++ b/backend/app/services/shipping_notice/task_supersession_service.py @@ -6,8 +6,9 @@ from datetime import datetime from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent +from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.task_disposition_service import task_is_active +from app.services.shipping_notice.tool_common import task_event_task_id def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingNotice, actor_id: int, reason: str) -> None: @@ -18,24 +19,48 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID') if not task_is_active(old): return - external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + latest_attempt = latest_upload_attempt(old) + external = bool( + has_verified_upload_success(old) + or str(getattr(latest_attempt, 'freight_ref_no', '') or '').strip() + ) if external: existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none() if existing is None: db.session.add(ShippingFreightCancellation(old_task_id=old.id, new_task_id=new.id, requested_by_id=actor_id, reason=reason)) - new.lifecycle_status = 'blocked' - new.pending_human_reason = 'freight_cancellation_required' - db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason})) + new_owner = ( + db.session.get(ShippingOrderTask, int(new.order_task_id)) + if new.order_task_id is not None else None + ) + if new_owner is not None: + # lifecycle_status 仅表达 active/voided/archived;流程阻断属于 status。 + new_owner.status = 'blocked' + new_owner.pending_human_reason = 'freight_cancellation_required' + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason})) return old.lifecycle_status = 'voided' old.voided_at = datetime.utcnow() old.voided_by_id = actor_id old.void_reason = reason - db.session.add(ShippingTaskEvent(task_id=old.id, event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason})) - db.session.add(ShippingTaskEvent(task_id=new.id, event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()})) + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(old), event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason})) + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()})) def assert_task_not_supersession_blocked(task: ShippingNotice) -> None: """库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。""" - if str(task.lifecycle_status or '').lower() == 'blocked' and task.pending_human_reason == 'freight_cancellation_required': + if isinstance(task, ShippingOrderTask): + lifecycle = str(getattr(task, 'lifecycle_status', '') or '').lower() + reason = str(getattr(task, 'pending_human_reason', '') or '').lower() + if str(getattr(task, 'status', '') or '').lower() == 'blocked' and reason == 'freight_cancellation_required': + raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED') + return + owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if task.order_task_id is not None else None + ) + lifecycle = str(getattr(owner, 'status', None) or '').lower() + reason = str(getattr(owner, 'pending_human_reason', None) or '').lower() + if lifecycle == 'blocked' and reason == 'freight_cancellation_required': raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED') diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index fb7e0d86..b4a2f40e 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -2,9 +2,9 @@ services/shipping_notice/task_workflow.py 用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。 -依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、 +依赖:query_service、tool_common、progress_workflow、state_machine、 fulfillment_audit、schema_edit_policy、动态订单字段编辑器、candidate_qualification_service。 -逻辑:tools.py 门面委托本模块;创建 Task 前强制客户已确认(禁止先建单再 customer_review); +逻辑:tools.py 门面委托本模块;创建 OT 不强制客户已确认(先建单,客户确认交由订单复核/客户门禁处理); 正式字段编辑经 Schema 策略门禁后落库,并按 change_effect 失效下游; 成功/拒绝编辑与库存/Excel 失效同事务写入 ShippingAuditEvent; retry_task 写入操作人与前后快照审计。 @@ -20,9 +20,8 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingNotice -from app.services.shipping_notice.constants import CP_TASK_EXISTS -from app.services.shipping_notice.decision_workflow import submit_decision +from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake +from app.services.shipping_notice.constants import POSITION_TASK_EXISTS from app.services.shipping_notice.task_order_field_editor import ( current_header_field_values, retire_current_order_extraction, @@ -52,8 +51,7 @@ from app.services.shipping_notice.batch_create_idempotency import ( assert_no_exact_duplicate_notices, ) from app.services.shipping_notice.candidate_qualification_service import ( - assert_customer_confirmed_before_task_create, - resolve_confirmed_bill_to_customer_id, + resolve_confirmed_customer_id, ) from app.services.shipping_notice.tool_common import ( generate_task_no, @@ -64,6 +62,13 @@ from app.services.shipping_notice.tool_common import ( ) from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent + +def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool: + """读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。""" + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + return has_ready_inventory_file_for_task(task) + EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"}) EDITABLE_NOTICE_LINE_FIELDS = frozenset({ "part_number", @@ -76,6 +81,12 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({ }) +def _task_intake(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderIntake | None: + """返回 OT 关联的 Intake,原始正文与来源元数据统一由 Intake 承载。""" + intake_id = getattr(task, 'intake_id', None) + return db.session.get(ShippingOrderIntake, int(intake_id)) if intake_id else None + + def start_task_orchestrator(task_no: str | None) -> bool: """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start @@ -118,13 +129,13 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: task_id=existing_by_no.task_no, message=f"已找到发货任务 {existing_by_no.task_no},将继续处理该任务。", data=qs_serialize_task(existing_by_no, TaskProjection.TOOL_INTERNAL), - checkpoint=CP_TASK_EXISTS, + position=POSITION_TASK_EXISTS, ) if conv_id: existing = ( - ShippingNotice.query.filter_by(conversation_id=conv_id) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query.filter_by(conversation_id=conv_id) + .filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'})) + .order_by(ShippingOrderTask.id.desc()) .first() ) if existing: @@ -133,37 +144,35 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: task_id=existing.task_no, message=( f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。" - "用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。" ), data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL), - checkpoint=CP_TASK_EXISTS, + position=POSITION_TASK_EXISTS, ) - # [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。 + # [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。 customer_id = _parse_optional_customer_id(payload.get("customer_id")) - assert_customer_confirmed_before_task_create( - customer_id=customer_id, - ) - task = ShippingNotice( + user_id = payload.get("user_id") + if user_id is None: + raise ValidationError('user_id is required', code='SHIPPING.USER_REQUIRED') + task = ShippingOrderTask( task_no=generate_task_no(), - customer_id=customer_id, - user_id=payload.get("user_id"), + user_id=int(user_id), conversation_id=str(payload.get("conversation_id") or "").strip() or None, - source_type=str(payload.get("source_type") or "manual"), - batch_index=1, - batch_total=1, - raw_content=str(payload.get("raw_content") or "").strip() or None, - customer_resolution_status='pending', + # OT 仅接受 intake 层定义的来源类型;未知/手工入口保持 NULL,避免违反模型约束。 + source_type=(str(payload.get("source_type") or "").strip() or None), + status='processing', + stage='document_parsing', ) db.session.add(task) log_task_event(task, "task_created", {"source_type": task.source_type}) db.session.flush() - _bind_confirmed_customer_after_task_create( - task, - customer_id=customer_id, - candidate=None, - actor_id=payload.get("user_id"), - ) + if customer_id is not None: + _bind_confirmed_customer_after_task_create( + task, + customer_id=customer_id, + candidate=None, + actor_id=payload.get("user_id"), + ) db.session.commit() return tool_response( status="ok", @@ -190,7 +199,7 @@ def _parse_optional_customer_id(raw: Any) -> int | None: def _bind_confirmed_customer_after_task_create( - task: ShippingNotice, + task: ShippingOrderTask, *, customer_id: int | None, candidate: ShippingOrderCandidate | None, @@ -199,9 +208,9 @@ def _bind_confirmed_customer_after_task_create( """ 创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。 - 核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。 + 核心逻辑:用显式 customer_id 或已确认识别结果直接确认当前 OT。 """ - bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate) + bind_id = customer_id or resolve_confirmed_customer_id(candidate=candidate) if bind_id is None: raise ConflictError( 'Customer must be confirmed before creating a shipping task', @@ -229,69 +238,43 @@ def _notice_header_snapshot(task: ShippingNotice) -> dict[str, Any]: def _reset_notice_edit_downstream(task: ShippingNotice) -> None: """清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。""" - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - task.upload_attempt = 0 - task.upload_started_at = None - task.upload_finished_at = None - task.upload_error_code = None - task.upload_error_message = None - task.upload_receipt_json = None - task.idempotency_key = None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload.pop('export_meta', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload def _reset_notice_export_downstream(task: ShippingNotice) -> None: """仅使 Excel 导出派生结果失效,保留库存匹配真相。""" - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - task.upload_attempt = 0 - task.upload_started_at = None - task.upload_finished_at = None - task.upload_error_code = None - task.upload_error_message = None - task.upload_receipt_json = None - task.idempotency_key = None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload.pop('export_meta', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload -def _resolve_order_task_for_notice(task: ShippingNotice): - """按 Notice 反查 OT;供 change_effect 同步统一进度 stage。""" - from app.models import ShippingOrderTask - +def _resolve_order_task_for_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask | None: + """按 Notice 反查 OT;若入参本身即 OT 则直接返回,供 change_effect 同步统一进度 stage。""" + if isinstance(task, ShippingOrderTask): + return task order_task_id = getattr(task, 'order_task_id', None) if order_task_id is not None: return db.session.get(ShippingOrderTask, int(order_task_id)) - return ( - db.session.query(ShippingOrderTask) - .filter(ShippingOrderTask.shipping_notice_id == int(task.id)) - .order_by(ShippingOrderTask.id.asc()) - .first() - ) + return None def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None: """ - 将改单失效起点写入 Notice.step_payload_json,供投影 stage_nodes 消费。 + 将改单失效起点写入 OT.step_payload_json,供投影 stage_nodes 消费。 [BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险; 完整列级约束与乐观锁仍待显式字段迁移。 Args: - task: 被编辑的正式任务。 + task: 被编辑的正式任务(ShippingNotice)。 stage: 失效起点统一 stage。 """ from datetime import datetime @@ -301,33 +284,42 @@ def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None code = str(stage or '').strip().lower() if code not in SHIPPING_PROCESSING_STAGES: return - payload = dict(task.step_payload_json or {}) if isinstance(task.step_payload_json, dict) else {} + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + payload = ( + dict(order_task.step_payload_json or {}) + if isinstance(order_task.step_payload_json, dict) else {} + ) history = payload.get('invalidated_from_stage_history') if not isinstance(history, list): history = [] history.append({ 'stage': code, 'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z', - 'progress_version': int(getattr(task, 'progress_version', None) or 0), + 'progress_version': int(getattr(order_task, 'progress_version', None) or 0), }) payload['invalidated_from_stage'] = code payload['invalidated_from_stage_history'] = history[-20:] - task.step_payload_json = payload + order_task.step_payload_json = payload def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None: """ - 清除 Notice 上的改单失效起点(下游已成功重跑后)。 + 清除 OT 上的改单失效起点(下游已成功重跑后)。 [BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。 """ - if not isinstance(task.step_payload_json, dict): + order_task = _resolve_order_task_for_notice(task) + if order_task is None: return - if 'invalidated_from_stage' not in task.step_payload_json: + if not isinstance(order_task.step_payload_json, dict): return - payload = dict(task.step_payload_json) + if 'invalidated_from_stage' not in order_task.step_payload_json: + return + payload = dict(order_task.step_payload_json) payload.pop('invalidated_from_stage', None) - task.step_payload_json = payload + order_task.step_payload_json = payload def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None: @@ -344,7 +336,10 @@ def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | Non if task is None: return None - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return None + payload = order_task.step_payload_json if isinstance(order_task.step_payload_json, dict) else {} code = str(payload.get('invalidated_from_stage') or '').strip().lower() return code if code in SHIPPING_PROCESSING_STAGES else None @@ -374,7 +369,6 @@ def _apply_notice_edit_change_effects( from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields from app.services.shipping_notice.order_task_service import sync_order_task_processing_state from app.services.shipping_notice.inventory_source_gate import ( - STABLE_INVENTORY_SOURCE_STATUSES, adjudicate_and_apply_inventory_source, clear_inventory_source_confirmation, ) @@ -399,18 +393,12 @@ def _apply_notice_edit_change_effects( # [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。 if 'rerun_inventory_source_resolution' in effects: clear_inventory_source_confirmation(task) - task.inventory_source_status = 'unresolved' - task.inventory_source_code = None - task.inventory_connector_type = None - task.inventory_warehouse_id = None - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.inventory_lines_json = None _reset_notice_export_downstream(task) _set_notice_invalidated_from_stage(task, 'inventory_source_resolving') adjudication = adjudicate_and_apply_inventory_source(task) - stable = str(adjudication.status or '').strip() in STABLE_INVENTORY_SOURCE_STATUSES + from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable + + stable = is_inventory_source_stable(task) if order_task is not None: if stable: sync_order_task_processing_state( @@ -429,10 +417,6 @@ def _apply_notice_edit_change_effects( return applied if 'rerun_inventory_matching' in effects: - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.inventory_lines_json = None _reset_notice_export_downstream(task) _set_notice_invalidated_from_stage(task, 'inventory_matching') if order_task is not None: @@ -553,9 +537,11 @@ def _record_formal_task_edit_audits( 'export_file_name': before_export_file_name, 'order_data_version': before_order_data_version, } + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + after_artifact = latest_export_artifact(task) after_summary = { - 'match_status': task.match_status, - 'export_file_name': task.export_file_name, + 'match_status': None, + 'export_file_name': getattr(after_artifact, 'file_name', None), 'order_data_version': task.order_data_version, } field_changes = _formal_edit_field_diff_summary( @@ -605,7 +591,7 @@ def _record_formal_task_edit_audits( reason_code='inventory_match_invalidated', result='success', before={'match_status': before_match_status}, - after={'match_status': task.match_status}, + after={'match_status': None}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, source='workspace_api', ) @@ -627,7 +613,7 @@ def _record_formal_task_edit_audits( reason_code='excel_export_invalidated', result='success', before={'export_file_name': before_export_file_name}, - after={'export_file_name': task.export_file_name}, + after={'export_file_name': getattr(after_artifact, 'file_name', None)}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, source='workspace_api', ) @@ -707,14 +693,14 @@ def replace_task_notice( """ cleaned_text = str(raw_text or "").strip() cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()] + intake = _task_intake(task) if not cleaned_text: apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) task.error_message = "未能从重新上传的发货通知中抽取到可解析文本" - task.raw_content = "" - if source_file_name: - task.source_file_name = source_file_name - if source_file_type: - task.source_file_type = source_file_type + if intake is not None: + intake.extracted_text = "" + intake.error_message = task.error_message + intake.parse_warnings_json = cleaned_warnings set_task_step_progress( task, step_key="step2_parse_confirm", @@ -736,13 +722,10 @@ def replace_task_notice( data={**serialize_task_for_tool(task), "warnings": cleaned_warnings}, ) - task.raw_content = cleaned_text - if source_file_name: - task.source_file_name = source_file_name - if source_file_type: - task.source_file_type = source_file_type + if intake is not None: + intake.extracted_text = cleaned_text + intake.parse_warnings_json = cleaned_warnings retire_current_order_extraction(task) - task.parse_confidence = None task.review_status = None task.pending_human_reason = None task.error_message = None @@ -821,6 +804,30 @@ def _assert_order_data_version(task: ShippingNotice, payload: dict[str, Any]) -> return None +def _edit_window_busy_error(task: ShippingNotice) -> dict[str, Any] | None: + """ + 二期编辑窗守卫(D10/§3.3):订单任一通知存在活动 Gate Attempt(库存 RPA / 匹配 queued|running) + 时拒绝保存,返回 SYSTEM_BUSY 的 failed Tool 响应;否则 None。 + + Args: + task: 被编辑的 ShippingNotice。 + + Returns: + 活动 Attempt 时的 tool_response(status='failed', error_code=SHIPPING.EDIT_WINDOW_SYSTEM_BUSY); + 通过则 None。 + """ + from app.services.shipping_notice.order_edit_window_service import order_has_active_attempt + + if order_has_active_attempt(task): + return tool_response( + status='failed', + task=task, + message='系统处理中,请稍后再修改。', + data={'error_code': 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY'}, + ) + return None + + def _notice_edit_idempotency_replay( task: ShippingNotice, payload: dict[str, Any], @@ -829,7 +836,10 @@ def _notice_edit_idempotency_replay( key = str(payload.get('idempotency_key') or '').strip() if not key: return None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return None + step_payload = dict(order_task.step_payload_json or {}) last = step_payload.get('last_notice_edit_idempotency') if not isinstance(last, dict): return None @@ -853,9 +863,35 @@ def _remember_notice_edit_idempotency( text = str(key or '').strip() if not text: return - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message} - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload + + +def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> str | None: + """ + 读取 OT 当前行级库存匹配状态(matched / shortage / None), + 供正式编辑审计 before 快照记录失效前的真实 match_status。 + + 核心逻辑:以行级 Match 事实为准(禁止读取 OT 缓存字段), + all 行匹配且无短缺为 matched,否则有行时视为 shortage;无行返回 None。 + """ + if order_task is None: + return None + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + facts = list(load_current_match_facts_by_task(order_task.id).values()) + if not facts: + return None + matched = all( + str(row.get('match_result') or '').strip().lower() == 'matched' + and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'} + for row in facts + ) + return 'matched' if matched else 'shortage' def _commit_notice_edit( @@ -887,7 +923,10 @@ def _commit_notice_edit( if not reviewed_by_id or not evidence_ref or not reason: raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED') # [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。 - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + raise ConflictError('Formal task edit requires a linked order task', code='SHIPPING.ORDER_TASK_REQUIRED') + step_payload = dict(order_task.step_payload_json or {}) validation_issues = task_reservation_gate_issues(task) step_payload["parse_validation"] = { "status": "needs_review" if validation_issues else "ready", @@ -903,11 +942,12 @@ def _commit_notice_edit( } else: step_payload.pop('process_field_gate', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload # [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。 - before_match_status = task.match_status - before_export_file_name = task.export_file_name + before_match_status = _order_task_match_status_for_audit(order_task) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + before_export_file_name = getattr(latest_export_artifact(task), 'file_name', None) before_order_data_version = task.order_data_version applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or []) if validation_issues: @@ -1046,6 +1086,10 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error fields = payload.get("fields") if not isinstance(fields, dict) or not fields: @@ -1137,6 +1181,10 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error try: line_index = int(payload.get("line_index")) @@ -1244,6 +1292,10 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error line = payload.get("line") if not isinstance(line, dict) or not line: @@ -1288,6 +1340,10 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error try: line_index = int(payload.get("line_index")) @@ -1347,10 +1403,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: task.error_message = None # [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮 # 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。 - task.match_status = None - task.line_results_json = None - task.shortage_json = None - try: order_lines = current_line_field_values(task) except ConflictError: @@ -1384,7 +1436,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: reason=comment or None, before=before, after=after, - metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)}, + metadata={ + 'has_order_lines': bool(order_lines), + 'has_inventory_lines': _has_ready_inventory_file(task), + }, source=event_source, ) db.session.commit() diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index ea584f61..fd3f4002 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -18,7 +18,7 @@ import uuid from flask import current_app from app import db -from app.models import ShippingNotice, ShippingTaskEvent +from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK @@ -221,8 +221,11 @@ def set_task_step_progress( detail: str | None = None, extra: dict[str, Any] | None = None, ) -> None: - """写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。""" - payload = dict(task.step_payload_json or {}) + """写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。""" + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = dict(getattr(owner, 'step_payload_json', None) or {}) progress: dict[str, Any] = { "step_key": step_key, "step_title": step_title, @@ -240,15 +243,23 @@ def set_task_step_progress( if extra: progress["extra"] = extra payload["current_step_progress"] = progress - task.current_step = step_key - task.step_payload_json = payload + if hasattr(owner, 'current_step'): + owner.current_step = step_key + if hasattr(owner, 'stage'): + owner.stage = step_key + if hasattr(owner, 'step_payload_json'): + owner.step_payload_json = payload def clear_task_step_progress(task: ShippingNotice) -> None: """清空任务步骤内进度,保留其他 step_payload_json 字段。""" - payload = dict(task.step_payload_json or {}) + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = dict(getattr(owner, 'step_payload_json', None) or {}) payload.pop("current_step_progress", None) - task.step_payload_json = payload or None + if hasattr(owner, 'step_payload_json'): + owner.step_payload_json = payload or None @@ -307,7 +318,7 @@ def build_task_action_event_detail( def log_task_event( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, event_type: str, detail: dict[str, Any] | None = None, *, @@ -333,10 +344,14 @@ def log_task_event( before: 操作前业务快照。 after: 操作后业务快照。 """ - if task.id is None: + event_task_id = task_event_task_id(task) + if event_task_id is None: db.session.flush() + event_task_id = task_event_task_id(task) + if event_task_id is None: + raise ValueError('shipping task event requires an order task id') db.session.add(ShippingTaskEvent( - task_id=task.id, + task_id=event_task_id, event_type=event_type, detail_json=detail or {}, actor_id=actor_id, @@ -436,6 +451,14 @@ def log_task_event( ) +def task_event_task_id(task: ShippingNotice | ShippingOrderTask) -> int | None: + """将 Notice/OT 输入统一解析为 ShippingTaskEvent 使用的 OT 主键。""" + if isinstance(task, ShippingOrderTask): + return int(task.id) if task.id is not None else None + order_task_id = getattr(task, 'order_task_id', None) + return int(order_task_id) if order_task_id is not None else None + + def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None: """ 将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。 @@ -505,7 +528,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]: snapshot = { 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), - 'reason_code': getattr(task, 'pending_human_reason', None), + 'reason_code': __import__('app.services.shipping_notice.process_gate_projection', fromlist=['task_blocking_reason']).task_blocking_reason(task), } return {key: value for key, value in snapshot.items() if value is not None} diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index f2699515..b7b8b700 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -2,7 +2,7 @@ services/shipping_notice/tool_response.py 用途:统一构建发货通知 Tool 的 JSON 响应结构。 -依赖:state_machine 中的 checkpoint 解析能力;ShippingProcessExecution。 +依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。 逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; 已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。 """ @@ -12,10 +12,10 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from app.models import ShippingNotice + from app.models import ShippingNotice, ShippingOrderTask -def _task_has_process_execution(task: ShippingNotice | None) -> bool: +def _task_has_process_execution(task: ShippingOrderTask | ShippingNotice | None) -> bool: """ 判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。 @@ -27,11 +27,17 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool: """ if task is None or getattr(task, 'id', None) is None: return False - from app.models import ShippingProcessExecution + from app.models import ShippingNotice, ShippingProcessExecution + if isinstance(task, ShippingNotice): + task_id = int(task.order_task_id) if task.order_task_id is not None else None + else: + task_id = int(task.id) if getattr(task, 'id', None) is not None else None + if task_id is None: + return False return ( ShippingProcessExecution.query - .filter_by(task_id=int(task.id)) + .filter_by(task_id=task_id) .filter(ShippingProcessExecution.status != 'superseded') .first() is not None @@ -77,7 +83,7 @@ def tool_response( data: dict[str, Any] | None = None, human_options: list[str] | None = None, action_buttons: list[dict[str, str]] | None = None, - checkpoint: str | None = None, + position: str | None = None, next_required_action: str | None = None, forbidden_next_tools: list[str] | None = None, stop_agent_turn: bool = False, @@ -86,11 +92,12 @@ def tool_response( """ 构建发货通知 Tool 标准 JSON 响应。 - 核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint; - 显式 checkpoint 优先(如 parse_ok、task_exists)。 - 若任务已有 ProcessExecution:不再填充旧动作字段,避免与 Gate 双真相。 + 核心逻辑:未显式传 position 时从 task 派生位置;显式 position 优先 + (如 parse_ok、task_exists)。若任务已有 ProcessExecution:不再填充旧动作字段, + 避免与 Gate 双真相。 Args: + position: 进程位置标签;None 时从 resolve_task_ui_state(task).position 推导。 stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。 extra: 需要保留在顶层的额外业务字段。 @@ -103,12 +110,12 @@ def tool_response( gate_owns_recovery = _task_has_process_execution(task) # action_buttons 是历史调用参数,仅为兼容调用方签名;绝不进入对外响应。 del action_buttons - resolved_checkpoint = checkpoint + resolved_position = position # 旧 human_options 参数仅保留调用签名兼容,绝不返回。用户动作必须由 Gate DTO 授权。 del human_options - if checkpoint is None and task is not None: + if position is None and task is not None: ui = resolve_task_ui_state(task) - resolved_checkpoint = ui.checkpoint + resolved_position = ui.position payload: dict[str, Any] = { "status": status, @@ -118,8 +125,8 @@ def tool_response( if task_id: payload["task_id"] = task_id # [STEP] 业务按钮统一由 ui_state.actions 返回;Tool 响应不再生成旧 human_options/action_buttons。 - if resolved_checkpoint: - payload["checkpoint"] = resolved_checkpoint + if resolved_position: + payload["position"] = resolved_position if next_required_action and not gate_owns_recovery: payload["next_required_action"] = _sanitize_user_facing_text(next_required_action) if forbidden_next_tools: diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 62efdde8..6e38cc90 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -20,7 +20,6 @@ from app.services.shipping_notice import customer_identity_gate # 任务 / 决策 create_task = task_workflow.create_task auto_progress = task_workflow.auto_progress -submit_decision = task_workflow.submit_decision get_task_status = task_workflow.get_task_status retry_task = task_workflow.retry_task update_notice_fields = task_workflow.update_notice_fields diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index be7c979b..38b755b3 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -2,14 +2,19 @@ services/shipping_notice/ui_state.py 用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 -依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、 - process_gate_projection(统一 Gate 用户摘要)、 - order_review_workbench_projection.apply_post_ot_gate_rules。 -逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions, - 再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 - stp_facts、progress_nodes); - 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; - Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); +依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、 + query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、 + process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、 + order_review_fulfillment_decision_service(短缺放行模板字段)、 + order_review_workbench_projection、inventory_source_repository(preparation.source_options)。 +逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode); + Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id); + stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT), + 行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源); + 短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line; + 下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass); + 用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要; + project_notice_available_actions 供货代上传聚合行内菜单轻量消费。 """ from __future__ import annotations @@ -18,24 +23,24 @@ from typing import Any from app.models import ShippingNotice from app.services.shipping_notice.constants import ( - CP_COMPLETED, - CP_CUSTOMER_REVIEW, - CP_EXPORT_GENERATED, - CP_EXPORT_READY, - CP_INVENTORY_PENDING, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_PARSE_REVIEW, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, + POSITION_COMPLETED, + POSITION_CUSTOMER_REVIEW, + POSITION_EXPORT_GENERATED, + POSITION_EXPORT_READY, + POSITION_INVENTORY_PENDING, + POSITION_INVENTORY_SOURCE_REVIEW, + POSITION_ORDER_FREEZE, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, + POSITION_PARSE_REVIEW, + POSITION_READY_EXPORT, + POSITION_READY_MATCH, + POSITION_REJECTED, + POSITION_RSV_REQ, + POSITION_UPLOADED, + POSITION_UPLOAD_FAILED, + POSITION_UPLOAD_RESULT_UNKNOWN, + POSITION_UPLOAD_REQ, + POSITION_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_RPA_EXHAUSTED, @@ -53,10 +58,12 @@ from app.services.shipping_notice.lifecycle_projection import ( ) from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary from app.services.shipping_notice.state_machine import ( - CheckpointKind, - resolve_task_ui_state, + UserMode, +) +from app.services.shipping_notice.user_facing_status import ( + user_facing_stage_label_for_position, + user_facing_task_stage, ) -from app.services.shipping_notice.user_facing_status import user_facing_task_stage WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( @@ -67,42 +74,52 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"}, ) -_REVIEW_ENTRY_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_NOTICE_TEXT_EXTRACTION_FAILED, +_REVIEW_ENTRY_POSITIONS = { + POSITION_PARSE_REVIEW, + POSITION_RSV_REQ, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, } -_NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = { - CP_INVENTORY_PENDING: "ensure_inventory", - CP_ORDER_FREEZE: "freeze_order", - CP_READY_MATCH: "match_inventory", - CP_READY_EXPORT: "generate_excel", +_NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = { + POSITION_INVENTORY_PENDING: "ensure_inventory", + POSITION_ORDER_FREEZE: "freeze_order", + POSITION_READY_MATCH: "match_inventory", + POSITION_READY_EXPORT: "generate_excel", } -_PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { - CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"), - CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"), - CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"), - CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"), - CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"), - CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"), +_PAUSE_REASON_BY_POSITION: dict[str, tuple[str, str]] = { + POSITION_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"), + POSITION_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"), + POSITION_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"), + POSITION_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"), + POSITION_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"), + POSITION_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"), RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"), - CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"), - CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), - CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), - CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), - CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), - CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + POSITION_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"), + POSITION_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), + POSITION_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), + POSITION_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), + POSITION_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + POSITION_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), } def _task_lifecycle( - *, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None, + *, task: ShippingNotice, position: str | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。""" + del position # 生命周期不再由位置码推导。 gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + # 有正式 Gate 或已验证上传时才开放五阶段入口;否则保持 unclassified(禁止旧 CP 冒充)。 + has_formal = bool( + isinstance(process_gate, dict) + and ( + process_gate.get('current_gate_code') + or process_gate.get('current_blocking_gate') + or process_gate.get('current_gate') + ) + ) return project_lifecycle( current_gate=gate if isinstance(gate, dict) else None, blocking_reason=( @@ -110,9 +127,9 @@ def _task_lifecycle( if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code') else None ), - # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 - has_candidate_context=True, + has_candidate_context=has_formal or has_verified_upload_success(task), verified_upload_success=has_verified_upload_success(task), + processing_stage=getattr(task, 'stage', None), ) @@ -184,7 +201,7 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]: def build_shipping_workflow_steps( task: ShippingNotice, - checkpoint: str | None, + position: str | None, *, lifecycle_stage: str | None = None, ) -> list[dict[str, str]]: @@ -194,6 +211,7 @@ def build_shipping_workflow_steps( Returns: list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。 """ + del position # 五阶段仅由 lifecycle_stage 驱动 lifecycle_index = next( (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage), None, @@ -218,12 +236,12 @@ def build_shipping_workflow_steps( return steps -_PARSE_STAGE_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_NOTICE_TEXT_EXTRACTION_FAILED, +_PARSE_STAGE_POSITIONS = { + POSITION_PARSE_REVIEW, + POSITION_RSV_REQ, + POSITION_INVENTORY_SOURCE_REVIEW, + POSITION_ORDER_FREEZE, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, } _WARNING_DISPLAY_ALIASES: dict[str, str] = { @@ -264,34 +282,34 @@ def _parse_validation_issue_text(issue: dict[str, Any]) -> str: return f"第 {line_no} 行料号 {part_number}:缺少合法的 Reservation ID。" -def _collect_parse_stage_issues(task: ShippingNotice, checkpoint: str | None) -> list[str]: +def _collect_parse_stage_issues(task: ShippingNotice, position: str | None) -> list[str]: """ 汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发; 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。 """ - checkpoint_value = str(checkpoint or "").strip() - if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS: + position_value = str(position or "").strip() + if position_value not in _PARSE_STAGE_POSITIONS: return [] issues: list[str] = [] - if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW: + if position_value == POSITION_INVENTORY_SOURCE_REVIEW: _append_unique_issue( issues, task.error_message or "无法根据发货通知唯一确定库存查询来源", ) - elif checkpoint_value == CP_RSV_REQ: + elif position_value == POSITION_RSV_REQ: _append_unique_issue( issues, task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)", ) - elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED: + elif position_value == POSITION_NOTICE_TEXT_EXTRACTION_FAILED: _append_unique_issue( issues, task.error_message or "未能从发货通知中解析到可审核内容", ) - elif checkpoint_value == CP_PARSE_REVIEW: + elif position_value == POSITION_PARSE_REVIEW: _append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。") if not is_inventory_source_stable(task): _append_unique_issue( @@ -317,7 +335,57 @@ def _collect_parse_stage_issues(task: ShippingNotice, checkpoint: str | None) -> return issues -def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str: +def _derived_entry_surface( + *, + gate_code: str | None, + review_status: str | None, + user_mode: str, + position: str | None = None, +) -> str: + """ + 由 Gate 位置与用户模式推导操作入口面。 + + Returns: + review_workbench | task_workbench | none + """ + rs = str(review_status or '').strip() + code = str(gate_code or '').strip() + pos = str(position or '').strip() + if pos in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED, POSITION_WAITING_UPLOAD} or code in { + 'artifact_generation', + 'manual_upload_handoff', + }: + return 'task_workbench' + if rs in {'parse_review', 'rsv_req', 'customer_review'} or code in { + 'order_field_extraction', + 'customer_resolution', + 'reservation_validation', + }: + return 'review_workbench' + if user_mode == 'complete': + return 'none' + if user_mode in {'must_human', 'wait_manual_upload'}: + return 'task_workbench' + if code in { + 'inventory_preparation', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'inventory_source_routing', + 'order_freeze_readiness', + }: + return 'task_workbench' + return 'none' + + +def _derived_current_todo(*, position: str | None) -> str | None: + """从 Gate position 提取只读待办说明。""" + pause = _PAUSE_REASON_BY_POSITION.get(str(position or '')) + return pause[1] if pause else None + + +def _entry_surface_for(position: str | None, kind: UserMode) -> str: """ 解析当前操作应进入的工作台类型。 @@ -325,28 +393,28 @@ def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str: review_workbench | task_workbench | none """ # Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。 - if str(checkpoint or "") in {CP_EXPORT_READY, CP_EXPORT_GENERATED}: + if str(position or "") in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED}: return "task_workbench" - if kind == CheckpointKind.COMPLETE: + if kind == UserMode.COMPLETE: return "none" - if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS: + if str(position or "") in _REVIEW_ENTRY_POSITIONS: return "review_workbench" - if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}: + if kind in {UserMode.MUST_HUMAN, UserMode.WAIT_MANUAL_UPLOAD}: return "task_workbench" - if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in { - CP_ORDER_FREEZE, - CP_READY_MATCH, - CP_READY_EXPORT, - CP_INVENTORY_PENDING, + if kind == UserMode.AUTO_CONTINUE and position in { + POSITION_ORDER_FREEZE, + POSITION_READY_MATCH, + POSITION_READY_EXPORT, + POSITION_INVENTORY_PENDING, }: # 自动链可继续,但仍允许工作台手动兜底 return "task_workbench" return "none" -def _current_todo_label(checkpoint: str | None) -> str | None: - """从内部 checkpoint 提取只读待办说明,不派生用户动作。""" - pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) +def _current_todo_label(position: str | None) -> str | None: + """从位置标签提取只读待办说明,不派生用户动作。""" + pause = _PAUSE_REASON_BY_POSITION.get(str(position or "")) return pause[1] if pause else None @@ -354,14 +422,11 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: """ 投影 STP 履约事实供 Chat/工作台/待办同源消费。 - 核心逻辑:只读 task + step_payload;无 STP 痕迹时返回 None,避免普通任务噪声。 - - Args: - task: 发货任务。 - - Returns: - stp_facts 字典或 None。 + 核心逻辑:只读 OT 的 CandidateSet、Preparation/Link/File 与行级 Match; + 无 STP 痕迹时返回 None,避免普通任务噪声。禁止读已下线的 OT 库存投影列。 """ + from app import db + from app.models import ShippingOrderTask from app.services.shipping_notice.inventory_candidate_projection import ( project_inventory_candidate_facts, ) @@ -369,26 +434,26 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - status = str(task.inventory_source_status or '').strip() - method = str(task.inventory_source_method or '').strip() - resolutions_raw = payload.get('line_inventory_resolutions') - resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else [] - multi_block = bool(payload.get('multi_source_excel_block')) - candidate_projection = project_inventory_candidate_facts(task) - frozen_codes = ( - list(candidate_projection.get('candidate_source_codes') or []) - or list( - (payload.get('line_inventory_candidates') or {}).get('source_codes') or [] - ) - or task_frozen_inventory_source_codes(task) + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + + candidate_projection = ( + project_inventory_candidate_facts(owner) + if getattr(owner, 'id', None) is not None else { + 'current_set': None, + 'candidate_source_codes': [], + 'line_resolutions': [], + } ) + status = 'candidates_frozen' if candidate_projection.get('current_set') else '' + method = 'candidate_set' if candidate_projection.get('current_set') else '' + frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(owner) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') or bool(frozen_codes) - or bool(resolutions) - or multi_block + or bool(candidate_projection.get('blocking_reason')) or bool(candidate_projection.get('current_set')) ) if not has_stp: @@ -396,19 +461,38 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: counts: dict[str, int] = {} compact_resolutions: list[dict[str, Any]] = [] - resolution_source = list(candidate_projection.get('line_resolutions') or []) or resolutions + resolution_source = list(candidate_projection.get('line_resolutions') or []) + if not resolution_source and getattr(owner, 'id', None) is not None: + from app.models import ShippingNoticeLineInventoryMatch + + resolution_source = [{ + 'line_index': row.line_index, + 'line_no': row.line_no, + 'disposition': row.match_result, + 'effective_reservation_id': row.reservation_id, + 'part_number': row.part_number, + 'resolved_inventory_source_code': row.inventory_source_code, + 'inventory_file_no': row.matched_file_no, + 'inventory_row_index': row.matched_row_index, + 'match_attempt_id': row.match_attempt_id, + 'required_qty': row.required_qty, + 'matched_qty': row.matched_qty or row.available_qty, + 'shortage_qty': row.shortage_qty, + 'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'), + } for row in ShippingNoticeLineInventoryMatch.query.filter_by( + task_id=int(owner.id), is_current=True, + ).order_by(ShippingNoticeLineInventoryMatch.line_no, ShippingNoticeLineInventoryMatch.id).all()] for item in resolution_source: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 compact_resolutions.append({ 'line_index': item.get('line_index'), - 'line_key': item.get('line_key'), + 'line_no': item.get('line_no'), 'disposition': disposition, 'effective_reservation_id': item.get('effective_reservation_id'), 'part_number': item.get('part_number'), 'resolved_inventory_source_code': item.get('resolved_inventory_source_code'), 'inventory_file_no': item.get('inventory_file_no'), - 'inventory_file_sha256': item.get('inventory_file_sha256'), 'inventory_row_index': item.get('inventory_row_index'), 'match_attempt_id': item.get('match_attempt_id'), 'required_qty': item.get('required_qty'), @@ -417,10 +501,19 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'inventory_row_ref': item.get('inventory_row_ref'), }) - recovery_codes = multi_source_recovery_source_codes(task) + recovery_codes = multi_source_recovery_source_codes(owner) + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} + multi_block = bool(payload.get('multi_source_excel_block')) + if not multi_block: + # 行级 source_conflict 与旧 payload 标志等价,摘要暂停原因须同源。 + multi_block = any( + str(item.get('disposition') or '').strip().lower() == 'source_conflict' + for item in compact_resolutions + ) facts = { 'inventory_source_status': status or None, - 'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None, + 'inventory_source_code': None, 'inventory_source_method': method or None, 'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()], 'candidate_set_id': candidate_projection.get('candidate_set_id'), @@ -440,53 +533,63 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: if str(code or '').strip() ], 'recovery_source_codes': recovery_codes, - 'match_status': str(task.match_status or '').strip() or None, + # 订单任务的库存匹配状态只由行级 Match 聚合;不得读取 OT match_status 投影。 + 'match_status': None, } return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts} def _build_task_summary( task: ShippingNotice, - checkpoint: str | None, + position: str | None, *, - checkpoint_kind: CheckpointKind, + user_mode: UserMode | str, + gate_code: str | None = None, ) -> dict[str, Any]: """ 输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。 - 核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、 - pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts、 - progress_nodes(固定节点顺序,禁止前端算百分比)。 + 核心逻辑:文案与入口由 position/user_mode(Gate 或 review 回退)驱动。 """ - title = user_facing_task_stage(task) - message_by_checkpoint: dict[str, str] = { - CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。", - CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", - CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。", - CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", - CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。", - CP_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。", - CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。", + effective_position = str(position or '').strip() or None + effective_mode = str(user_mode or '').strip() or str(UserMode.AUTO_CONTINUE) + # [PERF] position 已由 Gate 派生时优先用标签表,避免 user_facing_task_stage 再查 Gate。 + title = ( + user_facing_stage_label_for_position(task, position=effective_position) + or user_facing_task_stage(task) + ) + message_by_position: dict[str, str] = { + POSITION_PARSE_REVIEW: "解析结果需要人工确认后才能继续。", + POSITION_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", + POSITION_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。", + POSITION_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", + POSITION_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。", + POSITION_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。", + POSITION_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。", RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", - CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。", - CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", - CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", - CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", - CP_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", - CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", - CP_REJECTED: "任务已驳回,无需继续处理。", - CP_UPLOADED: "任务已完成上传。", - CP_COMPLETED: "任务已关闭。", + POSITION_READY_MATCH: "库存已就绪,系统将自动执行匹配。", + POSITION_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", + POSITION_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + POSITION_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + POSITION_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", + POSITION_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", + POSITION_REJECTED: "任务已驳回,无需继续处理。", + POSITION_UPLOADED: "任务已完成上传。", + POSITION_COMPLETED: "任务已关闭。", } - issues = _collect_parse_stage_issues(task, checkpoint) - pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) - pause_reason_code = pause[0] if pause else (task.pending_human_reason or None) - pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None) - message = message_by_checkpoint.get(str(checkpoint or ""), title) + issues = _collect_parse_stage_issues(task, effective_position) + pause = _PAUSE_REASON_BY_POSITION.get(str(effective_position or "")) + pause_reason_code = pause[0] if pause else getattr(task, 'pending_human_reason', None) + pause_reason = pause[1] if pause else ( + getattr(task, 'error_message', None) + or getattr(task, 'upload_error_message', None) + or None + ) + message = message_by_position.get(str(effective_position or ""), title) stp_facts = _build_stp_facts(task) current_todo_override: str | None = None + is_auto = effective_mode in {'auto_continue', str(UserMode.AUTO_CONTINUE)} - # [STEP] STP 多源 Excel 阻断:覆盖通用 shortage 文案,并提示可指定库存源。 if stp_facts and stp_facts.get('multi_source_excel_block'): pause_reason_code = 'multi_source_excel_block' pause_reason = '订单行命中多个不同库存源,首期无法生成单一发货 Excel,请拆单或人工指定库存源后继续' @@ -496,51 +599,164 @@ def _build_task_summary( if issue_text not in issues: issues = [*issues, issue_text] current_todo_override = '请拆单或人工指定库存源后继续' - elif stp_facts and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' and checkpoint_kind == CheckpointKind.AUTO_CONTINUE: + elif ( + stp_facts + and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' + and is_auto + ): message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。' - if checkpoint_kind == CheckpointKind.AUTO_CONTINUE and not (stp_facts and stp_facts.get('multi_source_excel_block')): + if is_auto and not (stp_facts and stp_facts.get('multi_source_excel_block')): pause_reason = None pause_reason_code = None event_at = None if task.updated_at is not None: event_at = task.updated_at.isoformat() + try: + mode_enum = UserMode(effective_mode) + except ValueError: + mode_enum = UserMode.AUTO_CONTINUE + entry_surface = ( + _derived_entry_surface( + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + user_mode=effective_mode, + position=effective_position, + ) + if (gate_code or position or user_mode) + else _entry_surface_for(effective_position, mode_enum) + ) + # 多库存源冲突必须进人工作台处理,不能因位置仍是 auto inventory_pending 落到 none。 + if stp_facts and stp_facts.get('multi_source_excel_block'): + entry_surface = 'task_workbench' summary: dict[str, Any] = { "title": title, "message": message, - "error_message": task.error_message or task.upload_error_message, + "error_message": ( + getattr(task, 'error_message', None) + or getattr(task, 'upload_error_message', None) + ), "issues": issues, "stage": title, - "checkpoint_kind": str(checkpoint_kind), + "user_mode": effective_mode, "current_todo": ( current_todo_override if current_todo_override is not None else ( pause_reason if stp_facts and stp_facts.get('multi_source_excel_block') - else _current_todo_label(checkpoint) + else ( + _derived_current_todo(position=effective_position) + if effective_position + else _current_todo_label(effective_position) + ) ) ), "pause_reason": pause_reason, "pause_reason_code": pause_reason_code, "next_auto_step": ( - _NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or "")) - if checkpoint_kind == CheckpointKind.AUTO_CONTINUE + _NEXT_AUTO_STEP_BY_POSITION.get(str(effective_position or "")) + if is_auto else None ), "event_at": event_at, - "entry_surface": _entry_surface_for(checkpoint, checkpoint_kind), + "entry_surface": entry_surface, "allowed_actions": [], } if stp_facts is not None: summary['stp_facts'] = stp_facts - # [STEP] 对话侧固定节点梯;前端只渲染 status,不自行推导百分比。 from app.services.shipping_notice.stp_progress_contract import project_task_progress_nodes summary['progress_nodes'] = project_task_progress_nodes(task) return summary +# 通知准备「任务级可编辑」排除集:作废/归档/删除/待作废/取消视图只读。 +_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES = frozenset({ + 'voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled', +}) + + +def _preparation_editable(task: ShippingNotice) -> bool: + """ + 判定通知准备工作面是否允许任务级编辑/出单门控放行。 + + 核心逻辑:仅按 lifecycle_status 终态/历史视图排除;active/blocked/空值可操作。 + Gate 阻断不在此谓词收紧。 + """ + status = str(getattr(task, 'lifecycle_status', None) or '').strip().lower() + return status not in _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES + + +def _stage_capabilities_for_task( + task: Any, + *, + lifecycle_stage: str | None, + preparation: dict[str, Any], + source_locked: bool, +) -> list[dict[str, Any]]: + """ + 按阶段能力契约计算通知准备阶段的常驻能力(enabled / disabled_reason)。 + + 核心逻辑:可用性 = 阶段 + Excel 未生成 + 数据谓词,不由门禁通过与否决定。 + 预条件:改源→有候选源;重抓→有候选源或失败源;重读→已有抓取结果; + 重匹配→已有匹配结果。右卡展示仍只读处理投影 A;本列表仅供点击后 + ``stageCapabilityBypass`` 查找(见 display-and-button-contract §3.2)。 + + Args: + task: Notice 或 OT(能力计算不读实体字段,保留形参供调用方透传)。 + lifecycle_stage: 五阶段码;仅 ``fulfillment_prep`` 下发库存能力。 + preparation: 已装配的 preparation 摘要(含 source_options / failed / + resolved / has_match_result)。 + source_locked: Excel 已生成时全部能力禁用。 + + Returns: + 能力列表,每项含 code/scope/action_code/enabled/disabled_reason。 + """ + del task # 能力谓词只读 preparation 摘要,避免再查库。 + from app.services.shipping_notice.process_gate_contract import STAGE_CAPABILITY_DEFINITIONS + + result: list[dict[str, Any]] = [] + source_options = preparation.get('source_options') or [] + has_candidates = bool(source_options) + failed_codes = preparation.get('failed_source_codes') or [] + resolved_codes = preparation.get('resolved_source_codes') or [] + has_match_result = bool(preparation.get('has_match_result')) + + def disabled(reason: str) -> dict[str, Any]: + return {'enabled': False, 'disabled_reason': reason} + + for code, definition in STAGE_CAPABILITY_DEFINITIONS.items(): + if definition.get('stage') != lifecycle_stage: + continue + cap: dict[str, Any] = { + 'code': code, + 'scope': definition.get('scope'), + 'action_code': definition.get('action_code'), + 'enabled': False, + 'disabled_reason': None, + } + if source_locked: + cap.update(disabled('excel_locked')) + elif code == 'retry_inventory_preparation': + # 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。 + retry_available = has_candidates or bool(failed_codes) + cap['enabled'] = retry_available + cap['disabled_reason'] = None if retry_available else 'no_candidates' + elif code == 'override_line_inventory_source': + cap['enabled'] = has_candidates + cap['disabled_reason'] = None if has_candidates else 'no_candidates' + elif code == 'reload_inventory_result': + has_prior = bool(resolved_codes) + cap['enabled'] = has_prior + cap['disabled_reason'] = None if has_prior else 'no_prior_result' + elif code == 'retry_inventory_matching': + cap['enabled'] = has_match_result + cap['disabled_reason'] = None if has_match_result else 'no_match_result' + result.append(cap) + return result + + def _build_stage_context( task: ShippingNotice, *, @@ -550,149 +766,168 @@ def _build_stage_context( ) -> dict[str, Any]: """构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 - 通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成 - 只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。 + 通知准备以冻结 Snapshot 行为轴,合并当前行级 Match + project_line_inventory_view; + Snapshot / Match / CandidateSet / PrepAttempt 一律按 OT 读取(Notice 经 order_task_id); + 行级双字段:selected_source_code=CandidateSet 取数目标(单源才填), + source_code=Match 正式匹配源(禁止用候选回填,避免与匹配结论混淆); + 短缺行另投影发货模板放行字段;匹配成功无短缺行投影 can_fulfill_complete_line; + preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉; + preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染); + Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询; + inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。 """ + from app import db + from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask from app.models.shipping_excel_template import ShippingExportArtifact - from app.models.shipping_fulfillment import ( - ShippingInventoryVerification, - ShippingUploadAttempt, + from app.models.shipping_fulfillment import ShippingUploadAttempt + from app.core.errors import ConflictError + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.line_inventory_match_projection import ( + inventory_rpa_is_running, + load_current_match_facts_by_task, + project_line_inventory_view, ) - from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch - from app.models.shipping_notice_line import ShippingNoticeLine - - facts = stp_facts if isinstance(stp_facts, dict) else {} - raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else [] - fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else [] - fact_by_key = { - str(row.get('line_key') or ''): row - for row in fact_rows - if isinstance(row, dict) and str(row.get('line_key') or '') - } - # 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。 - current_match_rows = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=task.id, is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id) - .all() - if getattr(task, 'id', None) is not None else [] - ) - match_by_key = { - str(row.line_key or ''): row - for row in current_match_rows - if str(row.line_key or '') - } - match_by_index = { - int(row.line_index): row - for row in current_match_rows - if row.line_index is not None - } - verification_rows: dict[str, dict[str, Any]] = {} - latest_verification = ( - ShippingInventoryVerification.query - .filter_by(task_id=task.id, status='completed') - .order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc()) - .first() - if getattr(task, 'id', None) is not None else None - ) - if latest_verification is not None: - # 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。 - for position, verification_line in enumerate(latest_verification.lines): - verification_rows[str(position)] = { - 'required_qty': verification_line.required_qty, - 'available_qty': verification_line.available_qty, - 'shortage_qty': ( - max(verification_line.required_qty - verification_line.available_qty, 0) - if verification_line.required_qty is not None and verification_line.available_qty is not None - else None - ), - 'status': verification_line.status, - } - # 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对 - # 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。 from app.services.shipping_notice.order_line_no_resolver import ( notice_line_field_id_map, - resolve_order_line_no_projection, + read_field_by_id, ) + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + _manual_required_release_fields, + _release_fact_identity, + _shortage_release_required_fields, + ) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + facts = stp_facts if isinstance(stp_facts, dict) else {} + # [STEP 1] Snapshot/Match/Candidate 归属 OT;Notice 详情入口必须经 order_task_id 解析, + # 禁止用 Notice.id 查 Match(否则改源/匹配已落库却投影为空行)。 + order_task = _resolve_order_task_for_gate_lookup(task) or task + has_formal_ot = isinstance(order_task, ShippingOrderTask) or getattr(order_task, 'order_snapshot_id', None) is not None + snapshot_id = getattr(order_task, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + snapshot_lines = ( + ShippingOrderSnapshotLine.query + .filter_by(snapshot_id=int(snapshot.id)) + .order_by(ShippingOrderSnapshotLine.position, ShippingOrderSnapshotLine.id) + .all() + if snapshot is not None else [] + ) + match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None)) + # [STEP] 与 Case 投影同源:库存 RPA 运行态只查一次 Attempt(请求内 memo),再传入各行纯函数。 + inventory_rpa_running = inventory_rpa_is_running(order_task) + candidate_codes_by_line_no: dict[int, list[str]] = {} + if getattr(order_task, 'id', None) is not None and isinstance(order_task, ShippingOrderTask): + for candidate_line in get_active_candidate_lines(order_task): + try: + line_no_key = int(getattr(candidate_line, 'line_no', 0) or 0) + except (TypeError, ValueError): + line_no_key = 0 + if line_no_key < 1: + continue + candidate_codes_by_line_no[line_no_key] = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code or '').strip() + ] + field_id_by_code = notice_line_field_id_map(order_task) - line_no_field_id_by_code = notice_line_field_id_map(task) frozen_order_lines: list[dict[str, Any]] = [] preparation_lines: list[dict[str, Any]] = [] - notice_lines = ( - ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all() - if getattr(task, 'id', None) is not None else [] - ) - for line in notice_lines: + for snapshot_line in snapshot_lines: + qty_text = str(snapshot_line.qty) if snapshot_line.qty is not None else None + line_no = int(snapshot_line.line_no) if snapshot_line.line_no is not None else None frozen_order_lines.append({ - 'line_key': getattr(line, 'line_key', None), - **resolve_order_line_no_projection( - field_values=dict(getattr(line, 'field_values_json', None) or {}), - field_id_by_code=line_no_field_id_by_code, - fallback_sequence=(int(line.position) + 1) if line.position is not None else None, - ), - 'reservation_id': getattr(line, 'reservation_id', None), - 'part_number': getattr(line, 'part_number', None), - 'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None, + 'snapshot_line_id': int(snapshot_line.id), + 'line_no': line_no, + 'reservation_id': snapshot_line.reservation_id, + 'part_number': snapshot_line.part_number, + 'required_qty': qty_text, }) - - # 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON - # 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。 - row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows)) - for index in range(row_count): - line = notice_lines[index] if index < len(notice_lines) else None - match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index) - structured = ({ - 'line_key': match_row.line_key, - 'reservation_id': match_row.reservation_id, - 'part_number': match_row.part_number, - 'required_qty': match_row.required_qty, - 'available_qty': match_row.matched_qty or match_row.available_qty, - 'shortage_qty': match_row.shortage_qty, - 'resolved_inventory_source_code': match_row.inventory_source_code, - 'disposition': match_row.match_result, - } if match_row is not None else {}) - legacy_source = fact_by_key.get( - str(getattr(line, 'line_key', '') or ''), - fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {}, + fact = match_by_snapshot_line_id.get(int(snapshot_line.id)) + required_qty = (fact or {}).get('required_qty') + if required_qty is None: + required_qty = qty_text + inv_view = project_line_inventory_view( + has_formal_ot=has_formal_ot, + fact=fact, + required_qty=required_qty, + stored_line_status=None, + decision_source=None, + can_fulfill_complete_line=False, + inventory_rpa_running=inventory_rpa_running, + ) + allowed = list((fact or {}).get('allowed_source_codes_snapshot') or []) + candidate_codes = candidate_codes_by_line_no.get(int(line_no), []) if line_no is not None else [] + # [STEP] 双字段真相:Match 正式源 vs CandidateSet 取数目标,禁止互相回填。 + source_code = (fact or {}).get('inventory_source_code') or ( + allowed[0] if len(allowed) == 1 else None + ) + selected_source_code = candidate_codes[0] if len(candidate_codes) == 1 else None + source_ambiguous = ( + str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict' + or (len(allowed) > 1 and not (fact or {}).get('inventory_source_code')) + or (fact is None and len(candidate_codes) > 1) + ) + source_candidates = ( + allowed if str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict' or len(allowed) > 1 + else (candidate_codes if source_ambiguous else []) + ) + # [STEP] 短缺行复用 Case 同款模板字段判定;解析失败 fail-closed,禁止只填原因放行。 + release_template_fields: list[dict[str, Any]] = [] + release_field_resolution_error: str | None = None + if bool(inv_view.get('is_shortage')): + try: + release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact) + if release_line_index is None and getattr(snapshot_line, 'position', None) is not None: + release_line_index = int(snapshot_line.position) + release_template_fields = _shortage_release_required_fields( + task=order_task, + line_index=release_line_index, + inventory_snapshot_id=release_snapshot_id, + inventory_source_code=release_source_code or source_code or selected_source_code, + ) + except ConflictError as exc: + release_field_resolution_error = exc.code + # [STEP] 正式 OT 行可履约 = 匹配成功且无短缺;供前端波次勾选(「生成发货通知和 Excel (N 行)」)。 + can_fulfill_complete_line = ( + str(inv_view.get('user_line_status') or '').strip() == 'inventory_matched' + and not bool(inv_view.get('is_shortage')) ) - # 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。 - source = { - **(legacy_source if isinstance(legacy_source, dict) else {}), - **{ - key: value - for key, value in structured.items() - if value is not None and value != '' - }, - } - verification = verification_rows.get(str(index), {}) - result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {} - required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None)))) - available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty')))) - shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty'))) preparation_lines.append({ - 'line_key': getattr(line, 'line_key', None) or source.get('line_key'), - **resolve_order_line_no_projection( - field_values=dict(getattr(line, 'field_values_json', None) or {}) if line is not None else None, - field_id_by_code=line_no_field_id_by_code, - fallback_sequence=index + 1, + 'snapshot_line_id': int(snapshot_line.id), + 'line_no': line_no, + 'customer_po_line_no': read_field_by_id( + dict(snapshot_line.field_values_json or {}), + field_id_by_code, + 'customer_po_line_no', ), - 'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None), - 'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None), + 'reservation_id': (fact or {}).get('reservation_id') or snapshot_line.reservation_id, + 'part_number': (fact or {}).get('part_number') or snapshot_line.part_number, 'required_qty': required_qty, - 'available_qty': available_qty, - 'shortage_qty': shortage_qty, - 'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'), - 'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None, + 'available_qty': inv_view.get('available_qty'), + 'shortage_qty': inv_view.get('shortage_qty'), + 'source_code': source_code, + 'selected_source_code': selected_source_code, + 'status': inv_view.get('user_line_status'), + 'source_ambiguous': source_ambiguous, + 'source_candidates': source_candidates, + 'is_shortage': bool(inv_view.get('is_shortage')), + 'user_line_status': inv_view.get('user_line_status'), + 'can_fulfill_complete_line': can_fulfill_complete_line, + 'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []), + 'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []), + 'inventory_file_no': inv_view.get('inventory_file_no'), + 'release_template_fields': release_template_fields, + 'release_required_fields': _manual_required_release_fields(release_template_fields), + 'release_field_resolution_error': release_field_resolution_error, + 'decision': None, }) - has_match_result = bool(current_match_rows or raw_rows or any( - row.get('matched_qty') is not None - or row.get('shortage_qty') is not None - or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage', 'released'} - for row in fact_rows if isinstance(row, dict) - )) + has_match_result = bool(match_by_snapshot_line_id) gate = process_gate if isinstance(process_gate, dict) else {} - gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '') + gate_code = str( + (gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '' + ) preparation_status = ( 'ready' if has_match_result else 'blocked' if gate_code else @@ -701,19 +936,19 @@ def _build_stage_context( inventory_sources: list[dict[str, Any]] = [] latest_preparation = None - if getattr(task, 'id', None): + if getattr(order_task, 'id', None): from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt latest_preparation = ( ShippingInventoryPreparationAttempt.query - .filter_by(task_id=task.id) + .filter_by(task_id=int(order_task.id)) .filter(ShippingInventoryPreparationAttempt.status != 'superseded') .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) .first() ) from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download - downloadable_inventory = resolve_task_inventory_download(task) + downloadable_inventory = resolve_task_inventory_download(order_task) for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []): inventory_sources.append({ 'source_code': source_attempt.source_code, @@ -721,6 +956,18 @@ def _build_stage_context( 'inventory_file_id': source_attempt.inventory_file_id, }) + # [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。 + from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + + source_options = [ + { + 'source_code': str(item.get('source_code') or '').strip().upper(), + 'display_name': str(item.get('display_name') or '') or str(item.get('source_code') or ''), + } + for item in list_database_inventory_sources(enabled_only=True) + if str(item.get('source_code') or '').strip() + ] + artifact = None attempts = [] if getattr(task, 'id', None): @@ -747,30 +994,48 @@ def _build_stage_context( 'awaiting_manual' if lifecycle_stage == 'freight_upload' else 'not_started' ) - return { - 'preparation': { - 'status': preparation_status, - 'reason_code': gate.get('blocking_reason_code') or None, - 'frozen_order': { - 'task_no': task.task_no, - 'snapshot_id': task.order_snapshot_id, - }, - 'inventory_source_code': facts.get('inventory_source_code'), - 'match_status': facts.get('match_status'), - 'frozen_order_lines': frozen_order_lines, - 'lines': preparation_lines, - 'has_match_result': has_match_result, - # 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。 - 'inventory_sources': inventory_sources, - 'inventory_file': { - 'available': downloadable_inventory is not None, - 'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None, - }, - 'artifact': { - 'file_name': artifact.file_name if artifact is not None else None, - 'status': artifact.status if artifact is not None else 'not_generated', - }, + source_locked = latest_export_artifact(task) is not None or latest_export_artifact(order_task) is not None + # [STEP] 先装配 preparation 再追加 capabilities,避免字面量自引用。 + preparation = { + 'status': preparation_status, + 'reason_code': gate.get('blocking_reason_code') or None, + 'editable': _preparation_editable(task), + 'source_locked': source_locked, + 'frozen_order': { + 'task_no': getattr(order_task, 'task_no', None) or task.task_no, + 'snapshot_id': snapshot_id, }, + 'inventory_source_code': facts.get('inventory_source_code'), + 'match_status': facts.get('match_status'), + 'frozen_order_lines': frozen_order_lines, + 'lines': preparation_lines, + 'has_match_result': has_match_result, + # 任务级 inventory_sources 只说明取数进度;行级看 selected_source_code / source_code。 + 'inventory_sources': inventory_sources, + # 供阶段能力预条件:失败可重试源 / 已有抓取结果。 + 'failed_source_codes': [ + item['source_code'] for item in inventory_sources + if str(item.get('status') or '').strip().lower() == 'failed' + ], + 'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []), + 'source_options': source_options, + 'inventory_file': { + 'available': downloadable_inventory is not None, + 'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None, + }, + 'artifact': { + 'file_name': artifact.file_name if artifact is not None else None, + 'status': artifact.status if artifact is not None else 'not_generated', + }, + } + preparation['capabilities'] = _stage_capabilities_for_task( + task, + lifecycle_stage=lifecycle_stage, + preparation=preparation, + source_locked=source_locked, + ) + return { + 'preparation': preparation, 'upload': { 'outcome': upload_outcome, # 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能 @@ -802,21 +1067,34 @@ def build_task_ui_state( """ 构建单票任务 UI State。 - 核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary, - 禁止 Chat、通知卡与任务中心分别推导状态;checkpoint 仅保留内部状态/自动推进, + 核心逻辑:所有 UI 入口只消费这里输出的 stage/position/user_mode/todo/actions/summary, + 禁止 Chat、通知卡与任务中心分别推导状态; 可点击用户动作只由 Gate 与已验证 Artifact 授权产生。 + Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。 """ - ui = resolve_task_ui_state(task) + from app.services.shipping_notice.state_machine import ( + _review_status_fallback_ui_state, + _ui_state_from_process_gate, + ) + process_gate = _process_gate_user_summary_for_task(task) - lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate) + ui = _ui_state_from_process_gate(task, process_gate) + if ui is None: + # 与 resolve_task_ui_state 无 Gate 分支同源:仅 review_status 薄回退。 + ui = _review_status_fallback_ui_state(task) + lifecycle = _task_lifecycle(task=task, position=ui.position, process_gate=process_gate) stage = _business_stage(lifecycle) - steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code']) + steps = build_shipping_workflow_steps(task, ui.position, lifecycle_stage=stage['code']) current_index = int(stage['index']) - 1 current_step = steps[current_index] if 0 <= current_index < len(steps) else None summary = _build_task_summary( task, - ui.checkpoint, - checkpoint_kind=ui.checkpoint_kind, + ui.position, + user_mode=ui.user_mode, + gate_code=( + process_gate.get('current_gate_code') + if isinstance(process_gate, dict) else None + ), ) if process_gate is not None: summary['process_gate'] = process_gate @@ -831,7 +1109,7 @@ def build_task_ui_state( summary['allowed_actions'] = [] actions = _unified_actions(process_gate=process_gate) # [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作, - # 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在 + # 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在 # Artifact 已通过 resolve_task_export_download 校验时补入下载授权。 if resolve_task_export_download(task) is not None: download_action = _unified_action({ @@ -842,7 +1120,7 @@ def build_task_ui_state( 'ui_handler': 'excel_download', 'enabled': True, # Artifact 已验证是下载授权的唯一来源;它直接声明展示位置, - # 不依赖旧 checkpoint 或 action code 位置映射。 + # 不依赖旧位置码或 action code 位置映射。 'target_surface': 'freight_upload', 'target_anchor': 'excel_artifact', }, default_kind='view') @@ -858,7 +1136,7 @@ def build_task_ui_state( # 同 PO 成功通知明细与批次 ZIP 的只读留档入口。 process_gate = None actions = {'primary': None, 'secondary': []} - # summary 仅作为 ui_state.actions 的只读镜像,禁止由 checkpoint 或任务字段另行推导。 + # summary 仅作为 ui_state.actions 的只读镜像,禁止由位置码或任务字段另行推导。 summary['allowed_actions'] = [ str(item.get('code')) for item in [actions.get('primary'), *(actions.get('secondary') or [])] @@ -873,11 +1151,6 @@ def build_task_ui_state( ) if include_stage_context else None ) - checkpoint_payload = { - "code": ui.checkpoint, - "kind": str(ui.checkpoint_kind), - "label": str(ui.checkpoint or "") or None, - } reason = None if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"): reason = { @@ -890,8 +1163,8 @@ def build_task_ui_state( "lifecycle_stage": stage["code"], "lifecycle_entries": lifecycle['lifecycle_entries'], "lifecycle_authority": lifecycle['lifecycle_authority'], - "checkpoint": checkpoint_payload, - "checkpoint_view": checkpoint_payload, + "position": ui.position, + "user_mode": str(ui.user_mode), "todo": { "title": summary.get("current_todo") or summary.get("title"), "message": summary.get("message"), @@ -900,12 +1173,11 @@ def build_task_ui_state( # 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。 **({'stage_context': stage_context} if stage_context is not None else {}), "reason": reason, - "lifecycle_status": task.lifecycle_status, - "checkpoint_code": ui.checkpoint, - "checkpoint_kind": str(ui.checkpoint_kind), - "review_status": task.review_status, - "pending_human_reason": task.pending_human_reason, - "match_status": task.match_status, + # OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。 + "lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None), + "review_status": getattr(task, "review_status", None), + "pending_human_reason": getattr(task, "pending_human_reason", None), + "match_status": getattr(task, "match_status", None), "current_step": current_step, "steps": steps, "summary": summary, @@ -914,42 +1186,107 @@ def build_task_ui_state( } -def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: +def _resolve_order_task_for_gate_lookup(task: Any): """ - 按 Task 查找活动 Execution 的用户 Gate 摘要。 + 解析 Execution.task_id 对应的正式 OT。 - 核心逻辑:Task 本身即正式 OT,套用 apply_post_ot_gate_rules, - 使 inventory_preparation 等系统等待不进入 current_blocking_gate。 + 核心逻辑:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id。 + 入参可能是 ShippingOrderTask,或挂有 order_task_id 的 ShippingNotice; + Artifact.task_id 才是 Notice 主键,禁止用 Notice.id 查 Execution。 + + Args: + task: ShippingOrderTask 或 ShippingNotice(及具备 order_task_id 的兼容对象)。 Returns: - 用户态 Gate 摘要;无 Execution 时 None。 + 正式 OT;Notice 未绑定 OT 时 None。 """ + from app import db + from app.models import ShippingOrderTask + + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is None: + return None + try: + return db.session.get(ShippingOrderTask, int(order_task_id)) + except (TypeError, ValueError): + return None + + +def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: + """ + 按正式 OT 查找活动 Execution 的用户 Gate 摘要。 + + 核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读 + active_process_execution_id,回退按 OT.id 取最新非 superseded Execution; + 套用 apply_post_ot_gate_rules,使 inventory_preparation 等系统等待 + 不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。 + 同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。 + + Returns: + 用户态 Gate 摘要;无 OT / Execution 时 None。 + """ + from app import db from app.models import ShippingProcessExecution from app.services.shipping_notice.order_review_workbench_projection import ( apply_post_ot_gate_rules, ) from app.services.shipping_notice.process_gate_projection import project_user_gate_summary - task_id = getattr(task, 'id', None) - if task_id is None: - return None + cache_key = ( + type(task).__name__, + getattr(task, 'id', None), + str(getattr(task, 'task_no', '') or ''), + ) try: - task_pk = int(task_id) - except (TypeError, ValueError): - return None - execution = ( - ShippingProcessExecution.query - .filter_by(task_id=task_pk) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() - ) - if execution is None: - return None - return apply_post_ot_gate_rules( - project_user_gate_summary(execution), - has_formal_ot=True, - ) + from flask import g, has_app_context, has_request_context + if has_app_context() and has_request_context(): + cache = getattr(g, '_shipping_process_gate_summary_by_task', None) + if cache is None: + cache = {} + g._shipping_process_gate_summary_by_task = cache + if cache_key in cache: + return cache[cache_key] + else: + cache = None + except Exception: + cache = None + + # [STEP 1] Notice→OT:Execution.task_id 只认 shipping_order_tasks.id。 + order_task = _resolve_order_task_for_gate_lookup(task) + if order_task is None or getattr(order_task, 'id', None) is None: + result = None + else: + # [STEP 2] 与 processing_projection 同源:优先活跃指针,再回退最新活跃 Execution。 + execution = None + active_execution_id = getattr(order_task, 'active_process_execution_id', None) + if active_execution_id is not None: + execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) + if execution is not None and ( + int(getattr(execution, 'task_id', 0) or 0) != int(order_task.id) + or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' + ): + execution = None + if execution is None: + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(order_task.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + result = None + else: + result = apply_post_ot_gate_rules( + project_user_gate_summary(execution), + has_formal_ot=True, + ) + + if cache is not None: + cache[cache_key] = result + return result def project_notice_available_actions(task: ShippingNotice) -> list[str]: diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index eb4294a1..af164ed8 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -1,9 +1,13 @@ """ services/shipping_notice/upload_attempt_service.py -用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。 -依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。 -逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。 +用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认;并提供 + Notice 面 upload_status / facts.upload_state 的唯一投影归一。 +依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机、 + process_gate_contract.PROJECTION_UPLOAD_STATES(facts 词汇)。 +逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded。 + Attempt 内成功词为 succeeded,Artifact 为 uploaded;对外 API 字段经 + project_notice_upload_status 统一为 uploaded,禁止调用方再扩同义词集合。 """ from __future__ import annotations @@ -22,9 +26,26 @@ from app.models import ( ShippingUploadAttempt, ) +# Attempt 在途词 → Notice 面 uploading;成功词在投影内按层翻译,不对外暴露别名。 +_UPLOAD_IN_FLIGHT_TOKENS = frozenset({'running', 'uploading', 'triggered', 'queued'}) + + +def _formal_notice(task: ShippingNotice | Any) -> ShippingNotice | None: + """解析上传事实所属的正式 Notice;OT 在 Notice 生成前不产生上传事实。""" + if isinstance(task, ShippingNotice): + return task if getattr(task, 'id', None) is not None else None + order_task_id = getattr(task, 'id', None) + if order_task_id is None: + return None + return ShippingNotice.query.filter_by(order_task_id=int(order_task_id)).order_by( + ShippingNotice.id.desc(), + ).first() + def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact: """返回本次上传目标 Artifact;调用方不能借 Task 旧文件指针绕过分轮履约。""" + if not isinstance(task, ShippingNotice) or getattr(task, 'id', None) is None: + raise ValidationError('Formal shipping notice is required before upload', code='SHIPPING.NOTICE_REQUIRED') query = ShippingExportArtifact.query.filter_by(task_id=task.id) if artifact_id is not None: artifact = query.filter_by(id=artifact_id).one_or_none() @@ -68,24 +89,107 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i return attempt -def _aggregate_task_upload_status(task: ShippingNotice) -> None: - """从预约单真相刷新兼容 Task 投影,不能由单个旧回调直接覆盖。""" - reservations = ShippingReservation.query.filter_by(task_id=task.id).all() - if reservations and all(item.status == 'uploaded' for item in reservations): - task.upload_status = 'uploaded' - task.upload_finished_at = datetime.utcnow() - elif any(item.status == 'uploaded' for item in reservations): - task.upload_status = 'partial' - else: - task.upload_status = 'pending' +def latest_export_artifact(task: ShippingNotice) -> ShippingExportArtifact | None: + """返回当前 Notice 最新有效导出 Artifact;不回读 Notice 的旧文件投影。""" + notice = _formal_notice(task) + if notice is None: + return None + return ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id == notice.id, + ShippingExportArtifact.status.in_({'ready', 'uploading', 'uploaded'}), + ).order_by( + ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), + ).first() + + +def latest_upload_attempt(task: ShippingNotice) -> ShippingUploadAttempt | None: + """返回当前 Notice 最近一次有效 Artifact 的最近上传尝试。""" + artifact = latest_export_artifact(task) + if artifact is None: + return None + return ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).order_by( + ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc(), + ).first() + + +def project_notice_upload_status(task: ShippingNotice | Any) -> str | None: + """投影 Notice 面 upload_status(货代聚合/任务详情对外字段)。 + + 核心逻辑:优先读最新 Attempt,缺则回退 Artifact。 + Attempt 成功词 succeeded、Artifact 成功词 uploaded → 一律输出 uploaded。 + 调用方只允许判断 ``== 'uploaded'`` 或使用 has_verified_upload_success;禁止再读 Attempt 原词做成败。 + + Args: + task: 正式 Notice,或可解析到 Notice 的 OT。 + + Returns: + uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。 + """ + attempt = latest_upload_attempt(task) + if attempt is not None: + status = str(getattr(attempt, 'status', None) or '').strip().lower() + # Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。 + if status == 'succeeded': + return 'uploaded' + if status in _UPLOAD_IN_FLIGHT_TOKENS: + return 'uploading' + if status == 'pending': + return 'pending' + if status == 'failed': + return 'failed' + if status in {'timed_out', 'unknown'}: + return 'unknown' + return status or None + + artifact = latest_export_artifact(task) + if artifact is None: + return None + status = str(getattr(artifact, 'status', None) or '').strip().lower() + if status == 'uploaded': + return 'uploaded' + if status == 'uploading': + return 'uploading' + if status == 'ready': + return 'pending' + return status or None + + +def project_facts_upload_state(task: ShippingNotice | Any) -> str: + """投影 facts.upload_state,取值必须落在 PROJECTION_UPLOAD_STATES。 + + 核心逻辑:与 Notice upload_status 同源读取;成功按 facts 契约输出 succeeded + (Attempt.succeeded / Artifact.uploaded → succeeded)。 + + Args: + task: 正式 Notice 或可解析到 Notice 的 OT。 + + Returns: + not_created | uploading | succeeded | failed | manual_upload_pending。 + """ + attempt = latest_upload_attempt(task) + artifact = latest_export_artifact(task) + if attempt is None: + if artifact is not None and str(getattr(artifact, 'status', None) or '').strip().lower() == 'uploaded': + return 'succeeded' + return 'not_created' + status = str(getattr(attempt, 'status', None) or '').strip().lower() + if status == 'succeeded': + return 'succeeded' + if status in _UPLOAD_IN_FLIGHT_TOKENS or status == 'pending': + return 'uploading' + if status == 'failed': + return 'failed' + if status in {'timed_out', 'unknown'}: + return 'manual_upload_pending' + return 'not_created' def has_verified_upload_success(task: ShippingNotice) -> bool: """判断任务是否具备可审计的货代上传成功事实。 - 业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、 - 单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 - 已完成分组与停止轮询共用的唯一成功谓词。 + 当前 Excel Artifact 标为 uploaded 即代表 Notice 业务完成;成功 Attempt 只作为上传 + 审计证据。预约单属于行级履约事实,不参与 Notice 完成判定。该函数是 UI 生命周期、 + 批次已完成分组与停止轮询共用的唯一成功谓词。 """ try: from flask import has_app_context @@ -99,18 +203,15 @@ def has_verified_upload_success(task: ShippingNotice) -> bool: 'voided', 'archived', 'deleted', 'cancelled', }: return False - if getattr(task, 'id', None) is None or str(task.upload_status or '').strip().lower() != 'uploaded': + # OT 在正式 Notice 创建前没有上传字段;只能由正式 Notice 进入该谓词。 + if not isinstance(task, ShippingNotice): return False - reservations = ShippingReservation.query.filter_by(task_id=task.id).all() - if not reservations or any(row.status != 'uploaded' for row in reservations): + if getattr(task, 'id', None) is None: return False - return db.session.query(ShippingUploadAttempt.id).join( - ShippingExportArtifact, - ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, - ).filter( - ShippingExportArtifact.task_id == task.id, - ShippingUploadAttempt.status == 'succeeded', - ).first() is not None + artifact = latest_export_artifact(task) + if artifact is None or artifact.status != 'uploaded': + return False + return True def _normalize_callback_result(result: str | None, success: bool) -> str: @@ -180,11 +281,8 @@ def complete_attempt( ShippingReservation.query.filter(ShippingReservation.id.in_(reservation_ids)).update( {'status': 'uploaded'}, synchronize_session=False, ) - # 批量更新绕开 ORM identity map;立即失效以确保同一事务的 Task 聚合读取最新预约单状态。 + # 批量更新绕开 ORM identity map;立即失效以确保同一事务的预约单事实读取最新状态。 db.session.expire_all() - if task is not None: - task.freight_ref_no = attempt.freight_ref_no - _aggregate_task_upload_status(task) else: # A missing callback may conceal a completed freight submission. A late # transport error is not enough to safely release or retry that Artifact. @@ -200,11 +298,6 @@ def complete_attempt( error_message or '无法判断上传是否成功/失败:RPA 结果未确认,可能已上传成功但未出现成功提示,或上传配置(result_selector/success_texts)有误;请人工核查或确认已上传' )[:500] - # 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status, - # 因为迟到的成功回调仍可解除该未知态)。 - if task is not None: - task.upload_error_code = attempt.error_code - task.upload_error_message = attempt.error_message db.session.flush() return attempt attempt.status = 'failed' @@ -212,11 +305,6 @@ def complete_attempt( attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED' attempt.error_message = message artifact.status = 'ready' - if task is not None: - task.upload_status = 'failed' - # 逐单状态展示:把失败原因落到 Notice,供「按发货通知单展示状态」读取。 - task.upload_error_code = attempt.error_code - task.upload_error_message = message db.session.flush() return attempt diff --git a/backend/app/services/shipping_notice/user_facing_status.py b/backend/app/services/shipping_notice/user_facing_status.py index e7bc9af7..bbd9b3ef 100644 --- a/backend/app/services/shipping_notice/user_facing_status.py +++ b/backend/app/services/shipping_notice/user_facing_status.py @@ -2,26 +2,30 @@ services/shipping_notice/user_facing_status.py 用途:将任务 DB / 状态机内部码转为面向用户的中文阶段描述,并过滤 Tool 响应中的内部字段。 -依赖:models.ShippingNotice、constants、state_machine.resolve_task_ui_state。 -逻辑:get_task_status 与 tool_response 序列化时调用;STP 多源阻断优先于通用 shortage 文案。 +依赖:models.ShippingNotice、constants、process_gate_contract.derive_position、 + ui_state._process_gate_user_summary_for_task、state_machine.resolve_task_ui_state(回退)。 +逻辑:get_task_status 与 tool_response 序列化时调用;阶段标签优先 Gate position, + 无 Execution 时回退 ui.position;STP 多源阻断优先于通用 shortage 文案; + user_facing_stage_label_for_position 供已持有 position 的调用方免二次查 Gate。 """ from __future__ import annotations -from app.models import ShippingNotice +from app import db +from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_INVENTORY_PENDING, - CP_PARSE_REVIEW, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_COMPLETED, - CP_UPLOAD_FAILED, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, + POSITION_EXPORT_READY, + POSITION_INVENTORY_PENDING, + POSITION_PARSE_REVIEW, + POSITION_READY_EXPORT, + POSITION_READY_MATCH, + POSITION_REJECTED, + POSITION_RSV_REQ, + POSITION_UPLOADED, + POSITION_COMPLETED, + POSITION_UPLOAD_FAILED, + POSITION_UPLOAD_REQ, + POSITION_WAITING_UPLOAD, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_SHORTAGE, @@ -38,20 +42,23 @@ TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset( } ) -_CHECKPOINT_LABELS: dict[str, str] = { - CP_PARSE_REVIEW: "待确认发货通知解析", - CP_UPLOAD_REQ: "待上传或获取库存", - CP_INVENTORY_PENDING: "待上传库存", - CP_RSV_REQ: "待补充 Reservation ID", +# 键对齐 Gate derive_position / 位置标签。 +_POSITION_LABELS: dict[str, str] = { + POSITION_PARSE_REVIEW: "待确认发货通知解析", + POSITION_UPLOAD_REQ: "待上传或获取库存", + POSITION_INVENTORY_PENDING: "待上传库存", + POSITION_RSV_REQ: "待补充 Reservation ID", + "customer_review": "待确认客户", + "quality_issue": "质量异常待处理", "shortage_review": "库存不足,无法发货", - CP_READY_MATCH: "待匹配库存", - CP_READY_EXPORT: "待生成发货 Excel", - CP_EXPORT_READY: "待人工上传登记", - CP_WAITING_UPLOAD: "待人工上传登记", - CP_UPLOAD_FAILED: "货代上传失败,待处理", - CP_REJECTED: "任务已驳回", - CP_UPLOADED: "已完成上传", - CP_COMPLETED: "任务已完成", + POSITION_READY_MATCH: "待匹配库存", + POSITION_READY_EXPORT: "待生成发货 Excel", + POSITION_EXPORT_READY: "待人工上传登记", + POSITION_WAITING_UPLOAD: "待人工上传登记", + POSITION_UPLOAD_FAILED: "货代上传失败,待处理", + POSITION_REJECTED: "任务已驳回", + POSITION_UPLOADED: "已完成上传", + POSITION_COMPLETED: "任务已完成", } _PROCESS_STATUS_LABELS: dict[str, str] = { @@ -78,24 +85,83 @@ _PENDING_REASON_LABELS: dict[str, str] = { } +def user_facing_stage_label_for_position( + task: ShippingNotice, + *, + position: str | None, +) -> str | None: + """ + 在调用方已持有 position 时生成标题,避免再查 Gate。 + + 核心逻辑:多源阻断与 pending_human_reason 优先;否则用位置标签表。 + 无法判定时返回 None,由调用方回退 ``user_facing_task_stage``。 + + Args: + task: 任务实体(读 step_payload / pending_human_reason)。 + position: 已派生的位置码。 + + Returns: + 中文阶段标题;无法仅凭已知事实判定时为 None。 + """ + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} + if payload.get('multi_source_excel_block'): + return '多库存源冲突,待人工处理' + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + reason = str(task_blocking_reason(owner) or '').strip() + if reason in _PENDING_REASON_LABELS: + return _PENDING_REASON_LABELS[reason] + pos = str(position or '').strip() + if pos and pos in _POSITION_LABELS: + return _POSITION_LABELS[pos] + return None + + def user_facing_task_stage(task: ShippingNotice) -> str: """ Short Chinese label for chat / get_task_status — no snake_case codes. 核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending` - 这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖; + 这类细粒度状态被通用位置文案(如“待上传或获取库存”)覆盖; + 其次 Gate derive_position;无 Gate 回退 resolve_task_ui_state.position; STP 多源 Excel 阻断覆盖通用 shortage 文案。 """ - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + # Notice 只承载正式单据;流程/UI 状态归属关联 OT。 + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} if payload.get('multi_source_excel_block'): return '多库存源冲突,待人工处理' - reason = str(task.pending_human_reason or "").strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + reason = str(task_blocking_reason(owner) or '').strip() if reason in _PENDING_REASON_LABELS: return _PENDING_REASON_LABELS[reason] - ui = resolve_task_ui_state(task) - if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS: - return _CHECKPOINT_LABELS[ui.checkpoint] - return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束" + + # [STEP] Gate-first:位置标签查找。 + from app.services.shipping_notice.process_gate_contract import derive_position + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(owner) + if isinstance(gate, dict) and gate: + pos = derive_position( + gate_code=gate.get('current_gate_code'), + review_status=getattr(owner, 'review_status', None), + ) + if pos and pos in _POSITION_LABELS: + return _POSITION_LABELS[pos] + + ui = resolve_task_ui_state(owner) + if ui.position and ui.position in _POSITION_LABELS: + return _POSITION_LABELS[ui.position] + lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active") + return lifecycle == "active" and "处理中" or "已结束" def strip_internal_task_fields(data: dict) -> dict: diff --git a/backend/app/services/shipping_notice/workflow_ledger_service.py b/backend/app/services/shipping_notice/workflow_ledger_service.py index 654348f3..03f87138 100644 --- a/backend/app/services/shipping_notice/workflow_ledger_service.py +++ b/backend/app/services/shipping_notice/workflow_ledger_service.py @@ -336,11 +336,15 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool: Returns: True 表示已进入 matched 或更后阶段。 """ - match_status = str(getattr(task, 'match_status', None) or '').strip().lower() + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + match_status = aggregate_match_status_for_task(match_task_id) or '' + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + artifact = latest_export_artifact(task) + attempt = latest_upload_attempt(task) return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool( - str(getattr(task, 'export_file_path', None) or '').strip() - or str(getattr(task, 'freight_ref_no', None) or '').strip() - or str(getattr(task, 'upload_status', None) or '').strip() + str(getattr(artifact, 'file_path', None) or '').strip() + or str(getattr(attempt, 'status', None) or '').strip() ) diff --git a/backend/app/services/voucher_check/__init__.py b/backend/app/services/voucher_check/__init__.py index a303a55d..699c8411 100644 --- a/backend/app/services/voucher_check/__init__.py +++ b/backend/app/services/voucher_check/__init__.py @@ -3,7 +3,7 @@ backend/app/services/voucher_check/__init__.py 用途:立账凭证检核领域服务包入口。 依赖:config / runner / query_service 等子模块。 -逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。 +逻辑:platform Job 与工作台 API 从此包调用 runner 与查询能力。 """ from app.services.voucher_check.runner import run_voucher_check_batch diff --git a/backend/app/services/voucher_check/adapters/__init__.py b/backend/app/services/voucher_check/adapters/__init__.py new file mode 100644 index 00000000..9314e478 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/__init__.py @@ -0,0 +1,47 @@ +""" +backend/app/services/voucher_check/adapters/__init__.py + +用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。 +依赖:各 adapter 模块。 +逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。 +""" + +from app.services.voucher_check.adapters.base import ( + AcquireAdapter, + ArchiveAdapter, + DirectoryScanAdapter, + ScanOutcome, + ScannedFile, + SubjectAdapter, + SubjectRow, +) +from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter +from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter +from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter +from app.services.voucher_check.adapters.hxjm_apa_subject import HxjmApaSubjectAdapter +from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter +from app.services.voucher_check.adapters.registry import get_adapter, register_adapter, registered_adapter_names + +register_adapter("hxjm_apa", HxjmApaSubjectAdapter) +register_adapter("directory_scan", DmsDirectoryScanAdapter) +register_adapter("erp_po_print", ErpPoPrintAdapter) +register_adapter("oa_sales_release", OaSalesReleaseAdapter) +register_adapter("dms_archive", DmsArchiveAdapter) + +__all__ = [ + "AcquireAdapter", + "ArchiveAdapter", + "DirectoryScanAdapter", + "DmsArchiveAdapter", + "DmsDirectoryScanAdapter", + "ErpPoPrintAdapter", + "HxjmApaSubjectAdapter", + "OaSalesReleaseAdapter", + "ScanOutcome", + "ScannedFile", + "SubjectAdapter", + "SubjectRow", + "get_adapter", + "register_adapter", + "registered_adapter_names", +] diff --git a/backend/app/services/voucher_check/adapters/base.py b/backend/app/services/voucher_check/adapters/base.py new file mode 100644 index 00000000..a728e03a --- /dev/null +++ b/backend/app/services/voucher_check/adapters/base.py @@ -0,0 +1,113 @@ +""" +backend/app/services/voucher_check/adapters/base.py + +用途:立账凭证来源 Adapter 统一数据结构与协议。 +依赖:无。 +逻辑:引擎只消费这些类型;ERP/OA/DMS 细节留在各 Adapter 内。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date +from typing import Any, Protocol + + +@dataclass(frozen=True) +class SubjectRow: + """应检 invoice 主体。""" + + invoice_no: str + invoice_date: date | None + source_fingerprint: str + attributes: dict[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class ScannedFile: + """类型目录中命中的一个文件。""" + + filename: str + item_id: str | None = None + folder_id: str | None = None + path: str | None = None + fingerprint: str | None = None + extra: dict[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class ScanOutcome: + """一条文件规则对一张 invoice 的扫描结果。""" + + status: str # matched / missing / technical_error + file: ScannedFile | None = None + error_code: str | None = None + error_message: str | None = None + folder_id: str | None = None + folder_path: str | None = None + + +class SubjectAdapter(Protocol): + """获取期间内应检主体。""" + + source_type: str + + def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]: + """ + 拉取一个自然月的 invoice 清单。 + 【AI 触发时机】周任务或强制重检需要本期主体时调用。 + """ + ... + + +class DirectoryScanAdapter(Protocol): + """扫描文档库类型目录。""" + + source_type: str + + def scan( + self, + *, + period_month: date, + invoice_no: str, + rule: dict[str, Any], + ) -> ScanOutcome: + """ + 在对应类型目录中按命名模板匹配文件。 + 【AI 触发时机】周任务对每张 invoice 的每条 directory_scan 规则调用。 + """ + ... + + +class AcquireAdapter(Protocol): + """把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。""" + + source_type: str + wired: bool + + def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]: + """ + 获取并落入类型目录。 + 【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。 + """ + ... + + +class ArchiveAdapter(Protocol): + """把已匹配文件复制到所有归档/{invoice}/。""" + + wired: bool + + def archive( + self, + *, + period_month: date, + invoice_no: str, + file: ScannedFile, + rule: dict[str, Any], + ) -> ScannedFile: + """ + 复制到归档子目录;目标已有同名文件则跳过覆盖。 + 【AI 触发时机】扫描命中且命名校验通过后调用。 + """ + ... diff --git a/backend/app/services/voucher_check/adapters/dms_archive.py b/backend/app/services/voucher_check/adapters/dms_archive.py new file mode 100644 index 00000000..31f25d26 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/dms_archive.py @@ -0,0 +1,81 @@ +""" +backend/app/services/voucher_check/adapters/dms_archive.py + +用途:把类型目录中的命中文件复制到「所有归档/{invoice}/」。 +依赖:dms_client(SaveFolder + Copy);不调用 Move。 +逻辑:wired=True;目标目录已有同名文件则跳过并记 archived,复制失败记技术失败。 +""" + +from __future__ import annotations + +from datetime import date +from typing import Any + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.base import ScannedFile +from app.services.voucher_check.dms_client import SalesDmsClient + + +class DmsArchiveAdapter: + """按票归档:建「所有归档/{invoice}/」并复制,同名跳过。""" + + source_type = "dms_archive" + wired = True + + def __init__(self) -> None: + self._archive_root_ids: dict[str, str] = {} + + def _archive_root_id(self, period_month: date) -> str: + key = period_month.strftime("%Y-%m") + if key not in self._archive_root_ids: + self._archive_root_ids[key] = SalesDmsClient.ensure_month_archive_root( + period_month=period_month + ) + return self._archive_root_ids[key] + + def archive( + self, + *, + period_month: date, + invoice_no: str, + file: ScannedFile, + rule: dict[str, Any], + ) -> ScannedFile: + """ + 确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。 + 【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。 + 核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。 + """ + yyyy = f"{period_month.year:04d}" + mm = f"{period_month.month:02d}" + archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{invoice_no}/{file.filename}" + source_item_id = str(file.item_id or "").strip() + if not source_item_id: + raise ServiceUnavailableError( + "命中文件缺少文档库条目 ID,无法复制", + code="VOUCHER_CHECK.ARCHIVE_FAILED", + details={"adapter": self.source_type, "rule": rule.get("code")}, + ) + archive_root_id = self._archive_root_id(period_month) + dest_folder_id = SalesDmsClient.ensure_folder( + parent_folder_id=archive_root_id, + leaf_name=str(invoice_no).strip(), + ) + dest_row, skipped = SalesDmsClient.copy_file_skip_same_name( + source_item_id=source_item_id, + dest_folder_id=dest_folder_id, + leaf_name=file.filename, + ) + return ScannedFile( + filename=file.filename, + item_id=str(dest_row.get("ID") or "").strip() or None, + folder_id=dest_folder_id, + path=archive_path, + fingerprint=file.fingerprint, + extra={ + "skipped_same_name": skipped, + "source_item_id": source_item_id, + "dest_version_id": dest_row.get("VersionID"), + "rule": rule.get("code"), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/dms_directory_scan.py b/backend/app/services/voucher_check/adapters/dms_directory_scan.py new file mode 100644 index 00000000..2a3d4009 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/dms_directory_scan.py @@ -0,0 +1,110 @@ +""" +backend/app/services/voucher_check/adapters/dms_directory_scan.py + +用途:扫描销售开票附件/{年}/{月}/{类型目录} 并按命名模板匹配 invoice。 +依赖:dms_client、filename_match、fingerprint。 +逻辑:目录不存在视为该规则缺件;登录/Page 失败视为技术失败。 +""" + +from __future__ import annotations + +from datetime import date +from typing import Any + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.base import ScanOutcome, ScannedFile +from app.services.voucher_check.dms_client import SalesDmsClient +from app.services.voucher_check.filename_match import first_match +from app.services.voucher_check.fingerprint import build_material_fingerprint + + +class DmsDirectoryScanAdapter: + """文档库类型目录扫描 Adapter。""" + + source_type = "directory_scan" + + def __init__(self) -> None: + self._month_folder_ids: dict[str, str | None] = {} + self._type_folder_ids: dict[str, str | None] = {} + self._type_files: dict[str, list[dict[str, Any]]] = {} + + def _period_key(self, period_month: date) -> str: + return period_month.strftime("%Y-%m") + + def _month_folder_id(self, period_month: date) -> str | None: + key = self._period_key(period_month) + if key not in self._month_folder_ids: + _year_id, month_id = SalesDmsClient.resolve_period_folder(period_month=period_month) + self._month_folder_ids[key] = month_id + return self._month_folder_ids[key] + + def _type_folder_id(self, period_month: date, type_folder: str) -> str | None: + cache_key = f"{self._period_key(period_month)}/{type_folder}" + if cache_key not in self._type_folder_ids: + month_id = self._month_folder_id(period_month) + if not month_id: + self._type_folder_ids[cache_key] = None + else: + self._type_folder_ids[cache_key] = SalesDmsClient.find_child_folder( + parent_folder_id=month_id, + leaf_name=type_folder, + ) + return self._type_folder_ids[cache_key] + + def scan( + self, + *, + period_month: date, + invoice_no: str, + rule: dict[str, Any], + ) -> ScanOutcome: + """ + 在类型目录中匹配当前 invoice 的文件。 + 核心逻辑:缓存月目录与类型目录列表,避免每票重复 Page。 + """ + type_folder = str(rule.get("type_folder") or "").strip() + template = str(rule.get("filename_template") or "").strip() + yyyy = f"{period_month.year:04d}" + mm = f"{period_month.month:02d}" + folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}" + try: + folder_id = self._type_folder_id(period_month, type_folder) + if not folder_id: + return ScanOutcome( + status="missing", + folder_path=folder_path, + ) + cache_key = folder_id + if cache_key not in self._type_files: + self._type_files[cache_key] = SalesDmsClient.list_files(folder_id=folder_id) + rows = self._type_files[cache_key] + names = [str(row.get("LeafName") or "").strip() for row in rows] + hit = first_match(names, template=template, invoice_no=invoice_no) + if hit is None: + return ScanOutcome(status="missing", folder_id=folder_id, folder_path=folder_path) + row = next((item for item in rows if str(item.get("LeafName") or "").strip() == hit.filename), {}) + item_id = str((row or {}).get("ID") or "") or None + version_id = str((row or {}).get("VersionID") or "") + fingerprint = build_material_fingerprint( + [(f"{hit.filename}|{item_id or ''}|{version_id}", 0, 0)] + ) + return ScanOutcome( + status="matched", + folder_id=folder_id, + folder_path=folder_path, + file=ScannedFile( + filename=hit.filename, + item_id=item_id, + folder_id=folder_id, + path=str((row or {}).get("Path") or folder_path), + fingerprint=fingerprint, + extra={"version_id": (row or {}).get("VersionID")}, + ), + ) + except ServiceUnavailableError as exc: + return ScanOutcome( + status="technical_error", + folder_path=folder_path, + error_code=exc.code, + error_message=exc.message, + ) diff --git a/backend/app/services/voucher_check/adapters/erp_po_print.py b/backend/app/services/voucher_check/adapters/erp_po_print.py new file mode 100644 index 00000000..32a4e968 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/erp_po_print.py @@ -0,0 +1,36 @@ +""" +backend/app/services/voucher_check/adapters/erp_po_print.py + +用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。 +依赖:adapters.base。 +逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。 +""" + +from __future__ import annotations + +from datetime import date + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow + + +class ErpPoPrintAdapter: + """PO 打印占位;未接线时禁止生成假 PDF。""" + + source_type = "erp_po_print" + wired = False + + def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]: + """ + 预留:按 invoice 反查 PO 并打印到类型目录。 + 【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。 + """ + raise ServiceUnavailableError( + "ERP PO 打印尚未接线", + code="VOUCHER_CHECK.ADAPTER_NOT_WIRED", + details={ + "adapter": self.source_type, + "period": period_month.isoformat(), + "subject_count": len(subjects), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py new file mode 100644 index 00000000..23e8e265 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py @@ -0,0 +1,61 @@ +""" +backend/app/services/voucher_check/adapters/hxjm_apa_subject.py + +用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。 +依赖:erp_repository.fetch_month_invoices、fingerprint。 +逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。 +""" + +from __future__ import annotations + +from datetime import date +from typing import Any + +from app.services.voucher_check.adapters.base import SubjectRow +from app.services.voucher_check.erp_repository import fetch_month_invoices +from app.services.voucher_check.fingerprint import build_material_fingerprint + + +class HxjmApaSubjectAdapter: + """HXJM apa08/apa09 主体 Adapter。""" + + source_type = "hxjm_apa" + + def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]: + """ + 查询上月发票号集合并生成主体指纹。 + 核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。 + + Args: + period_month: 检核月首日,由 runner 预先算好。 + config: 含 ERP 连接的运行配置。 + + Returns: + SubjectRow 列表。 + """ + actual_period, rows = fetch_month_invoices(config) + if actual_period != period_month: + from app.core.errors import ServiceUnavailableError + + raise ServiceUnavailableError( + "ERP 期间与批次期间不一致", + code="VOUCHER_CHECK.ERP_UNAVAILABLE", + details={ + "expected": period_month.isoformat(), + "actual": actual_period.isoformat(), + }, + ) + subjects: list[SubjectRow] = [] + for row in rows: + fingerprint = build_material_fingerprint( + [(row.invoice_no, 0, int((row.invoice_date or period_month).toordinal()))] + ) + subjects.append( + SubjectRow( + invoice_no=row.invoice_no, + invoice_date=row.invoice_date, + source_fingerprint=fingerprint, + attributes={"scope_code": getattr(config, "scope_code", "HXJM")}, + ) + ) + return subjects diff --git a/backend/app/services/voucher_check/adapters/oa_sales_release.py b/backend/app/services/voucher_check/adapters/oa_sales_release.py new file mode 100644 index 00000000..16658713 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/oa_sales_release.py @@ -0,0 +1,36 @@ +""" +backend/app/services/voucher_check/adapters/oa_sales_release.py + +用途:OA 销货放行单模拟页面打印的占位 Adapter。 +依赖:adapters.base。 +逻辑:一期规则已定但页面自动化未实现;周任务不调用,只扫描「销货单」目录。 +""" + +from __future__ import annotations + +from datetime import date + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow + + +class OaSalesReleaseAdapter: + """销货放行单打印占位;未接线时禁止生成假 PDF。""" + + source_type = "oa_sales_release" + wired = False + + def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]: + """ + 预留:按上月/归档/HXJM/发票号非空过滤后逐条打印。 + 【AI 触发时机】仅当独立「抓取销货放行单」任务上线后调用。 + """ + raise ServiceUnavailableError( + "OA 销货放行单打印尚未接线", + code="VOUCHER_CHECK.ADAPTER_NOT_WIRED", + details={ + "adapter": self.source_type, + "period": period_month.isoformat(), + "subject_count": len(subjects), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/registry.py b/backend/app/services/voucher_check/adapters/registry.py new file mode 100644 index 00000000..a845fed8 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/registry.py @@ -0,0 +1,44 @@ +""" +backend/app/services/voucher_check/adapters/registry.py + +用途:按 source_type / adapter 名解析已注册 Adapter。 +依赖:adapters.base。 +逻辑:模块 import 时 register;引擎禁止使用未登记的 source_type。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +from app.core.errors import ValidationError + +_REGISTRY: dict[str, Callable[[], Any]] = {} + + +def register_adapter(name: str, factory: Callable[[], Any]) -> None: + """登记 Adapter 工厂。同名后注册覆盖,便于测试注入。""" + key = str(name or "").strip() + if not key: + raise ValidationError("Adapter 名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + _REGISTRY[key] = factory + + +def get_adapter(name: str) -> Any: + """ + 按名称构造 Adapter。 + 核心逻辑:未注册则配置失败,避免引擎落到未知来源。 + """ + key = str(name or "").strip() + factory = _REGISTRY.get(key) + if factory is None: + raise ValidationError( + f"未注册的 Adapter: {key}", + code="VOUCHER_CHECK.CONFIG_INVALID", + details={"adapter": key}, + ) + return factory() + + +def registered_adapter_names() -> tuple[str, ...]: + """返回已登记名称,供测试断言。""" + return tuple(sorted(_REGISTRY)) diff --git a/backend/app/services/voucher_check/aggregator.py b/backend/app/services/voucher_check/aggregator.py new file mode 100644 index 00000000..8714cc00 --- /dev/null +++ b/backend/app/services/voucher_check/aggregator.py @@ -0,0 +1,114 @@ +""" +backend/app/services/voucher_check/aggregator.py + +用途:按单文件结果计算缺件双口径、invoice 行 Excel 值与批次状态。 +依赖:无 IO。 +逻辑:缺件文件数计 missing 条数;缺件 invoice 数对 missing 去重;技术失败/跳过/待归档不计缺件。 +""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Any + +EXCEL_PRESENT = "有" +EXCEL_MISSING = "缺件" +EXCEL_PENDING = "未检核" +INVOICE_COMPLETE = "完整" +INVOICE_MISSING = "缺件" +INVOICE_PENDING = "待处理" + +_MISSING = "missing" +_ARCHIVED = "archived" +_SKIPPED = "skipped" +_TECH = "technical_error" +_STAGED = "staged" + + +def excel_cell_for_rule(statuses: list[str]) -> str: + """一条规则在 Excel 中的单元格:缺件优先于有,其余为未检核。""" + if any(status == _MISSING for status in statuses): + return EXCEL_MISSING + if statuses and all(status == _ARCHIVED for status in statuses): + return EXCEL_PRESENT + return EXCEL_PENDING + + +def invoice_conclusion(cells: list[str]) -> str: + """invoice 行总体状态。""" + if cells and all(cell == EXCEL_PRESENT for cell in cells): + return INVOICE_COMPLETE + if any(cell == EXCEL_MISSING for cell in cells): + return INVOICE_MISSING + return INVOICE_PENDING + + +def aggregate_file_results( + results: list[dict[str, Any]], + *, + rules: list[dict[str, Any]], +) -> dict[str, Any]: + """ + 聚合单文件结果。 + 核心逻辑:只认 status 字段;同一 invoice 多条缺件文件计多份、invoice 只计一次。 + """ + missing_files = [row for row in results if row.get("status") == _MISSING] + missing_invoices = {str(row.get("invoice_no") or "") for row in missing_files} + missing_invoices.discard("") + by_type: dict[str, dict[str, Any]] = {} + for rule in rules: + code = str(rule.get("code") or "") + type_rows = [row for row in results if row.get("rule_code") == code] + type_missing = [row for row in type_rows if row.get("status") == _MISSING] + by_type[code] = { + "rule_code": code, + "rule_name": rule.get("name") or code, + "missing_file_count": len(type_missing), + "missing_invoice_count": len({str(row.get("invoice_no") or "") for row in type_missing} - {""}), + } + + invoices: dict[str, list[dict[str, Any]]] = defaultdict(list) + for row in results: + invoices[str(row.get("invoice_no") or "")].append(row) + + excel_rows: list[dict[str, Any]] = [] + for invoice_no, rows in invoices.items(): + if not invoice_no: + continue + cells: dict[str, str] = {} + ordered_cells: list[str] = [] + for rule in rules: + code = str(rule.get("code") or "") + cell = excel_cell_for_rule( + [str(item.get("status") or "") for item in rows if item.get("rule_code") == code] + ) + cells[code] = cell + ordered_cells.append(cell) + excel_rows.append( + { + "invoice_no": invoice_no, + "invoice_date": next((item.get("invoice_date") for item in rows if item.get("invoice_date")), None), + "cells": cells, + "status": invoice_conclusion(ordered_cells), + } + ) + excel_rows.sort(key=lambda item: str(item["invoice_no"])) + + batch_status = "completed" + if missing_files: + batch_status = "missing" + elif any(row.get("status") == _TECH for row in results): + batch_status = "technical_failed" + + return { + "subject_count": len([key for key in invoices if key]), + "archived_file_count": sum(1 for row in results if row.get("status") == _ARCHIVED), + "skipped_file_count": sum(1 for row in results if row.get("status") == _SKIPPED), + "missing_file_count": len(missing_files), + "missing_invoice_count": len(missing_invoices), + "technical_error_count": sum(1 for row in results if row.get("status") == _TECH), + "staged_file_count": sum(1 for row in results if row.get("status") == _STAGED), + "by_file_type": by_type, + "excel_rows": excel_rows, + "batch_status": batch_status, + } diff --git a/backend/app/services/voucher_check/config.py b/backend/app/services/voucher_check/config.py index c22fc367..1f8a62e2 100644 --- a/backend/app/services/voucher_check/config.py +++ b/backend/app/services/voucher_check/config.py @@ -1,16 +1,15 @@ """ backend/app/services/voucher_check/config.py -用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。 +用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。 依赖:Flask current_app.config、core.errors.ValidationError。 -逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。 +逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID; + ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。 """ from __future__ import annotations -import json import os -import re from dataclasses import dataclass from typing import Any @@ -18,60 +17,22 @@ from flask import has_app_context, current_app from app.core.errors import ValidationError -_ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"} -_TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}") -_UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)") - -DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [ - { - "code": "price_check_sheet", - "name": "核价单", - "required": True, - "accepted_filenames": ["核价单.pdf"], - }, - { - "code": "purchase_order", - "name": "采购单", - "required": True, - "accepted_filenames": ["采购单.pdf"], - }, -] - DEFAULT_JOB_PARAMS: dict[str, Any] = { + "profile_code": "sales", "scope_code": "HXJM", - "directory_template": "{root}/{YYYY}/{MM}/{invoice_no}", - "required_files": DEFAULT_REQUIRED_FILES, - "filename_case_sensitive": True, "notify_missing_enabled": True, "notify_failure_enabled": True, - "same_day_dedup_enabled": True, } @dataclass(frozen=True) -class RequiredFileRule: - """单条必检材料规则。""" - - code: str - name: str - required: bool - accepted_filenames: tuple[str, ...] - - -@dataclass(frozen=True) -class VoucherCheckConfig: - """运行期检核配置快照。""" +class VoucherCheckEngineConfig: + """销售一期引擎运行配置:ERP + 通知开关。""" scope_code: str - directory_template: str - required_files: tuple[RequiredFileRule, ...] - filename_case_sensitive: bool + profile_code: str notify_missing_enabled: bool notify_failure_enabled: bool - same_day_dedup_enabled: bool - local_root: str - share_unc: str - healthcheck_relative_path: str erp_dsn: str erp_username: str erp_password: str @@ -99,114 +60,13 @@ def _as_bool(value: Any, default: bool) -> bool: return default -def _parse_required_files(raw: Any) -> list[RequiredFileRule]: - if raw is None: - raw = DEFAULT_REQUIRED_FILES - if isinstance(raw, str): - try: - raw = json.loads(raw) - except json.JSONDecodeError as exc: - raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc - if not isinstance(raw, list) or not raw: - raise _config_invalid("required_files 至少包含一个必检项") - - rules: list[RequiredFileRule] = [] - for idx, item in enumerate(raw): - if not isinstance(item, dict): - raise _config_invalid(f"required_files[{idx}] 必须为对象") - code = str(item.get("code") or "").strip() - name = str(item.get("name") or code).strip() - accepted = item.get("accepted_filenames") or [] - if not code: - raise _config_invalid(f"required_files[{idx}].code 不能为空") - if not isinstance(accepted, list) or not accepted: - raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空") - filenames: list[str] = [] - for fname in accepted: - text = str(fname or "").strip() - if not text: - raise _config_invalid(f"required_files[{idx}] 存在空文件名") - if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text): - raise _config_invalid( - f"required_files[{idx}] 文件名禁止通配/路径字符: {text}", - ) - filenames.append(text) - rules.append( - RequiredFileRule( - code=code, - name=name or code, - required=_as_bool(item.get("required"), True), - accepted_filenames=tuple(filenames), - ) - ) - if not any(r.required for r in rules): - raise _config_invalid("required_files 至少包含一个 required=true 项") - return rules - - -def validate_directory_template(template: str) -> str: +def _erp_settings() -> tuple[str, str, str, int]: """ - 校验目录模板占位符。 - 核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。 + 读取 ERP 只读连接;密码只来自环境/配置,不写日志。 + + 核心逻辑:VOUCHER_CHECK_ERP_* 优先,其次通用 ERP_*,再回退合同付款同一套只读账号。 """ - text = str(template or "").strip().replace("\\", "/") - if not text: - raise _config_invalid("directory_template 不能为空") - tokens = _TEMPLATE_TOKEN_RE.findall(text) - unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS}) - if unknown: - raise _config_invalid( - "directory_template 含非法占位符", - details={"unknown": unknown}, - ) - missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens)) - if missing: - raise _config_invalid( - "directory_template 缺少必要占位符", - details={"missing": missing}, - ) - return text - - -def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig: - """ - 合并 env 与 job_params,返回校验后的检核配置。 - 核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。 - """ - params = dict(DEFAULT_JOB_PARAMS) - if isinstance(job_params, dict): - params.update({k: v for k, v in job_params.items() if v is not None}) - - scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM" - if scope_code != "HXJM": - raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code}) - - template = validate_directory_template( - str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"]) - ) - required_files = _parse_required_files(params.get("required_files")) - cfg = current_app.config if has_app_context() else {} - local_root = str( - cfg.get("VOUCHER_CHECK_LOCAL_ROOT") - or os.getenv("VOUCHER_CHECK_LOCAL_ROOT") - or "" - ).strip() - share_unc = str( - cfg.get("VOUCHER_CHECK_SHARE_UNC") - or os.getenv("VOUCHER_CHECK_SHARE_UNC") - or "" - ).strip() - healthcheck = str( - cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") - or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") - or ".hxops-share-ready" - ).strip() or ".hxops-share-ready" - - # 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT - if not local_root and not share_unc: - raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC") - erp_dsn = str( cfg.get("VOUCHER_CHECK_ERP_DSN") or os.getenv("VOUCHER_CHECK_ERP_DSN") @@ -217,46 +77,53 @@ def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> Vouch erp_username = str( cfg.get("VOUCHER_CHECK_ERP_USERNAME") or os.getenv("VOUCHER_CHECK_ERP_USERNAME") + or cfg.get("ERP_USERNAME") + or os.getenv("ERP_USERNAME") + or cfg.get("CONTRACT_PAYMENT_ERP_USERNAME") + or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME") or "" ).strip() erp_password = str( cfg.get("VOUCHER_CHECK_ERP_PASSWORD") or os.getenv("VOUCHER_CHECK_ERP_PASSWORD") + or cfg.get("ERP_PASSWORD") + or os.getenv("ERP_PASSWORD") + or cfg.get("CONTRACT_PAYMENT_ERP_PASSWORD") + or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD") or "" ) if not erp_dsn or not erp_username: raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME") - timeout = int( cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") + or cfg.get("ERP_TIMEOUT_SECONDS") + or os.getenv("ERP_TIMEOUT_SECONDS") or 30 ) + return erp_dsn, erp_username, erp_password, max(1, timeout) - return VoucherCheckConfig( + +def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheckEngineConfig: + """ + 加载销售一期引擎配置。 + 核心逻辑:不要求共享盘;DMS 根目录由 SalesDmsClient.ensure_configured 在 runner 中校验。 + """ + params = dict(DEFAULT_JOB_PARAMS) + if isinstance(job_params, dict): + params.update({k: v for k, v in job_params.items() if v is not None}) + scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM" + if scope_code != "HXJM": + raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code}) + profile_code = str(params.get("profile_code") or "sales").strip() or "sales" + erp_dsn, erp_username, erp_password, timeout = _erp_settings() + return VoucherCheckEngineConfig( scope_code=scope_code, - directory_template=template, - required_files=tuple(required_files), - filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True), + profile_code=profile_code, notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True), notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True), - same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True), - local_root=local_root, - share_unc=share_unc, - healthcheck_relative_path=healthcheck, erp_dsn=erp_dsn, erp_username=erp_username, erp_password=erp_password, - erp_timeout_seconds=max(1, timeout), + erp_timeout_seconds=timeout, ) - - -def resolve_share_root(config: VoucherCheckConfig) -> str: - """ - 解析实际扫描根路径。 - 核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。 - """ - root = (config.local_root or config.share_unc or "").strip() - if not root: - raise _config_invalid("共享盘根路径为空") - return root diff --git a/backend/app/services/voucher_check/dms_client.py b/backend/app/services/voucher_check/dms_client.py new file mode 100644 index 00000000..b78dd52f --- /dev/null +++ b/backend/app/services/voucher_check/dms_client.py @@ -0,0 +1,402 @@ +""" +backend/app/services/voucher_check/dms_client.py + +用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。 +依赖:requests、Flask 配置;登录接口与合同库相同。 +逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。 +""" + +from __future__ import annotations + +import threading +import time +from datetime import date +from typing import Any + +import requests +from flask import current_app + +from app.core.errors import ServiceUnavailableError, ValidationError + +_LOCK = threading.Lock() +_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0} + +ARCHIVE_ROOT_LEAF = "所有归档" + + +def _extract_item_id(payload: dict[str, Any]) -> str: + """ + 从 DMS SaveFolder / Copy 响应中取出条目 ID。 + 核心逻辑:现网 Data 可能是对象或字符串;缺字段时返回空串,由调用方再 Page 回查。 + """ + data = payload.get("Data") + if isinstance(data, str) and data.strip(): + return data.strip() + if not isinstance(data, dict): + return "" + for key in ("ID", "ItemID", "FolderID"): + value = str(data.get(key) or "").strip() + if value: + return value + nested = data.get("Item") or data.get("Folder") or {} + if isinstance(nested, dict): + return str(nested.get("ID") or "").strip() + return "" + + +def _is_name_conflict(message: str) -> bool: + """判断 DMS 返回是否为同名/已存在冲突,便于按「同名跳过」回收。""" + text = str(message or "").strip() + if not text: + return False + lowered = text.lower() + return any( + needle in text + for needle in ("已存在", "同名", "重复名称", "名称重复") + ) or any( + needle in lowered + for needle in ("already exist", "already exists", "duplicate name") + ) + + +class SalesDmsClient: + """销售开票附件 DMS 客户端;不把账号密码返回给 API。""" + + @classmethod + def _cfg(cls, key: str, fallback: str = "") -> str: + value = current_app.config.get(key) or fallback + return str(value or "").strip() + + @classmethod + def base_url(cls) -> str: + return (cls._cfg("VOUCHER_CHECK_DMS_BASE_URL") or cls._cfg("CONTRACT_DMS_BASE_URL")).rstrip("/") + + @classmethod + def library_id(cls) -> str: + return cls._cfg("VOUCHER_CHECK_DMS_LIBRARY_ID") or cls._cfg("CONTRACT_DMS_LIBRARY_ID") + + @classmethod + def root_folder_id(cls) -> str: + return cls._cfg("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID") + + @classmethod + def username(cls) -> str: + return cls._cfg("VOUCHER_CHECK_DMS_USERNAME") or cls._cfg("CONTRACT_DMS_USERNAME") + + @classmethod + def password(cls) -> str: + return str( + current_app.config.get("VOUCHER_CHECK_DMS_PASSWORD") + or current_app.config.get("CONTRACT_DMS_PASSWORD") + or "" + ) + + @classmethod + def is_configured(cls) -> bool: + """判断销售 DMS 基址、账号、文档库 ID 和销售根目录是否齐全。""" + return bool(cls.base_url() and cls.username() and cls.password() and cls.library_id() and cls.root_folder_id()) + + @classmethod + def ensure_configured(cls) -> None: + """ + 配置缺失时在批次开始前失败,并返回可操作的缺失项。 + 核心逻辑:避免把空扫当成业务缺件;同时不能将任意凭据值写入错误响应。 + """ + missing = [ + key + for key, value in ( + ("VOUCHER_CHECK_DMS_BASE_URL", cls.base_url()), + ("VOUCHER_CHECK_DMS_LIBRARY_ID", cls.library_id()), + ("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID", cls.root_folder_id()), + ("VOUCHER_CHECK_DMS_USERNAME", cls.username()), + ("VOUCHER_CHECK_DMS_PASSWORD", cls.password()), + ) + if not value + ] + if missing: + raise ValidationError( + "销售开票附件文档库配置不完整", + code="VOUCHER_CHECK.CONFIG_INVALID", + details={"missing": missing}, + ) + + @classmethod + def _session(cls, *, refresh: bool = False) -> requests.Session: + """登录 DMS 并缓存会话。""" + with _LOCK: + session = _CACHE.get("session") + if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200: + return session + session = requests.Session() + try: + response = session.post( + f"{cls.base_url()}/Login/_api/Login", + json={"LoginName": cls.username(), "Pwd": cls.password()}, + timeout=20, + ) + response.raise_for_status() + payload = response.json() + except requests.RequestException as exc: + raise ServiceUnavailableError( + "文档库登录失败", + code="VOUCHER_CHECK.DMS_UNAVAILABLE", + ) from exc + if int(payload.get("Code") or 0) != 0: + raise ServiceUnavailableError( + payload.get("Msg") or "文档库登录失败", + code="VOUCHER_CHECK.DMS_UNAVAILABLE", + ) + _CACHE.update({"session": session, "created_at": time.time()}) + return session + + @classmethod + def _post_json( + cls, + path: str, + payload: dict[str, Any], + *, + timeout: int = 30, + failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE", + failure_message: str = "文档库请求失败", + ) -> dict[str, Any]: + """ + POST JSON 到现网 DMS,并统一处理 401 刷新与 Code!=0。 + 核心逻辑:路径相对基址;失败抛 ServiceUnavailableError,不把凭据写入异常。 + """ + url = f"{cls.base_url()}{path}" + try: + session = cls._session() + response = session.post(url, json=payload, timeout=timeout) + if response.status_code in {401, 403}: + session = cls._session(refresh=True) + response = session.post(url, json=payload, timeout=timeout) + response.raise_for_status() + data = response.json() + except (requests.RequestException, ValueError) as exc: + raise ServiceUnavailableError(failure_message, code=failure_code) from exc + if int(data.get("Code") or 0) != 0: + raise ServiceUnavailableError( + data.get("Msg") or failure_message, + code=failure_code, + ) + return data + + @classmethod + def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]: + """ + 查询一个父目录下的条目。 + 核心逻辑:POST Item/Page,按页累加直到本页不足 Size 或达到 Total;避免「所有归档」超过 200 个子目录时漏建/漏跳过。 + """ + items: list[dict[str, Any]] = [] + page_size = 200 + index = 1 + while index <= 50: + payload = { + "LibraryID": cls.library_id(), + "ParentFolderID": parent_folder_id, + "Keywords": "", + "Page": {"Size": page_size, "Index": index}, + "Total": 0, + "Recursion": recursion, + "OrderBy": [], + "FieldQuery": [], + "LeafName": leaf_name, + } + data = cls._post_json("/Api/_api/APS/Public/Item/Page", payload, timeout=30) + section = data.get("Data") or {} + batch = section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or [] + items.extend(batch) + total = int(section.get("Total") or 0) + if len(batch) < page_size: + break + if total and len(items) >= total: + break + index += 1 + return items + + @classmethod + def find_child_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str | None: + """在父目录下按 LeafName 找文件夹 ID,找不到返回 None。""" + wanted = str(leaf_name or "").strip() + if not wanted: + return None + for row in cls.page(parent_folder_id=parent_folder_id, recursion=False): + if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted: + folder_id = str(row.get("ID") or "").strip() + if folder_id: + return folder_id + return None + + @classmethod + def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None: + """在父目录下按 LeafName 找非文件夹条目,找不到返回 None。""" + wanted = str(leaf_name or "").strip() + if not wanted: + return None + for row in cls.list_files(folder_id=parent_folder_id): + if str(row.get("LeafName") or "").strip() == wanted: + return row + return None + + @classmethod + def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]: + """ + 解析销售开票附件/{yyyy}/{MM} 的 FolderID。 + 核心逻辑:从销售根逐级找年、月目录;缺层返回 (None, None),由扫描记缺件而非技术失败。 + """ + root = cls.root_folder_id() + year_name = f"{period_month.year:04d}" + month_name = f"{period_month.month:02d}" + year_id = cls.find_child_folder(parent_folder_id=root, leaf_name=year_name) + if not year_id: + return None, None + month_id = cls.find_child_folder(parent_folder_id=year_id, leaf_name=month_name) + return year_id, month_id + + @classmethod + def list_files(cls, *, folder_id: str) -> list[dict[str, Any]]: + """列出目录下的非文件夹条目。""" + rows = cls.page(parent_folder_id=folder_id, recursion=False) + return [row for row in rows if not row.get("IsFolder")] + + @classmethod + def ensure_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str: + """ + 确保父目录下存在指定 LeafName 的文件夹;没有则 SaveFolder。 + 核心逻辑:先 Page 查找;已存在直接返回。创建时若接口报同名,再查一次当作成功。 + """ + wanted = str(leaf_name or "").strip() + if not wanted: + raise ValidationError("文件夹名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) + if existing: + return existing + try: + payload = cls._post_json( + "/Api/_api/APS/Public/Item/SaveFolder", + { + "ID": "", + "LibraryID": cls.library_id(), + "ParentFolderID": parent_folder_id, + "LeafName": wanted, + "FieldValues": [], + }, + failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", + failure_message="文档库创建文件夹失败", + ) + except ServiceUnavailableError as exc: + existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) + if existing: + return existing + if _is_name_conflict(exc.message): + existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) + if existing: + return existing + raise + created_id = _extract_item_id(payload) + if created_id: + return created_id + existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted) + if existing: + return existing + raise ServiceUnavailableError( + "创建文件夹后未能解析 FolderID", + code="VOUCHER_CHECK.ARCHIVE_FAILED", + details={"leaf_name": wanted}, + ) + + @classmethod + def ensure_month_archive_root(cls, *, period_month: date) -> str: + """ + 确保销售开票附件/{yyyy}/{MM}/所有归档 存在并返回 FolderID。 + 核心逻辑:月目录必须已存在(扫描命中才归档);缺月目录视为技术失败,不降级为缺件。 + """ + _year_id, month_id = cls.resolve_period_folder(period_month=period_month) + if not month_id: + raise ServiceUnavailableError( + "销售开票附件年/月目录不存在,无法创建归档文件夹", + code="VOUCHER_CHECK.ARCHIVE_FAILED", + ) + return cls.ensure_folder(parent_folder_id=month_id, leaf_name=ARCHIVE_ROOT_LEAF) + + @classmethod + def ensure_invoice_archive_folder(cls, *, period_month: date, invoice_no: str) -> str: + """ + 确保所有归档/{invoice}/ 存在并返回 FolderID。 + 核心逻辑:先保证「所有归档」,再按发票号建子目录。 + """ + invoice = str(invoice_no or "").strip() + if not invoice: + raise ValidationError("归档发票号不能为空", code="VOUCHER_CHECK.INVOICE_REQUIRED") + archive_root_id = cls.ensure_month_archive_root(period_month=period_month) + return cls.ensure_folder(parent_folder_id=archive_root_id, leaf_name=invoice) + + @classmethod + def copy_items(cls, *, item_ids: list[str], dest_folder_id: str) -> dict[str, Any]: + """ + 把文档库条目复制到目标文件夹(不移动原件)。 + 核心逻辑:POST Item/Copy;ItemID 为数组,与现网前端 CopyFileFolder 一致。 + """ + ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()] + dest = str(dest_folder_id or "").strip() + if not ids: + raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + if not dest: + raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + return cls._post_json( + "/Api/_api/APS/Public/Item/Copy", + {"ItemID": ids, "ParentFolderID": dest}, + timeout=60, + failure_code="VOUCHER_CHECK.ARCHIVE_FAILED", + failure_message="文档库复制文件失败", + ) + + @classmethod + def copy_file_skip_same_name( + cls, + *, + source_item_id: str, + dest_folder_id: str, + leaf_name: str, + ) -> tuple[dict[str, Any], bool]: + """ + 复制文件到目标目录;目标已有同名文件则跳过、不覆盖。 + 核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。 + + Returns: + (目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。 + """ + wanted = str(leaf_name or "").strip() + source = str(source_item_id or "").strip() + dest = str(dest_folder_id or "").strip() + if not source: + raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + if not dest: + raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + if not wanted: + raise ValidationError("复制文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + + try: + cls.copy_items(item_ids=[source], dest_folder_id=dest) + except ServiceUnavailableError as exc: + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + if _is_name_conflict(exc.message): + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + raise + + dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if not dest_row: + raise ServiceUnavailableError( + "复制成功但目标目录未找到同名文件", + code="VOUCHER_CHECK.ARCHIVE_FAILED", + details={"leaf_name": wanted}, + ) + return dest_row, False diff --git a/backend/app/services/voucher_check/engine_persistence.py b/backend/app/services/voucher_check/engine_persistence.py new file mode 100644 index 00000000..2cd6b1e0 --- /dev/null +++ b/backend/app/services/voucher_check/engine_persistence.py @@ -0,0 +1,182 @@ +""" +backend/app/services/voucher_check/engine_persistence.py + +用途:新引擎批次、主体、单文件结果与通知审计的写入。 +依赖:models.voucher_check 新表。 +逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from typing import Any + +from app import db +from app.models.voucher_check import ( + VoucherCheckFileResult, + VoucherCheckNotification, + VoucherCheckRun, + VoucherCheckSubject, +) + + +def create_run( + *, + schedule_run_id: int | None, + run_no: str, + profile_code: str, + profile_version: str, + profile_snapshot: dict[str, Any], + period_month: date, + mode: str, + started_at: datetime, +) -> VoucherCheckRun: + """创建 running 状态的检核批次。""" + run = VoucherCheckRun( + schedule_run_id=schedule_run_id, + run_no=run_no, + profile_code=profile_code, + profile_version=profile_version, + profile_snapshot_json=profile_snapshot, + period_month=period_month, + mode=mode, + status="running", + started_at=started_at, + created_at=started_at, + ) + db.session.add(run) + db.session.flush() + return run + + +def persist_engine_results( + *, + run: VoucherCheckRun, + subjects: list[dict[str, Any]], + file_results: list[dict[str, Any]], + stats: dict[str, Any], + now: datetime | None = None, +) -> None: + """ + 写入主体与单文件结果,并固化批次统计快照。 + 核心逻辑:file_results 是缺件/Excel 真相源;列表查询不再重算。 + """ + ts = now or datetime.utcnow() + subject_ids: dict[str, int] = {} + for item in subjects: + invoice_no = str(item["invoice_no"]).strip() + row = VoucherCheckSubject( + run_id=run.id, + invoice_no=invoice_no, + invoice_date=item.get("invoice_date"), + source_fingerprint=item.get("source_fingerprint"), + attributes_json=item.get("attributes") or {}, + created_at=ts, + ) + db.session.add(row) + db.session.flush() + subject_ids[invoice_no] = row.id + + for item in file_results: + invoice_no = str(item["invoice_no"]).strip() + db.session.add( + VoucherCheckFileResult( + run_id=run.id, + subject_id=subject_ids.get(invoice_no), + invoice_no=invoice_no, + rule_code=str(item["rule_code"]), + rule_name=str(item.get("rule_name") or item["rule_code"]), + source_type=str(item.get("source_type") or "directory_scan"), + expected_name=item.get("expected_name"), + matched_name=item.get("matched_name"), + source_folder_id=item.get("source_folder_id"), + source_item_id=item.get("source_item_id"), + archive_folder_id=item.get("archive_folder_id"), + archive_item_id=item.get("archive_item_id"), + source_path=item.get("source_path"), + archive_path=item.get("archive_path"), + status=str(item["status"]), + missing_reason=item.get("missing_reason"), + error_code=item.get("error_code"), + error_message=item.get("error_message"), + source_fingerprint=item.get("source_fingerprint"), + checked_at=item.get("checked_at") or ts, + created_at=ts, + ) + ) + + run.subject_count = int(stats.get("subject_count") or 0) + run.archived_file_count = int(stats.get("archived_file_count") or 0) + run.skipped_file_count = int(stats.get("skipped_file_count") or 0) + run.missing_file_count = int(stats.get("missing_file_count") or 0) + run.missing_invoice_count = int(stats.get("missing_invoice_count") or 0) + run.technical_error_count = int(stats.get("technical_error_count") or 0) + run.staged_file_count = int(stats.get("staged_file_count") or 0) + run.stats_json = { + "by_file_type": stats.get("by_file_type") or {}, + "batch_status": stats.get("batch_status"), + } + run.status = str(stats.get("batch_status") or "completed") + run.finished_at = ts + db.session.flush() + + +def persist_notification( + *, + run_id: int, + excel_filename: str | None, + recipient_user_ids: list[int], + send_status: str, + skip_reason: str | None, + summary: dict[str, Any], + sent_at: datetime | None, +) -> VoucherCheckNotification: + """写入或覆盖本批次通知审计(一个 run 一条)。""" + row = ( + db.session.query(VoucherCheckNotification) + .filter_by(run_id=run_id) + .one_or_none() + ) + if row is None: + row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow()) + db.session.add(row) + row.excel_filename = excel_filename + row.recipient_user_ids_json = recipient_user_ids + row.send_status = send_status + row.skip_reason = skip_reason + row.summary_json = summary + row.sent_at = sent_at + db.session.flush() + return row + + +def load_previous_archived_fingerprints( + *, + profile_code: str, + period_month: date, + exclude_run_id: int | None = None, +) -> dict[tuple[str, str], str]: + """ + 读取同 Profile+期间已归档文件的最新指纹,供增量跳过。 + 核心逻辑:按 file_results.id 倒序,每个 invoice+rule 只留一条 archived。 + """ + query = ( + db.session.query(VoucherCheckFileResult, VoucherCheckRun) + .join(VoucherCheckRun, VoucherCheckFileResult.run_id == VoucherCheckRun.id) + .filter( + VoucherCheckRun.profile_code == profile_code, + VoucherCheckRun.period_month == period_month, + VoucherCheckFileResult.status == "archived", + ) + .order_by(VoucherCheckFileResult.id.desc()) + ) + if exclude_run_id: + query = query.filter(VoucherCheckFileResult.run_id != exclude_run_id) + found: dict[tuple[str, str], str] = {} + for result, _run in query.all(): + key = (result.invoice_no, result.rule_code) + if key in found: + continue + if result.source_fingerprint: + found[key] = result.source_fingerprint + return found diff --git a/backend/app/services/voucher_check/erp_repository.py b/backend/app/services/voucher_check/erp_repository.py index b4e922db..2155075d 100644 --- a/backend/app/services/voucher_check/erp_repository.py +++ b/backend/app/services/voucher_check/erp_repository.py @@ -1,7 +1,7 @@ """ backend/app/services/voucher_check/erp_repository.py -用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。 +用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。 依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。 逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。 """ @@ -13,7 +13,7 @@ from datetime import date, datetime from zoneinfo import ZoneInfo from app.core.errors import ServiceUnavailableError -from app.services.voucher_check.config import VoucherCheckConfig +from app.services.voucher_check.config import VoucherCheckEngineConfig _TZ = ZoneInfo("Asia/Shanghai") @@ -31,7 +31,7 @@ SELECT DISTINCT @dataclass(frozen=True) class ErpInvoiceRow: - """ERP 当月发票行。""" + """ERP 发票行。""" invoice_no: str invoice_date: date | None @@ -40,7 +40,7 @@ class ErpInvoiceRow: def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]: """ 按 Asia/Shanghai 计算当前自然月起止。 - 核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。 + 核心逻辑:不用 Oracle SYSDATE,作为 previous_period_bounds 的基准。 Returns: (period_month_first, next_month_first, period_start_dt, next_period_start_dt) @@ -60,13 +60,32 @@ def current_period_bounds(now: datetime | None = None) -> tuple[date, date, date return period_month, next_month, period_start, next_start +def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]: + """ + 按 Asia/Shanghai 计算上一个自然月起止。 + 核心逻辑:周二跑批检核上个月;跨年时 1 月回退到上年 12 月。 + + Returns: + (period_month_first, current_month_first, period_start_dt, next_period_start_dt) + 其中 next_period_start 为当前月 1 日,即上月结束边界。 + """ + current_month, _next_month, _current_start, _next_start = current_period_bounds(now) + if current_month.month == 1: + period_month = date(current_month.year - 1, 12, 1) + else: + period_month = date(current_month.year, current_month.month - 1, 1) + period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ) + next_start = datetime(current_month.year, current_month.month, 1, 0, 0, 0, tzinfo=_TZ) + return period_month, current_month, period_start, next_start + + def fetch_month_invoices( - config: VoucherCheckConfig, + config: VoucherCheckEngineConfig, *, now: datetime | None = None, ) -> tuple[date, list[ErpInvoiceRow]]: """ - 查询当前自然月发票清单。 + 查询上一个自然月发票清单。 Args: config: 含 Oracle DSN/账号的检核配置。 @@ -78,7 +97,7 @@ def fetch_month_invoices( Raises: ServiceUnavailableError: Oracle 不可用。 """ - period_month, _next_month, period_start, next_start = current_period_bounds(now) + period_month, _current_month, period_start, next_start = previous_period_bounds(now) try: import oracledb except ImportError as exc: diff --git a/backend/app/services/voucher_check/excel_rows.py b/backend/app/services/voucher_check/excel_rows.py index a690c1d6..a9aed91a 100644 --- a/backend/app/services/voucher_check/excel_rows.py +++ b/backend/app/services/voucher_check/excel_rows.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/excel_rows.py -用途:把批次明细转换为通用 Excel 导出行与表头。 -依赖:无。 -逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。 +用途:把按 invoice 聚合的检核结果转为排程 Excel 行与表头。 +依赖:aggregator 单元格文案。 +逻辑:一行一张 invoice;六类必检列为有/缺件/未检核;资料所属期间与执行时间单独成列以兼容现有排程导出。 """ from __future__ import annotations @@ -12,82 +12,57 @@ from typing import Any VOUCHER_CHECK_HEADER_ORDER = [ "period", - "scope_code", + "executed_at", "invoice_no", - "invoice_date", - "result", - "folder_exists", - "folder_path", - "matched_files", - "missing_materials", - "material_fingerprint", - "checked_at", - "error_code", - "error_message", + "po_order", + "customs_pack", + "sales_release", + "tax_invoice", + "customs_declaration", + "bill_of_lading", + "status", ] VOUCHER_CHECK_HEADER_LABELS = { - "period": "检核月份", - "scope_code": "账套", - "invoice_no": "发票号", - "invoice_date": "发票日期", - "result": "结论", - "folder_exists": "发票目录是否存在", - "folder_path": "共享盘相对路径", - "matched_files": "已找到材料", - "missing_materials": "缺失材料", - "material_fingerprint": "目录元数据指纹", - "checked_at": "实际检核时间", - "error_code": "技术错误码", - "error_message": "技术错误摘要", + "period": "资料所属期间", + "executed_at": "执行时间", + "invoice_no": "invoice", + "po_order": "PO订单", + "customs_pack": "报关资料", + "sales_release": "销货放行申请单", + "tax_invoice": "发票", + "customs_declaration": "报关单", + "bill_of_lading": "提单", + "status": "状态", } -_RESULT_LABELS = { - "complete": "齐全", - "missing": "缺资料", - "skipped": "跳过", - "technical_error": "技术异常", -} +_RULE_COLUMNS = ( + "po_order", + "customs_pack", + "sales_release", + "tax_invoice", + "customs_declaration", + "bill_of_lading", +) -def _fmt_matched(matched: dict[str, Any] | None) -> str: - if not matched: - return "" - return "; ".join(f"{k}={v}" for k, v in matched.items()) - - -def _fmt_missing(missing: list[dict[str, Any]] | None) -> str: - if not missing: - return "" - parts = [] - for item in missing: - name = item.get("name") or item.get("code") or "" - code = item.get("code") or "" - parts.append(f"{name}({code})" if code and name != code else str(name or code)) - return "; ".join(parts) - - -def to_excel_detail_row(item: dict[str, Any], *, period: str, scope_code: str) -> dict[str, Any]: +def to_excel_invoice_row( + item: dict[str, Any], + *, + period: str, + executed_at: str, +) -> dict[str, Any]: """ - 将内存结果行转为 Excel details 行。 + 将聚合后的 invoice 行转为排程 Excel details。 + 核心逻辑:cells 按 rule_code 取值;缺列填未检核。 """ - result = str(item.get("result") or "") - checked_at = item.get("checked_at") - invoice_date = item.get("invoice_date") - return { + cells = item.get("cells") or {} + row = { "period": period, - "scope_code": scope_code, + "executed_at": executed_at, "invoice_no": item.get("invoice_no"), - "invoice_date": invoice_date.isoformat() if hasattr(invoice_date, "isoformat") else invoice_date, - "result": _RESULT_LABELS.get(result, result), - "folder_exists": "是" if item.get("folder_exists") else "否", - "folder_path": item.get("folder_path") or "", - "matched_files": _fmt_matched(item.get("matched_files")), - "missing_materials": _fmt_missing(item.get("missing_materials")), - "material_fingerprint": item.get("material_fingerprint") or "", - "checked_at": checked_at.isoformat(sep=" ", timespec="seconds") - if hasattr(checked_at, "isoformat") - else (checked_at or ""), - "error_code": item.get("error_code") or "", - "error_message": item.get("error_message") or "", + "status": item.get("status") or "", } + for code in _RULE_COLUMNS: + row[code] = cells.get(code) or "未检核" + return row diff --git a/backend/app/services/voucher_check/filename_match.py b/backend/app/services/voucher_check/filename_match.py new file mode 100644 index 00000000..bef6af9b --- /dev/null +++ b/backend/app/services/voucher_check/filename_match.py @@ -0,0 +1,89 @@ +""" +backend/app/services/voucher_check/filename_match.py + +用途:按 Profile 命名模板匹配文档库文件名,并校验文件名中的 invoice。 +依赖:标准库 re。 +逻辑:{invoice} 替换为当前票号;其余 {token} 视为一段非路径字符;禁止路径穿越。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +_PLACEHOLDER_RE = re.compile(r"\{([^{}]+)\}") +_UNSAFE_RE = re.compile(r"[/\\\x00]|(\.\.)") + + +@dataclass(frozen=True) +class FilenameMatch: + """单次文件名命中。""" + + filename: str + groups: dict[str, str] + + +def compile_filename_pattern(template: str, *, invoice_no: str) -> re.Pattern[str]: + """ + 把命名模板编译为整名匹配正则。 + 核心逻辑:先替换 invoice,再把剩余占位符变成捕获组,字面量全部转义。 + + Args: + template: 如 `{invoice}-{order_no}.pdf`。 + invoice_no: 当前发票号,禁止含路径字符。 + + Returns: + 锚定的正则。 + + Raises: + ValueError: 模板或发票号非法。 + """ + invoice = str(invoice_no or "").strip() + if not invoice or _UNSAFE_RE.search(invoice): + raise ValueError("invoice_no 非法") + text = str(template or "").strip() + if not text or _UNSAFE_RE.search(_PLACEHOLDER_RE.sub("", text)): + raise ValueError("filename_template 非法") + + parts: list[str] = [] + cursor = 0 + for match in _PLACEHOLDER_RE.finditer(text): + parts.append(re.escape(text[cursor : match.start()])) + name = match.group(1) + if name in {"invoice", "invoice号"}: + parts.append(re.escape(invoice)) + else: + parts.append(rf"(?P<{re.escape(name)}>[^/\\]+)") + cursor = match.end() + parts.append(re.escape(text[cursor:])) + return re.compile(r"^" + "".join(parts) + r"$") + + +def match_filename(filename: str, *, template: str, invoice_no: str) -> FilenameMatch | None: + """ + 判断文件名是否属于该 invoice 的规则。 + 核心逻辑:整名匹配;命中后要求文件名包含 invoice 原文。 + """ + name = str(filename or "").strip() + if not name: + return None + try: + pattern = compile_filename_pattern(template, invoice_no=invoice_no) + except ValueError: + return None + matched = pattern.match(name) + if not matched: + return None + invoice = str(invoice_no).strip() + if invoice not in name: + return None + return FilenameMatch(filename=name, groups=matched.groupdict()) + + +def first_match(filenames: list[str], *, template: str, invoice_no: str) -> FilenameMatch | None: + """在文件名列表中返回第一条命中,保持目录返回顺序。""" + for name in filenames: + hit = match_filename(name, template=template, invoice_no=invoice_no) + if hit is not None: + return hit + return None diff --git a/backend/app/services/voucher_check/fingerprint.py b/backend/app/services/voucher_check/fingerprint.py index 02b0f568..05a45c55 100644 --- a/backend/app/services/voucher_check/fingerprint.py +++ b/backend/app/services/voucher_check/fingerprint.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/fingerprint.py -用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。 +用途:根据文件名与元数据生成稳定 SHA-256 指纹。 依赖:标准库 hashlib / json。 -逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。 +逻辑:DMS 目录扫描与 HXJM 主体 Adapter 调用,供增量跳过比对。 """ from __future__ import annotations diff --git a/backend/app/services/voucher_check/notification.py b/backend/app/services/voucher_check/notification.py index 10255011..da89c0eb 100644 --- a/backend/app/services/voucher_check/notification.py +++ b/backend/app/services/voucher_check/notification.py @@ -1,15 +1,15 @@ """ backend/app/services/voucher_check/notification.py -用途:立账凭证检核缺资料企微 textcard 与批次失败告警。 -依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。 -逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。 +用途:立账凭证检核批次级企微汇总与技术失败告警。 +依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。 +逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。 """ from __future__ import annotations import uuid -from datetime import date, datetime +from datetime import datetime from typing import Any from zoneinfo import ZoneInfo @@ -17,7 +17,7 @@ from flask import current_app from app import db from app.models import ScheduleRun, ScheduleTask, User -from app.services.voucher_check.persistence import mark_missing_notified +from app.services.voucher_check.engine_persistence import persist_notification _TZ = ZoneInfo("Asia/Shanghai") @@ -30,85 +30,115 @@ def _recipient_users(task: ScheduleTask) -> list[User]: return [u for u in users if u.wecom_userid] -def _today_shanghai(now: datetime | None = None) -> date: - base = now or datetime.now(_TZ) - if base.tzinfo is None: - base = base.replace(tzinfo=_TZ) - else: - base = base.astimezone(_TZ) - return base.date() - - -def send_missing_notifications( +def send_batch_missing_summary( *, task: ScheduleTask, - run: ScheduleRun, - scope_code: str, - period_month: date, - missing_items: list[dict[str, Any]], - same_day_dedup: bool, + schedule_run: ScheduleRun, + engine_run_id: int, + profile_code: str, + period_month: str, + stats: dict[str, Any], + excel_filename: str | None, enabled: bool, -) -> int: +) -> str: """ - 合并发送缺资料 textcard。 - 核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。 + 发送本批缺件汇总 textcard。 + 核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。 Returns: - 本次实际通知的发票数。 + send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed """ - if not enabled or not missing_items: - return 0 + missing_files = int(stats.get("missing_file_count") or 0) + missing_invoices = int(stats.get("missing_invoice_count") or 0) + summary = { + "profile_code": profile_code, + "period": period_month, + "subject_count": int(stats.get("subject_count") or 0), + "missing_file_count": missing_files, + "missing_invoice_count": missing_invoices, + "run_no": schedule_run.run_no, + } + recipient_ids = [int(u.id) for u in _recipient_users(task)] + + if not enabled: + persist_notification( + run_id=engine_run_id, + excel_filename=excel_filename, + recipient_user_ids=recipient_ids, + send_status="skipped_disabled", + skip_reason="notify_missing_enabled=false", + summary=summary, + sent_at=None, + ) + db.session.commit() + return "skipped_disabled" + + if missing_files <= 0: + persist_notification( + run_id=engine_run_id, + excel_filename=excel_filename, + recipient_user_ids=recipient_ids, + send_status="skipped_no_missing", + skip_reason="本批无缺件", + summary=summary, + sent_at=None, + ) + db.session.commit() + return "skipped_no_missing" + if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): - return 0 + persist_notification( + run_id=engine_run_id, + excel_filename=excel_filename, + recipient_user_ids=recipient_ids, + send_status="skipped_disabled", + skip_reason="WECOM_NOTIFY_ENABLED=false", + summary=summary, + sent_at=None, + ) + db.session.commit() + return "skipped_disabled" + + users = _recipient_users(task) + if not users: + persist_notification( + run_id=engine_run_id, + excel_filename=excel_filename, + recipient_user_ids=[], + send_status="skipped_no_recipients", + skip_reason="未配置企业微信接收人", + summary=summary, + sent_at=None, + ) + db.session.commit() + return "skipped_no_recipients" - from app.models.voucher_check import VoucherCheckInvoiceState from app.services.wecom_notify import ( _build_jump_url, _create_audit, send_wecom_textcard_message, ) - today = _today_shanghai() - invoice_nos = [str(i["invoice_no"]).strip() for i in missing_items] - states = ( - db.session.query(VoucherCheckInvoiceState) - .filter( - VoucherCheckInvoiceState.scope_code == scope_code, - VoucherCheckInvoiceState.period_month == period_month, - VoucherCheckInvoiceState.invoice_no.in_(invoice_nos), - ) - .all() + type_stats = stats.get("by_file_type") or {} + top_missing = sorted( + ( + (item.get("rule_name") or key, int(item.get("missing_file_count") or 0)) + for key, item in type_stats.items() + if isinstance(item, dict) + ), + key=lambda pair: pair[1], + reverse=True, ) - state_map = {s.invoice_no: s for s in states} - to_notify: list[dict[str, Any]] = [] - for item in missing_items: - inv = str(item["invoice_no"]).strip() - state = state_map.get(inv) - if same_day_dedup and state and state.last_missing_notified_on == today: - continue - to_notify.append(item) - if not to_notify: - return 0 - - users = _recipient_users(task) - if not users: - current_app.logger.warning( - "[voucher-check] missing notify skipped: no wecom recipients run_id=%s", - run.id, - ) - return 0 - - sample = "、".join(i["invoice_no"] for i in to_notify[:8]) - if len(to_notify) > 8: - sample += "…" - period = period_month.strftime("%Y-%m") - title = f"立账凭证缺资料: {task.name}" + top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4] + title = f"立账凭证缺件汇总: {task.name}" description = ( - f"批次 {run.run_no}\n" - f"检核月份 {period}\n" - f"缺资料 {len(to_notify)} 张\n" - f"示例:{sample}\n" - f"完整清单请查看工作台检核记录或 Excel。" + f"业务方 {profile_code}\n" + f"资料所属期间 {period_month}\n" + f"批次 {schedule_run.run_no}\n" + f"主体 {int(stats.get('subject_count') or 0)} 张\n" + f"缺件文件 {missing_files} / 缺件 invoice {missing_invoices}\n" + f"主要缺失:{'、'.join(top_missing) or '—'}\n" + f"明细以工作台 Excel 为准。" ) ok_any = False for user in users: @@ -116,7 +146,7 @@ def send_missing_notifications( jump_url = _build_jump_url( "/workspace/accounting-voucher-check", trace_id, - {"task_id": task.id, "run_id": run.id}, + {"task_id": task.id, "run_id": schedule_run.id}, ) try: audit = _create_audit("voucher_check_missing", user, title, description, trace_id) @@ -130,20 +160,22 @@ def send_missing_notifications( audit.error_message = str(data.get("errmsg", "unknown"))[:255] except Exception as exc: current_app.logger.warning( - "[voucher-check] missing notify failed user=%s err=%s", + "[voucher-check] batch notify failed user=%s err=%s", user.id, exc, ) - if ok_any: - mark_missing_notified( - scope_code=scope_code, - period_month=period_month, - invoice_nos=[str(i["invoice_no"]).strip() for i in to_notify], - notified_on=today, - ) - db.session.commit() - return len(to_notify) - return 0 + status = "sent" if ok_any else "failed" + persist_notification( + run_id=engine_run_id, + excel_filename=excel_filename, + recipient_user_ids=recipient_ids, + send_status=status, + skip_reason=None if ok_any else "企业微信发送失败", + summary=summary, + sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None, + ) + db.session.commit() + return status def send_failure_alert( @@ -155,7 +187,7 @@ def send_failure_alert( error_message: str, enabled: bool, ) -> None: - """批次级失败告警(共享盘/Oracle/业务配置异常)。""" + """批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。""" if not enabled: return if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): @@ -178,7 +210,7 @@ def send_failure_alert( f"错误码:{error_code}\n" f"摘要:{(error_message or '')[:200]}\n" f"run_id={run.id}\n" - f"请检查 Oracle 连接与共享盘挂载/健康标记。" + f"请检查 Oracle 与文档库连接。" ) for user in users: trace_id = uuid.uuid4().hex diff --git a/backend/app/services/voucher_check/openapi_base.json b/backend/app/services/voucher_check/openapi_base.json deleted file mode 100644 index 372a97c4..00000000 --- a/backend/app/services/voucher_check/openapi_base.json +++ /dev/null @@ -1,316 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "HXOPS Accounting Voucher Check Tool API", - "description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://127.0.0.1:5052", - "description": "HXOPS_TOOLS_API_BASE" - } - ], - "security": [ - { - "BearerAuth": [] - }, - { - "IntegrationKey": [] - } - ], - "paths": { - "/api/accounting-voucher-check/tools/tasks/{task_id}/missing": { - "get": { - "operationId": "list_voucher_missing", - "summary": "查询缺资料发票(最新状态)", - "description": "按账套与月份查询 status=missing 的发票;默认当前自然月。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "task_id", - "in": "path", - "required": true, - "schema": { "type": "integer", "example": 12 }, - "description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { "type": "string", "example": "2026-08" }, - "description": "检核月份 YYYY-MM;缺省为当前自然月" - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { "type": "string", "default": "HXJM", "example": "HXJM" } - }, - { - "name": "limit", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 200, "minimum": 1, "maximum": 1000 } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/MissingListResponse" } - } - } - }, - "400": { "$ref": "#/components/responses/BadRequest" }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - }, - "/api/accounting-voucher-check/tools/runs/{run_id}/items": { - "get": { - "operationId": "list_voucher_run_items", - "summary": "查询批次发票明细", - "description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "run_id", - "in": "path", - "required": true, - "schema": { "type": "integer", "example": 1001 } - }, - { - "name": "result", - "in": "query", - "required": false, - "schema": { - "type": "string", - "enum": ["complete", "missing", "skipped", "technical_error"], - "example": "missing" - } - }, - { - "name": "page", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 1, "minimum": 1 } - }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/RunItemsResponse" } - } - } - }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "404": { "$ref": "#/components/responses/NotFound" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - }, - "/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": { - "get": { - "operationId": "get_voucher_invoice_latest", - "summary": "查询指定发票最新检核状态", - "description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "invoice_no", - "in": "path", - "required": true, - "schema": { "type": "string", "example": "INV-20260803001" }, - "description": "发票号(apa08 原值)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { "type": "string", "example": "2026-08" } - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { "type": "string", "default": "HXJM" } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/InvoiceLatestResponse" } - } - } - }, - "400": { "$ref": "#/components/responses/BadRequest" }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "404": { "$ref": "#/components/responses/NotFound" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - } - }, - "components": { - "securitySchemes": { - "BearerAuth": { - "type": "http", - "scheme": "bearer", - "description": "Authorization: Bearer " - }, - "IntegrationKey": { - "type": "apiKey", - "in": "header", - "name": "X-Integration-Key", - "description": "与 Bearer 二选一" - } - }, - "schemas": { - "MissingMaterial": { - "type": "object", - "properties": { - "code": { "type": "string", "example": "price_check_sheet" }, - "name": { "type": "string", "example": "核价单" } - } - }, - "InvoiceState": { - "type": "object", - "properties": { - "id": { "type": "integer" }, - "scope_code": { "type": "string" }, - "period_month": { "type": "string", "nullable": true }, - "invoice_no": { "type": "string" }, - "invoice_date": { "type": "string", "nullable": true }, - "status": { "type": "string", "enum": ["complete", "missing"] }, - "folder_path": { "type": "string", "nullable": true }, - "folder_exists": { "type": "boolean" }, - "matched_files": { "type": "object", "additionalProperties": { "type": "string" } }, - "missing_materials": { - "type": "array", - "items": { "$ref": "#/components/schemas/MissingMaterial" } - }, - "last_checked_at": { "type": "string", "nullable": true } - } - }, - "MissingListResponse": { - "type": "object", - "required": ["ok", "items", "count"], - "properties": { - "ok": { "type": "boolean", "example": true }, - "task_id": { "type": "integer", "nullable": true }, - "scope_code": { "type": "string" }, - "period": { "type": "string", "example": "2026-08" }, - "count": { "type": "integer" }, - "items": { - "type": "array", - "items": { "$ref": "#/components/schemas/InvoiceState" } - } - } - }, - "RunItem": { - "type": "object", - "properties": { - "id": { "type": "integer" }, - "schedule_run_id": { "type": "integer" }, - "invoice_no": { "type": "string" }, - "result": { - "type": "string", - "enum": ["complete", "missing", "skipped", "technical_error"] - }, - "folder_path": { "type": "string", "nullable": true }, - "matched_files": { "type": "object", "additionalProperties": { "type": "string" } }, - "missing_materials": { - "type": "array", - "items": { "$ref": "#/components/schemas/MissingMaterial" } - }, - "error_code": { "type": "string", "nullable": true }, - "error_message": { "type": "string", "nullable": true } - } - }, - "RunItemsResponse": { - "type": "object", - "required": ["ok", "items", "total"], - "properties": { - "ok": { "type": "boolean" }, - "run_id": { "type": "integer" }, - "run_no": { "type": "string" }, - "page": { "type": "integer" }, - "page_size": { "type": "integer" }, - "total": { "type": "integer" }, - "items": { - "type": "array", - "items": { "$ref": "#/components/schemas/RunItem" } - } - } - }, - "InvoiceLatestResponse": { - "type": "object", - "required": ["ok", "state"], - "properties": { - "ok": { "type": "boolean" }, - "state": { "$ref": "#/components/schemas/InvoiceState" }, - "recent_run_items": { - "type": "array", - "items": { "$ref": "#/components/schemas/RunItem" } - } - } - }, - "ToolError": { - "type": "object", - "properties": { - "ok": { "type": "boolean", "example": false }, - "error_code": { "type": "string" }, - "message": { "type": "string" }, - "details": { "type": "object" } - } - } - }, - "responses": { - "BadRequest": { - "description": "参数错误", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "Unauthorized": { - "description": "鉴权失败", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "NotFound": { - "description": "资源不存在", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "MissingAuth": { - "description": "服务端未配置 Tool API Key", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - } - } - } -} diff --git a/backend/app/services/voucher_check/openapi_spec.py b/backend/app/services/voucher_check/openapi_spec.py deleted file mode 100644 index ce8f976f..00000000 --- a/backend/app/services/voucher_check/openapi_spec.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -backend/app/services/voucher_check/openapi_spec.py - -用途:构建立账凭证检核 Chatflow 查询 Tool 的 OpenAPI 3.0 规范。 -依赖:openapi_base.json。 -逻辑:GET /api/accounting-voucher-check/tools/openapi.json 调用本模块;Dify URL 导入。 -""" - -from __future__ import annotations - -import copy -import json -from pathlib import Path -from typing import Any - -_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json") - - -def _load_base_spec() -> dict[str, Any]: - with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp: - return json.load(fp) - - -def build_voucher_check_openapi_spec(base_url: str) -> dict[str, Any]: - """ - 构建立账凭证检核 Tool OpenAPI。 - 核心逻辑:深拷贝静态规格,并将 servers[0].url 替换为当前 HXOPS_TOOLS_API_BASE。 - """ - spec = copy.deepcopy(_load_base_spec()) - base = str(base_url or "").strip().rstrip("/") - servers = spec.get("servers") - if base and isinstance(servers, list) and servers: - servers[0]["url"] = base - servers[0]["description"] = "HXOPS_TOOLS_API_BASE" - return spec diff --git a/backend/app/services/voucher_check/persistence.py b/backend/app/services/voucher_check/persistence.py deleted file mode 100644 index 74e75271..00000000 --- a/backend/app/services/voucher_check/persistence.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -backend/app/services/voucher_check/persistence.py - -用途:立账凭证检核单票状态与批次明细的事务写入。 -依赖:models.voucher_check、ScheduleRun、SQLAlchemy session。 -逻辑:runner 阶段 B 调用;skipped 只更新 last_seen_erp_at;批次级失败不进入本模块。 -""" - -from __future__ import annotations - -from datetime import date, datetime -from typing import Any - -from app import db -from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem - - -def persist_batch_results( - *, - schedule_run_id: int, - scope_code: str, - period_month: date, - items: list[dict[str, Any]], - now: datetime | None = None, -) -> None: - """ - 单事务写入批次明细并 upsert 最新状态。 - 核心逻辑:先写 run_items;非 skipped/technical_error 再 upsert states; - skipped 仅刷新 last_seen_erp_at。 - - Args: - schedule_run_id: ScheduleRun.id - scope_code: 账套 - period_month: 当月首日 - items: 内存中的结果行(含 result / fingerprint / missing 等) - now: 可选时钟 - """ - ts = now or datetime.utcnow() - for item in items: - invoice_no = str(item["invoice_no"]).strip() - result = str(item["result"]) - run_item = VoucherCheckRunItem( - schedule_run_id=schedule_run_id, - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - invoice_date=item.get("invoice_date"), - result=result, - folder_path=item.get("folder_path"), - folder_exists=bool(item.get("folder_exists")), - material_fingerprint=item.get("material_fingerprint"), - matched_files_json=item.get("matched_files") or {}, - missing_materials_json=item.get("missing_materials") or [], - error_code=item.get("error_code"), - error_message=item.get("error_message"), - checked_at=item.get("checked_at"), - created_at=ts, - ) - db.session.add(run_item) - - state = ( - db.session.query(VoucherCheckInvoiceState) - .filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - ) - .one_or_none() - ) - if state is None: - state = VoucherCheckInvoiceState( - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - created_at=ts, - ) - db.session.add(state) - - state.last_seen_erp_at = ts - state.invoice_date = item.get("invoice_date") or state.invoice_date - state.updated_at = ts - - if result == "skipped": - # 跳过:不改写齐全结论与实际扫描时间 - continue - if result == "technical_error": - continue - - state.status = "complete" if result == "complete" else "missing" - state.folder_path = item.get("folder_path") - state.folder_exists = bool(item.get("folder_exists")) - state.material_fingerprint = item.get("material_fingerprint") - state.matched_files_json = item.get("matched_files") or {} - state.missing_materials_json = item.get("missing_materials") or [] - state.last_actual_run_id = schedule_run_id - state.last_checked_at = item.get("checked_at") or ts - - db.session.flush() - run_item.invoice_state_id = state.id - - db.session.flush() - - -def mark_missing_notified( - *, - scope_code: str, - period_month: date, - invoice_nos: list[str], - notified_on: date, -) -> None: - """发送缺资料通知成功后更新同票同日节流字段。""" - if not invoice_nos: - return - states = ( - db.session.query(VoucherCheckInvoiceState) - .filter( - VoucherCheckInvoiceState.scope_code == scope_code, - VoucherCheckInvoiceState.period_month == period_month, - VoucherCheckInvoiceState.invoice_no.in_(invoice_nos), - ) - .all() - ) - for state in states: - state.last_missing_notified_on = notified_on - state.updated_at = datetime.utcnow() - db.session.flush() diff --git a/backend/app/services/voucher_check/profile_loader.py b/backend/app/services/voucher_check/profile_loader.py new file mode 100644 index 00000000..d5bb8038 --- /dev/null +++ b/backend/app/services/voucher_check/profile_loader.py @@ -0,0 +1,70 @@ +""" +backend/app/services/voucher_check/profile_loader.py + +用途:加载销售 Profile 并确保数据库中有对应已发布快照。 +依赖:profiles 目录、models.VoucherCheckProfile。 +逻辑:批次绑定 definition_json 快照;运行中不以表热更新覆盖已开始的批次。 +""" + +from __future__ import annotations + +import copy +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ValidationError +from app.models.voucher_check import VoucherCheckProfile +from app.services.voucher_check.profiles import PROFILE_CATALOG + + +def load_profile_definition(profile_code: str = "sales") -> dict[str, Any]: + """ + 读取内置 Profile 定义的深拷贝。 + 核心逻辑:未知 profile_code 在批次开始前失败。 + """ + code = str(profile_code or "sales").strip() or "sales" + definition = PROFILE_CATALOG.get(code) + if not definition: + raise ValidationError( + f"未知 Profile: {code}", + code="VOUCHER_CHECK.CONFIG_INVALID", + details={"profile_code": code}, + ) + snapshot = copy.deepcopy(definition) + if not snapshot.get("file_rules"): + raise ValidationError("Profile 缺少 file_rules", code="VOUCHER_CHECK.CONFIG_INVALID") + return snapshot + + +def ensure_published_profile(profile_code: str = "sales") -> VoucherCheckProfile: + """ + 幂等写入已发布 Profile 行,供审计;批次仍使用内存快照。 + """ + snapshot = load_profile_definition(profile_code) + code = str(snapshot["profile_code"]) + version = str(snapshot["profile_version"]) + row = ( + db.session.query(VoucherCheckProfile) + .filter_by(profile_code=code, version=version) + .one_or_none() + ) + now = datetime.utcnow() + if row is None: + row = VoucherCheckProfile( + profile_code=code, + version=version, + definition_json=snapshot, + status="published", + created_at=now, + updated_at=now, + ) + db.session.add(row) + db.session.flush() + return row + if row.status != "published" or row.definition_json != snapshot: + row.definition_json = snapshot + row.status = "published" + row.updated_at = now + db.session.flush() + return row diff --git a/backend/app/services/voucher_check/profiles/__init__.py b/backend/app/services/voucher_check/profiles/__init__.py new file mode 100644 index 00000000..2b173420 --- /dev/null +++ b/backend/app/services/voucher_check/profiles/__init__.py @@ -0,0 +1,15 @@ +""" +backend/app/services/voucher_check/profiles/__init__.py + +用途:业务方 Profile 包入口。 +依赖:sales 销售一期定义。 +逻辑:profile_loader 按 profile_code 加载;新增业务方在此登记。 +""" + +from app.services.voucher_check.profiles.sales import SALES_PROFILE, SALES_PROFILE_CODE, SALES_PROFILE_VERSION + +PROFILE_CATALOG = { + SALES_PROFILE_CODE: SALES_PROFILE, +} + +__all__ = ["PROFILE_CATALOG", "SALES_PROFILE", "SALES_PROFILE_CODE", "SALES_PROFILE_VERSION"] diff --git a/backend/app/services/voucher_check/profiles/sales.py b/backend/app/services/voucher_check/profiles/sales.py new file mode 100644 index 00000000..0c24e95c --- /dev/null +++ b/backend/app/services/voucher_check/profiles/sales.py @@ -0,0 +1,92 @@ +""" +backend/app/services/voucher_check/profiles/sales.py + +用途:销售一期 Profile 定义(六类必检文件、类型目录、命名模板)。 +依赖:无外部 IO;由 profile_loader 发布快照。 +逻辑:周任务扫描 source_type=directory_scan;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。 +""" + +from __future__ import annotations + +from typing import Any + +SALES_PROFILE_CODE = "sales" +SALES_PROFILE_VERSION = "v1" + +SALES_PROFILE: dict[str, Any] = { + "profile_code": SALES_PROFILE_CODE, + "profile_version": SALES_PROFILE_VERSION, + "scope_code": "HXJM", + "subject_adapter": "hxjm_apa", + "dms": { + "year_folder_template": "{yyyy}", + "month_folder_template": "{MM}", + "archive_folder": "所有归档", + }, + "file_rules": [ + { + "code": "po_order", + "name": "PO订单", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": "erp_po_print", + "type_folder": "PO订单", + "filename_template": "{invoice}-{order_no}.pdf", + }, + { + "code": "customs_pack", + "name": "报关资料", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": None, + "type_folder": "报关资料", + "filename_template": "{invoice}.pdf", + }, + { + "code": "sales_release", + "name": "销货放行申请单", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": "oa_sales_release", + "type_folder": "销货单", + "filename_template": "{invoice}-{delivery_no}.pdf", + }, + { + "code": "tax_invoice", + "name": "发票", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": None, + "type_folder": "发票", + "filename_template": "{invoice}-{tax_invoice_no}.pdf", + }, + { + "code": "customs_declaration", + "name": "报关单", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": None, + "type_folder": "报关单", + "filename_template": "{invoice}-{customs_no}.pdf", + }, + { + "code": "bill_of_lading", + "name": "提单", + "required": True, + "source_type": "directory_scan", + "acquire_adapter": None, + "type_folder": "提单", + "filename_template": "{invoice}-提单.pdf", + }, + ], +} + + +def required_file_rules(definition: dict[str, Any] | None = None) -> list[dict[str, Any]]: + """ + 返回必检文件规则列表。 + 核心逻辑:过滤 required=true,保持 Profile 声明顺序供 Excel 动态列使用。 + """ + payload = definition or SALES_PROFILE + rules = payload.get("file_rules") or [] + return [rule for rule in rules if isinstance(rule, dict) and rule.get("required", True)] diff --git a/backend/app/services/voucher_check/query_service.py b/backend/app/services/voucher_check/query_service.py index 61eefc70..4219013a 100644 --- a/backend/app/services/voucher_check/query_service.py +++ b/backend/app/services/voucher_check/query_service.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/query_service.py -用途:查询批次明细、当月缺资料与单票最新状态。 -依赖:models.voucher_check、ScheduleRun。 -逻辑:Tool API 与工作台 API 调用;不触发扫描。 +用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。 +依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。 +逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。 """ from __future__ import annotations @@ -11,61 +11,21 @@ from __future__ import annotations from datetime import date, datetime from typing import Any -from app.core.errors import NotFoundError, ValidationError -from app.models import ScheduleRun -from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem -from app.services.voucher_check.erp_repository import current_period_bounds - - -def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]: - return { - "id": state.id, - "scope_code": state.scope_code, - "period_month": state.period_month.isoformat() if state.period_month else None, - "invoice_no": state.invoice_no, - "invoice_date": state.invoice_date.isoformat() if state.invoice_date else None, - "status": state.status, - "folder_path": state.folder_path, - "folder_exists": state.folder_exists, - "material_fingerprint": state.material_fingerprint, - "matched_files": state.matched_files_json or {}, - "missing_materials": state.missing_materials_json or [], - "last_actual_run_id": state.last_actual_run_id, - "last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None, - "last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None, - "last_missing_notified_on": ( - state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None - ), - "updated_at": state.updated_at.isoformat() if state.updated_at else None, - } - - -def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]: - return { - "id": item.id, - "schedule_run_id": item.schedule_run_id, - "invoice_state_id": item.invoice_state_id, - "scope_code": item.scope_code, - "period_month": item.period_month.isoformat() if item.period_month else None, - "invoice_no": item.invoice_no, - "invoice_date": item.invoice_date.isoformat() if item.invoice_date else None, - "result": item.result, - "folder_path": item.folder_path, - "folder_exists": item.folder_exists, - "material_fingerprint": item.material_fingerprint, - "matched_files": item.matched_files_json or {}, - "missing_materials": item.missing_materials_json or [], - "error_code": item.error_code, - "error_message": item.error_message, - "checked_at": item.checked_at.isoformat() if item.checked_at else None, - "created_at": item.created_at.isoformat() if item.created_at else None, - } +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ScheduleRun, ScheduleTask, User +from app.models.voucher_check import ( + VoucherCheckFileResult, + VoucherCheckNotification, + VoucherCheckRun, +) +from app.services.voucher_check.aggregator import aggregate_file_results +from app.services.voucher_check.erp_repository import previous_period_bounds def parse_period_month(raw: str | None) -> date: - """解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。""" + """解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。""" if not raw: - period_month, *_ = current_period_bounds() + period_month, *_ = previous_period_bounds() return period_month text = str(raw).strip() try: @@ -81,38 +41,191 @@ def parse_period_month(raw: str | None) -> date: ) from exc -def list_missing_states( +def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]: + return { + "id": run.id, + "schedule_run_id": run.schedule_run_id, + "run_no": run.run_no, + "profile_code": run.profile_code, + "period_month": run.period_month.strftime("%Y-%m") if run.period_month else None, + "mode": run.mode, + "status": run.status, + "subject_count": int(run.subject_count or 0), + "archived_file_count": int(run.archived_file_count or 0), + "missing_file_count": int(run.missing_file_count or 0), + "missing_invoice_count": int(run.missing_invoice_count or 0), + "technical_error_count": int(run.technical_error_count or 0), + "staged_file_count": int(run.staged_file_count or 0), + "skipped_file_count": int(run.skipped_file_count or 0), + "started_at": run.started_at.isoformat() if run.started_at else None, + "finished_at": run.finished_at.isoformat() if run.finished_at else None, + } + + +def _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]: + """ + 序列化尚未创建引擎批次的立账凭证排程记录。 + 核心逻辑:配置或外部依赖在引擎建批前失败时,仍须在工作台展示失败原因, + 避免用户只能看到空列表而无法判断强制重检是否已执行。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + voucher_summary = summary.get("voucher_check") if isinstance(summary.get("voucher_check"), dict) else {} + period_month, *_ = previous_period_bounds() + return { + "id": run.id, + "schedule_run_id": run.id, + "run_no": run.run_no, + "profile_code": str(voucher_summary.get("profile_code") or "sales"), + "period_month": str(voucher_summary.get("period") or period_month.strftime("%Y-%m")), + "mode": str(voucher_summary.get("mode") or "incremental"), + # 工作台按引擎状态筛选;排程在建批前失败统一映射为技术失败。 + "status": "technical_failed", + "subject_count": int(run.total_count or 0), + "archived_file_count": 0, + "missing_file_count": 0, + "missing_invoice_count": 0, + "technical_error_count": 1 if run.status == "failed" else 0, + "staged_file_count": 0, + "skipped_file_count": int(run.skipped_count or 0), + "started_at": run.started_at.isoformat() if run.started_at else None, + "finished_at": run.finished_at.isoformat() if run.finished_at else None, + "error_message": run.error_message, + } + + +def list_runs( *, - task_id: int | None = None, - scope_code: str = "HXJM", period: str | None = None, - limit: int = 200, + profile_code: str | None = None, + status: str | None = None, + page: int = 1, + page_size: int = 50, ) -> dict[str, Any]: """ - 查询指定月份缺资料票(最新状态表)。 - task_id 预留与排程绑定校验,本期仅用于响应回显。 + 工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。 + 核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在 + create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。 """ - period_month = parse_period_month(period) - limit = max(1, min(int(limit or 200), 1000)) - q = ( - VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, - status="missing", + page = max(1, int(page or 1)) + page_size = max(1, min(int(page_size or 50), 200)) + q = VoucherCheckRun.query + if period: + q = q.filter(VoucherCheckRun.period_month == parse_period_month(period)) + if profile_code: + q = q.filter(VoucherCheckRun.profile_code == str(profile_code).strip()) + if status: + q = q.filter(VoucherCheckRun.status == str(status).strip()) + engine_rows = q.order_by(VoucherCheckRun.id.desc()).all() + engine_schedule_run_ids = {row.schedule_run_id for row in engine_rows if row.schedule_run_id} + fallback_query = ( + ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id) + .filter( + ScheduleTask.platform_api_path == "accounting-voucher-check", + ScheduleRun.status == "failed", ) - .order_by(VoucherCheckInvoiceState.invoice_no.asc()) - .limit(limit) ) - items = [_serialize_state(s) for s in q.all()] + if status and str(status).strip() != "technical_failed": + fallback_rows: list[ScheduleRun] = [] + else: + fallback_rows = fallback_query.order_by(ScheduleRun.id.desc()).all() + fallback_rows = [ + row + for row in fallback_rows + if row.id not in engine_schedule_run_ids + and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m")) + ] + merged = [_serialize_engine_run(row) for row in engine_rows] + merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows) + merged.sort(key=lambda row: row.get("finished_at") or row.get("started_at") or "", reverse=True) + total = len(merged) + rows = merged[(page - 1) * page_size : page * page_size] return { - "task_id": task_id, - "scope_code": scope_code, - "period": period_month.strftime("%Y-%m"), - "count": len(items), - "items": items, + "page": page, + "page_size": page_size, + "total": total, + "items": rows, } +def _serialize_file_type_rows(aggregated: dict[str, Any]) -> list[dict[str, Any]]: + """ + 将聚合器的 by_file_type 转成工作台「按文件类型」表格行。 + 核心逻辑:缺失占比 = 该类型缺件 invoice 数 / 本批主体总数。 + """ + subject_count = int(aggregated.get("subject_count") or 0) + by_type = aggregated.get("by_file_type") or {} + rows: list[dict[str, Any]] = [] + for item in by_type.values(): + if not isinstance(item, dict): + continue + missing_invoices = int(item.get("missing_invoice_count") or 0) + ratio = (missing_invoices / subject_count) if subject_count else 0.0 + rows.append( + { + "rule_code": item.get("rule_code"), + "rule_name": item.get("rule_name"), + "missing_file_count": int(item.get("missing_file_count") or 0), + "missing_invoice_count": missing_invoices, + "missing_ratio": round(ratio, 4), + } + ) + return rows + + +def _engine_invoice_items(engine_run: VoucherCheckRun) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """ + 将单文件结果聚合成 invoice 行,并返回同一批的类型汇总。 + 核心逻辑:按 invoice 汇总缺件材料;类型汇总来自聚合器,不受 invoice 行筛选影响。 + """ + rows = ( + VoucherCheckFileResult.query.filter_by(run_id=engine_run.id) + .order_by(VoucherCheckFileResult.invoice_no.asc(), VoucherCheckFileResult.id.asc()) + .all() + ) + payload = [ + { + "invoice_no": row.invoice_no, + "rule_code": row.rule_code, + "rule_name": row.rule_name, + "status": row.status, + "invoice_date": None, + } + for row in rows + ] + rules = (engine_run.profile_snapshot_json or {}).get("file_rules") or [] + aggregated = aggregate_file_results(payload, rules=rules) + items: list[dict[str, Any]] = [] + for excel_row in aggregated["excel_rows"]: + missing = [ + {"code": code, "name": next((r.get("name") for r in rules if r.get("code") == code), code)} + for code, cell in (excel_row.get("cells") or {}).items() + if cell == "缺件" + ] + mapped_status = { + "完整": "complete", + "缺件": "missing", + "待处理": "pending", + }.get(str(excel_row.get("status") or ""), "pending") + items.append( + { + "id": 0, + "invoice_no": excel_row["invoice_no"], + "invoice_date": None, + "result": mapped_status, + "cells": excel_row.get("cells") or {}, + "status_label": excel_row.get("status"), + "missing_materials": missing, + "missing_count": len(missing), + "folder_path": None, + "folder_exists": False, + "error_code": None, + "error_message": None, + "checked_at": engine_run.finished_at.isoformat() if engine_run.finished_at else None, + } + ) + return items, aggregated + + def list_run_items( *, run_id: int, @@ -120,101 +233,202 @@ def list_run_items( page: int = 1, page_size: int = 50, ) -> dict[str, Any]: - """分页查询批次明细。""" + """分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。""" run = ScheduleRun.query.get(run_id) if not run: raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND") page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) - q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id) - if result: - q = q.filter(VoucherCheckRunItem.result == str(result).strip()) - total = q.count() - rows = ( - q.order_by(VoucherCheckRunItem.invoice_no.asc()) - .offset((page - 1) * page_size) - .limit(page_size) - .all() + engine_run = ( + VoucherCheckRun.query.filter_by(schedule_run_id=run_id) + .order_by(VoucherCheckRun.id.desc()) + .first() ) + if engine_run is None: + return { + "run_id": run_id, + "run_no": run.run_no, + "page": page, + "page_size": page_size, + "total": 0, + "items": [], + "subject_count": 0, + "by_file_type": [], + } + items, aggregated = _engine_invoice_items(engine_run) + result_filter = str(result).strip() if result else "" + if result_filter: + items = [row for row in items if row.get("result") == result_filter] + total = len(items) + sliced = items[(page - 1) * page_size : page * page_size] return { "run_id": run_id, + "engine_run_id": engine_run.id, "run_no": run.run_no, "page": page, "page_size": page_size, "total": total, - "items": [_serialize_run_item(r) for r in rows], + "items": sliced, + "subject_count": int(aggregated.get("subject_count") or 0), + "by_file_type": _serialize_file_type_rows(aggregated), } -def get_invoice_latest( +def list_notifications( *, - invoice_no: str, - scope_code: str = "HXJM", period: str | None = None, -) -> dict[str, Any]: - """查询单票最新状态及近期批次快照。""" - inv = str(invoice_no or "").strip() - if not inv: - raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED") - period_month = parse_period_month(period) - state = ( - VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=inv, - ).one_or_none() - ) - if not state: - raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND") - history = ( - VoucherCheckRunItem.query.filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=inv, - ) - .order_by(VoucherCheckRunItem.id.desc()) - .limit(20) - .all() - ) - return { - "state": _serialize_state(state), - "recent_run_items": [_serialize_run_item(h) for h in history], - } - - -def list_states( - *, - scope_code: str = "HXJM", - period: str | None = None, - status: str | None = None, - invoice_no: str | None = None, + send_status: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: - """工作台:按月/状态/发票号筛选最新状态。""" - period_month = parse_period_month(period) + """ + 分页查询企微缺件汇总发送记录。 + 核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。 + """ page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) - q = VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, + q = VoucherCheckNotification.query.join( + VoucherCheckRun, + VoucherCheckNotification.run_id == VoucherCheckRun.id, ) - if status: - q = q.filter(VoucherCheckInvoiceState.status == str(status).strip()) - if invoice_no: - q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%")) + if period: + q = q.filter(VoucherCheckRun.period_month == parse_period_month(period)) + status_filter = str(send_status or "").strip() + if status_filter: + q = q.filter(VoucherCheckNotification.send_status == status_filter) total = q.count() rows = ( - q.order_by(VoucherCheckInvoiceState.invoice_no.asc()) + q.order_by(VoucherCheckNotification.id.desc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) + engine_runs = { + run.id: run + for run in VoucherCheckRun.query.filter( + VoucherCheckRun.id.in_([row.run_id for row in rows] or [0]) + ).all() + } + schedule_ids = [ + engine_runs[row.run_id].schedule_run_id + for row in rows + if row.run_id in engine_runs and engine_runs[row.run_id].schedule_run_id + ] + schedule_map = { + item.id: item + for item in ScheduleRun.query.filter(ScheduleRun.id.in_(schedule_ids or [0])).all() + } + recipient_ids: set[int] = set() + for row in rows: + for raw in row.recipient_user_ids_json or []: + try: + recipient_ids.add(int(raw)) + except (TypeError, ValueError): + continue + users = { + user.id: user + for user in (User.query.filter(User.id.in_(recipient_ids)).all() if recipient_ids else []) + } + items: list[dict[str, Any]] = [] + for row in rows: + engine_run = engine_runs.get(row.run_id) + summary = row.summary_json if isinstance(row.summary_json, dict) else {} + names: list[str] = [] + for raw in row.recipient_user_ids_json or []: + try: + user = users.get(int(raw)) + except (TypeError, ValueError): + user = None + if user: + names.append(str(user.real_name or user.username or user.id)) + schedule_run_id = engine_run.schedule_run_id if engine_run else None + schedule_run = schedule_map.get(schedule_run_id) if schedule_run_id else None + items.append( + { + "id": row.id, + "run_id": row.run_id, + "schedule_run_id": schedule_run_id, + "run_no": ( + (engine_run.run_no if engine_run else None) + or summary.get("run_no") + or (schedule_run.run_no if schedule_run else None) + ), + "period_month": ( + engine_run.period_month.strftime("%Y-%m") + if engine_run and engine_run.period_month + else summary.get("period") + ), + "subject_count": int( + (engine_run.subject_count if engine_run else None) or summary.get("subject_count") or 0 + ), + "missing_file_count": int( + (engine_run.missing_file_count if engine_run else None) + or summary.get("missing_file_count") + or 0 + ), + "missing_invoice_count": int( + (engine_run.missing_invoice_count if engine_run else None) + or summary.get("missing_invoice_count") + or 0 + ), + "send_status": row.send_status, + "skip_reason": row.skip_reason, + "excel_filename": row.excel_filename or (schedule_run.excel_file_name if schedule_run else None), + "has_excel": bool(schedule_run and schedule_run.excel_file_name), + "recipient_names": names, + "sent_at": row.sent_at.isoformat() if row.sent_at else None, + "created_at": row.created_at.isoformat() if row.created_at else None, + } + ) return { - "scope_code": scope_code, - "period": period_month.strftime("%Y-%m"), "page": page, "page_size": page_size, "total": total, - "items": [_serialize_state(r) for r in rows], + "items": items, + } + + +def enqueue_force_all_run(*, triggered_by_user_id: int | None) -> dict[str, Any]: + """ + 将默认立账凭证排程以 force_all 入队,全量重检上一个自然月。 + 核心逻辑:复用周批 ScheduleTask;已有 queued/running 时冲突失败,不覆盖进行中的批次。 + """ + from app.services.schedule.queue_service import enqueue_manual_schedule_run + from app.services.voucher_check.config import load_engine_config + from app.services.voucher_check.dms_client import SalesDmsClient + from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition + from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule + + task = ensure_default_voucher_check_schedule(commit=True) + if task is None: + raise NotFoundError( + "未找到立账凭证检核排程任务", + code="VOUCHER_CHECK.SCHEDULE_NOT_FOUND", + ) + # [STEP 1] 入队前完成不依赖外部 IO 的配置预校验,避免 worker 失败后页面空白。 + config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {}) + profile = load_profile_definition(config.profile_code) + ensure_published_profile(config.profile_code) + SalesDmsClient.ensure_configured() + run, job_id, created = enqueue_manual_schedule_run( + task.id, + triggered_by_user_id=triggered_by_user_id, + api_request_json={ + "trigger_source": "workspace_force_all", + "run_options": {"mode": "force_all"}, + }, + ) + if not created: + raise ConflictError( + "立账凭证检核正在执行或排队中", + code="VOUCHER_CHECK.RUN_IN_PROGRESS", + details={"schedule_run_id": run.id, "run_no": run.run_no}, + ) + return { + "schedule_task_id": task.id, + "schedule_run_id": run.id, + "run_no": run.run_no, + "job_id": job_id, + "mode": "force_all", + "status": run.status, } diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py index dcdbbe9d..9d99991d 100644 --- a/backend/app/services/voucher_check/runner.py +++ b/backend/app/services/voucher_check/runner.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/runner.py -用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。 -依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。 -逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。 +用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。 +依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。 +逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。 """ from __future__ import annotations @@ -16,13 +16,21 @@ from flask import current_app from app import db from app.core.errors import AppError, NotFoundError, ServiceUnavailableError, ValidationError from app.models import ScheduleRun, ScheduleTask -from app.models.voucher_check import VoucherCheckInvoiceState -from app.services.voucher_check.config import load_voucher_check_config -from app.services.voucher_check.erp_repository import fetch_month_invoices -from app.services.voucher_check.excel_rows import to_excel_detail_row -from app.services.voucher_check.notification import send_failure_alert, send_missing_notifications -from app.services.voucher_check.persistence import persist_batch_results -from app.services.voucher_check.share_scanner import ensure_share_healthy, scan_invoice_folder +from app.services.voucher_check import adapters as _register_adapters # noqa: F401 +from app.services.voucher_check.adapters.registry import get_adapter +from app.services.voucher_check.aggregator import aggregate_file_results +from app.services.voucher_check.config import load_engine_config +from app.services.voucher_check.dms_client import SalesDmsClient +from app.services.voucher_check.engine_persistence import ( + create_run, + load_previous_archived_fingerprints, + persist_engine_results, +) +from app.services.voucher_check.erp_repository import previous_period_bounds +from app.services.voucher_check.excel_rows import to_excel_invoice_row +from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert +from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition +from app.services.voucher_check.profiles.sales import required_file_rules ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] @@ -57,17 +65,16 @@ def _update_progress( if voucher_summary: summary["voucher_check"] = voucher_summary summary["file_judgement"] = { - "qualified_count": int(voucher_summary.get("complete_count") or 0), - "unqualified_count": int(voucher_summary.get("missing_count") or 0), + "qualified_count": int(voucher_summary.get("complete_invoice_count") or 0), + "unqualified_count": int(voucher_summary.get("missing_invoice_count") or 0), "manual_count": 0, "system_error_count": int(voucher_summary.get("technical_error_count") or 0), } summary["progress_metrics"] = [ - {"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("total_count") or 0)}, - {"key": "scan", "label_key": "chat.voucherCheck.scanned", "value": int(voucher_summary.get("scan_count") or 0)}, - {"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_count") or 0)}, - {"key": "complete", "label_key": "chat.voucherCheck.complete", "value": int(voucher_summary.get("complete_count") or 0)}, - {"key": "missing", "label_key": "chat.voucherCheck.missing", "value": int(voucher_summary.get("missing_count") or 0)}, + {"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("subject_count") or 0)}, + {"key": "missing_files", "label_key": "chat.voucherCheck.missingFiles", "value": int(voucher_summary.get("missing_file_count") or 0)}, + {"key": "missing", "label_key": "chat.voucherCheck.missingInvoices", "value": int(voucher_summary.get("missing_invoice_count") or 0)}, + {"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_file_count") or 0)}, ] summary["domain_notification_managed"] = True run.response_summary_json = summary @@ -76,8 +83,9 @@ def _update_progress( def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ - 执行立账凭证检核批次。 - 核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。 + 执行立账凭证周批次。 + 核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。 + 启动日志带 path=accounting-voucher-check,便于在全是 schedule 的 worker 输出中识别本任务。 Returns: ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs) @@ -87,9 +95,19 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe options = _extract_run_options(run) mode = options["mode"] single_invoice = options["invoice_no"] + now = datetime.utcnow() + current_app.logger.info( + "[voucher-check] start name=%s path=accounting-voucher-check run_no=%s mode=%s", + getattr(task, "name", None) or "立账凭证检核", + run.run_no, + mode, + ) try: - config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {}) + config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {}) + profile = load_profile_definition(config.profile_code) + ensure_published_profile(config.profile_code) + SalesDmsClient.ensure_configured() except AppError as exc: send_failure_alert( task=task, @@ -101,10 +119,15 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe ) raise - # [STEP 1] 拉取 ERP 当月发票清单 - _update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证") + rules = required_file_rules(profile) + period_month, _current, _start, _end = previous_period_bounds() + period = period_month.strftime("%Y-%m") + + # [STEP 1] 拉取上月销售 invoice 清单 + _update_progress(run, step="fetch_erp", label="拉取上月销售 invoice") try: - period_month, invoices = fetch_month_invoices(config) + subject_adapter = get_adapter(str(profile.get("subject_adapter") or "hxjm_apa")) + subjects = subject_adapter.fetch(period_month=period_month, config=config) except ServiceUnavailableError as exc: send_failure_alert( task=task, @@ -119,7 +142,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe { "step": "fetch_erp", "status": "success", - "detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")}, + "detail": {"count": len(subjects), "period": period}, } ) @@ -129,169 +152,200 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe "single 模式必须提供 invoice_no", code="VOUCHER_CHECK.INVOICE_REQUIRED", ) - invoices = [row for row in invoices if row.invoice_no == single_invoice] - if not invoices: + subjects = [row for row in subjects if row.invoice_no == single_invoice] + if not subjects: raise NotFoundError( - "指定发票不在当前月 ERP 集合", + "指定发票不在上一个月 ERP 集合", code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD", ) - # [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing) - _update_progress(run, step="share_health", label="检查共享盘可用性") - try: - root = ensure_share_healthy(config) - except ServiceUnavailableError as exc: - send_failure_alert( - task=task, - run=run, - stage="share_health", - error_code=exc.code, - error_message=exc.message, - enabled=config.notify_failure_enabled, - ) - raise - step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}}) - - # [STEP 3] 读取历史状态,供增量判定 - existing_states = ( - db.session.query(VoucherCheckInvoiceState) - .filter_by(scope_code=config.scope_code, period_month=period_month) - .all() + engine_run = create_run( + schedule_run_id=run.id, + run_no=str(run.run_no or f"VC-{run.id}"), + profile_code=str(profile["profile_code"]), + profile_version=str(profile["profile_version"]), + profile_snapshot=profile, + period_month=period_month, + mode=mode, + started_at=now, ) - state_map = {s.invoice_no: s for s in existing_states} + db.session.commit() - results: list[dict[str, Any]] = [] - complete_count = 0 - missing_count = 0 - skipped_count = 0 - technical_error_count = 0 - now = datetime.utcnow() + scan_adapter = get_adapter("directory_scan") + archive_adapter = get_adapter("dms_archive") force = mode in {"force_all", "single"} + previous_fp = {} if force else load_previous_archived_fingerprints( + profile_code=str(profile["profile_code"]), + period_month=period_month, + exclude_run_id=engine_run.id, + ) - # [STEP 4] 逐票扫描 / 指纹比对 + # [STEP 2] 扫描六类类型目录(不调用 PO/OA 打印 Adapter) _update_progress( run, - step="scan_share", - label="扫描共享盘文件名", + step="scan_dms", + label="扫描销售开票附件类型目录", processed=0, voucher_summary={ "scope_code": config.scope_code, - "period": period_month.strftime("%Y-%m"), + "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": 0, - "missing_count": 0, - "scan_count": 0, - "skipped_count": 0, + "subject_count": len(subjects), + "missing_file_count": 0, + "missing_invoice_count": 0, + "skipped_file_count": 0, "technical_error_count": 0, + "complete_invoice_count": 0, }, ) - for idx, row in enumerate(invoices, start=1): - hist = state_map.get(row.invoice_no) - scan = scan_invoice_folder( - config, - root=root, - period_month=period_month, - invoice_no=row.invoice_no, - ) - - # 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹) - can_skip = ( - not force - and hist is not None - and hist.status == "complete" - and hist.material_fingerprint - and scan.result == "complete" - and scan.material_fingerprint == hist.material_fingerprint - ) - if can_skip: - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": "skipped", - "folder_path": scan.folder_path, - "folder_exists": scan.folder_exists, - "material_fingerprint": scan.material_fingerprint, - "matched_files": scan.matched_files, - "missing_materials": [], - "checked_at": None, - } - skipped_count += 1 - elif scan.result == "technical_error": - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": "technical_error", - "folder_path": scan.folder_path, - "folder_exists": False, - "material_fingerprint": None, - "matched_files": {}, - "missing_materials": [], - "error_code": scan.error_code, - "error_message": scan.error_message, + file_results: list[dict[str, Any]] = [] + yyyy = f"{period_month.year:04d}" + mm = f"{period_month.month:02d}" + for idx, subject in enumerate(subjects, start=1): + for rule in rules: + rule_code = str(rule["code"]) + expected = str(rule.get("filename_template") or "").replace("{invoice}", subject.invoice_no) + prev_key = (subject.invoice_no, rule_code) + outcome = scan_adapter.scan( + period_month=period_month, + invoice_no=subject.invoice_no, + rule=rule, + ) + result: dict[str, Any] = { + "invoice_no": subject.invoice_no, + "invoice_date": subject.invoice_date, + "rule_code": rule_code, + "rule_name": rule.get("name") or rule_code, + "source_type": "directory_scan", + "expected_name": expected, + "source_folder_id": outcome.folder_id, + "source_path": outcome.folder_path, "checked_at": now, } - technical_error_count += 1 - else: - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": scan.result, - "folder_path": scan.folder_path, - "folder_exists": scan.folder_exists, - "material_fingerprint": scan.material_fingerprint, - "matched_files": scan.matched_files, - "missing_materials": scan.missing_materials, - "checked_at": now, - } - if scan.result == "complete": - complete_count += 1 + if ( + not force + and outcome.status == "matched" + and outcome.file + and outcome.file.fingerprint + and previous_fp.get(prev_key) == outcome.file.fingerprint + ): + result.update( + { + "status": "skipped", + "matched_name": outcome.file.filename, + "source_item_id": outcome.file.item_id, + "source_fingerprint": outcome.file.fingerprint, + } + ) + elif outcome.status == "technical_error": + result.update( + { + "status": "technical_error", + "error_code": outcome.error_code, + "error_message": outcome.error_message, + } + ) + elif outcome.status != "matched" or outcome.file is None: + result.update( + { + "status": "missing", + "missing_reason": "类型目录未找到匹配文件", + } + ) else: - missing_count += 1 - results.append(item) + scanned = outcome.file + result.update( + { + "matched_name": scanned.filename, + "source_item_id": scanned.item_id, + "source_fingerprint": scanned.fingerprint, + } + ) + archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{subject.invoice_no}/{scanned.filename}" + result["archive_path"] = archive_path + if getattr(archive_adapter, "wired", False): + try: + archived = archive_adapter.archive( + period_month=period_month, + invoice_no=subject.invoice_no, + file=scanned, + rule=rule, + ) + extra = archived.extra or {} + result.update( + { + "status": "archived", + "archive_item_id": archived.item_id, + "archive_folder_id": archived.folder_id, + "archive_skipped_same_name": bool(extra.get("skipped_same_name")), + } + ) + except ServiceUnavailableError as exc: + result.update( + { + "status": "technical_error", + "error_code": exc.code, + "error_message": exc.message, + } + ) + else: + result["status"] = "staged" + file_results.append(result) - if idx % 20 == 0 or idx == len(invoices): - scan_count = complete_count + missing_count + technical_error_count + if idx % 20 == 0 or idx == len(subjects): + preview = aggregate_file_results(file_results, rules=rules) _update_progress( run, - step="scan_share", - label="扫描共享盘文件名", + step="scan_dms", + label="扫描销售开票附件类型目录", processed=idx, voucher_summary={ "scope_code": config.scope_code, - "period": period_month.strftime("%Y-%m"), + "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": complete_count, - "missing_count": missing_count, - "scan_count": scan_count, - "skipped_count": skipped_count, - "technical_error_count": technical_error_count, + "subject_count": len(subjects), + "missing_file_count": preview["missing_file_count"], + "missing_invoice_count": preview["missing_invoice_count"], + "skipped_file_count": preview["skipped_file_count"], + "technical_error_count": preview["technical_error_count"], + "complete_invoice_count": sum( + 1 for row in preview["excel_rows"] if row["status"] == "完整" + ), }, ) + stats = aggregate_file_results(file_results, rules=rules) step_logs.append( { - "step": "scan_share", + "step": "scan_dms", "status": "success", "detail": { - "complete": complete_count, - "missing": missing_count, - "skipped": skipped_count, - "technical_error": technical_error_count, + "missing_files": stats["missing_file_count"], + "missing_invoices": stats["missing_invoice_count"], + "staged": stats["staged_file_count"], + "skipped": stats["skipped_file_count"], + "technical_error": stats["technical_error_count"], }, } ) - # [STEP 5] 事务落库 + # [STEP 3] 落库单文件结果 _update_progress(run, step="persist", label="写入检核记录") try: - persist_batch_results( - schedule_run_id=run.id, - scope_code=config.scope_code, - period_month=period_month, - items=results, + persist_engine_results( + run=engine_run, + subjects=[ + { + "invoice_no": row.invoice_no, + "invoice_date": row.invoice_date, + "source_fingerprint": row.source_fingerprint, + "attributes": row.attributes, + } + for row in subjects + ], + file_results=file_results, + stats=stats, now=now, ) db.session.commit() @@ -308,58 +362,62 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe ) raise - # [STEP 6] 缺资料通知 - missing_items = [r for r in results if r["result"] == "missing"] - notified = send_missing_notifications( + excel_filename = f"voucher_check_{profile['profile_code']}_{period}_{run.run_no}.xlsx" + executed_at = now.strftime("%Y-%m-%d %H:%M:%S") + details = [ + to_excel_invoice_row(item, period=period, executed_at=executed_at) + for item in stats["excel_rows"] + ] + + # [STEP 4] 每批一条企微汇总 + notify_status = send_batch_missing_summary( task=task, - run=run, - scope_code=config.scope_code, - period_month=period_month, - missing_items=missing_items, - same_day_dedup=config.same_day_dedup_enabled, + schedule_run=run, + engine_run_id=engine_run.id, + profile_code=str(profile["profile_code"]), + period_month=period, + stats=stats, + excel_filename=excel_filename, enabled=config.notify_missing_enabled, ) step_logs.append( { "step": "notify", "status": "success", - "detail": {"missing": len(missing_items), "notified": notified}, + "detail": {"send_status": notify_status, "missing_files": stats["missing_file_count"]}, } ) - period = period_month.strftime("%Y-%m") - scan_count = complete_count + missing_count + technical_error_count + complete_invoices = sum(1 for row in stats["excel_rows"] if row["status"] == "完整") voucher_summary = { "scope_code": config.scope_code, "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": complete_count, - "missing_count": missing_count, - "scan_count": scan_count, - "skipped_count": skipped_count, - "technical_error_count": technical_error_count, - "missing_notification_count": notified, + "engine_run_id": engine_run.id, + "subject_count": stats["subject_count"], + "missing_file_count": stats["missing_file_count"], + "missing_invoice_count": stats["missing_invoice_count"], + "skipped_file_count": stats["skipped_file_count"], + "technical_error_count": stats["technical_error_count"], + "staged_file_count": stats["staged_file_count"], + "complete_invoice_count": complete_invoices, + "notify_status": notify_status, } _update_progress( run, step="done", label="检核完成", - processed=len(invoices), + processed=len(subjects), voucher_summary=voucher_summary, ) - details = [ - to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results - ] - # success_count = complete + missing(业务成功);failed_count 仅技术异常 - success_count = complete_count + missing_count - total_count = len(invoices) + success_count = stats["subject_count"] + failed_count = 1 if stats["batch_status"] == "technical_failed" and stats["missing_file_count"] == 0 else 0 return ( - total_count, + stats["subject_count"], success_count, - technical_error_count, - skipped_count, + failed_count, + stats["skipped_file_count"], details, errors, step_logs, diff --git a/backend/app/services/voucher_check/schedule_seed.py b/backend/app/services/voucher_check/schedule_seed.py index 936c3d75..500b4a52 100644 --- a/backend/app/services/voucher_check/schedule_seed.py +++ b/backend/app/services/voucher_check/schedule_seed.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/schedule_seed.py -用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。 +用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。 依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。 -逻辑:迁移种子 + create_app / User after_commit 幂等补建。 +逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。 """ from __future__ import annotations @@ -14,6 +14,7 @@ from typing import Any from sqlalchemy import event from sqlalchemy.orm import Session +from sqlalchemy.orm.attributes import flag_modified from app import db from app.models import ScheduleTask, User @@ -24,20 +25,40 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_VOUCHER_CHECK_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK" DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check" -DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * *" -DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(日批)" +DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * 2" +DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(周批)" _HOOKS_REGISTERED = False _SESSION_INFO_KEY = "_seed_voucher_check_schedule" +def _normalize_existing_job_params(raw: Any) -> tuple[dict[str, Any], bool]: + """ + 把已有排程的 job_params 收成当前 schema。 + 核心逻辑:保留 DEFAULT_JOB_PARAMS 与 _advanced;丢掉共享盘时代的未知字段。 + """ + from app.services.schedule.job_params import ADVANCED_PARAMS_KEY + + current = dict(raw) if isinstance(raw, dict) else {} + cleaned: dict[str, Any] = {} + for key, default in DEFAULT_JOB_PARAMS.items(): + value = current.get(key) + cleaned[key] = default if value is None else value + advanced = current.get(ADVANCED_PARAMS_KEY) + if isinstance(advanced, dict): + cleaned[ADVANCED_PARAMS_KEY] = advanced + return cleaned, current != cleaned + + def ensure_default_voucher_check_schedule( *, commit: bool = True, session: Any | None = None, ) -> ScheduleTask | None: """ - 幂等确保默认立账凭证检核日批排程存在。 + 幂等确保默认立账凭证检核周批排程存在。 + 核心逻辑:已存在任务会把日批 cron 改成周二,并剥离 schema 外的旧 job_params, + 避免 worker 执行前校验 unknown params 整批失败。 Args: commit: 是否立即提交。 @@ -56,6 +77,29 @@ def ensure_default_voucher_check_schedule( .first() ) if existing is not None: + changed = False + if existing.cron_expr == "0 6 * * *": + existing.cron_expr = DEFAULT_VOUCHER_CHECK_CRON + if existing.name == "立账凭证检核(日批)": + existing.name = DEFAULT_VOUCHER_CHECK_NAME + existing.next_run_at = compute_next_run_at( + DEFAULT_VOUCHER_CHECK_CRON, + timezone_name="Asia/Shanghai", + ) or existing.next_run_at + changed = True + cleaned_params, params_changed = _normalize_existing_job_params(existing.job_params) + if params_changed: + existing.job_params = cleaned_params + flag_modified(existing, "job_params") + changed = True + _LOGGER.info( + "stripped legacy accounting-voucher-check job_params id=%s", + existing.id, + ) + if changed: + existing.updated_at = datetime.utcnow() + if commit: + sess.commit() return existing owner = ( diff --git a/backend/app/services/voucher_check/share_scanner.py b/backend/app/services/voucher_check/share_scanner.py deleted file mode 100644 index 020e1d13..00000000 --- a/backend/app/services/voucher_check/share_scanner.py +++ /dev/null @@ -1,273 +0,0 @@ -""" -backend/app/services/voucher_check/share_scanner.py - -用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。 -依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。 -逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。 -""" - -from __future__ import annotations - -import os -from dataclasses import dataclass, field -from datetime import date -from pathlib import Path - -from app.core.errors import ServiceUnavailableError, ValidationError -from app.services.voucher_check.config import ( - RequiredFileRule, - VoucherCheckConfig, - resolve_share_root, -) -from app.services.voucher_check.fingerprint import build_material_fingerprint - - -@dataclass -class FileMeta: - """直接子文件元数据。""" - - name: str - size: int - mtime_ns: int - - -@dataclass -class InvoiceScanResult: - """单票扫描结果。""" - - invoice_no: str - folder_path: str - absolute_path: str - folder_exists: bool - material_fingerprint: str | None - matched_files: dict[str, str] = field(default_factory=dict) - missing_materials: list[dict[str, str]] = field(default_factory=list) - result: str = "missing" # complete / missing / technical_error - error_code: str | None = None - error_message: str | None = None - - -def ensure_share_healthy(config: VoucherCheckConfig) -> str: - """ - 校验共享盘根目录可用。 - 核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。 - - Returns: - 解析后的绝对根路径。 - """ - root = resolve_share_root(config) - root_path = Path(root) - try: - if not root_path.exists() or not root_path.is_dir(): - raise ServiceUnavailableError( - "共享盘根目录不可用", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - # [STEP 1] 轻量枚举证明 I/O 可用 - with os.scandir(root_path) as it: - _ = next(it, None) - root_path.stat() - # [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件 - marker = (root_path / config.healthcheck_relative_path).resolve() - if not str(marker).startswith(str(root_path.resolve())): - raise ServiceUnavailableError( - "共享盘健康标记路径非法", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - if not marker.is_file(): - raise ServiceUnavailableError( - "共享盘健康标记文件缺失", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - except ServiceUnavailableError: - raise - except OSError as exc: - raise ServiceUnavailableError( - "共享盘健康检查失败", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - details={"error_type": type(exc).__name__}, - ) from exc - return str(root_path) - - -def _render_invoice_relative_path( - template: str, - *, - year: str, - month: str, - invoice_no: str, -) -> str: - """渲染相对业务路径(不含 root 实际值,报告用)。""" - rendered = ( - template.replace("{root}", "vouche") - .replace("{YYYY}", year) - .replace("{MM}", month) - .replace("{invoice_no}", invoice_no) - ) - return rendered.strip("/").replace("\\", "/") - - -def build_invoice_absolute_path( - config: VoucherCheckConfig, - *, - root: str, - period_month: date, - invoice_no: str, -) -> tuple[str, str]: - """ - 构造单票绝对路径与相对业务路径。 - 核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。 - """ - year = f"{period_month.year:04d}" - month = f"{period_month.month:02d}" - invoice = str(invoice_no or "").strip() - if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice: - raise ValidationError( - "发票号含非法路径字符", - code="VOUCHER_CHECK.INVOICE_PATH_INVALID", - details={"invoice_no": invoice_no}, - ) - - relative = _render_invoice_relative_path( - config.directory_template, - year=year, - month=month, - invoice_no=invoice, - ) - # 实际落盘:用真实 root 替换模板中的 {root} - absolute_template = ( - config.directory_template.replace("{root}", root.rstrip("/\\")) - .replace("{YYYY}", year) - .replace("{MM}", month) - .replace("{invoice_no}", invoice) - ) - absolute = str(Path(absolute_template)) - resolved_root = Path(root).resolve() - resolved_abs = Path(absolute).resolve() - try: - resolved_abs.relative_to(resolved_root) - except ValueError as exc: - raise ValidationError( - "发票目录逃逸共享根", - code="VOUCHER_CHECK.INVOICE_PATH_INVALID", - details={"invoice_no": invoice}, - ) from exc - return absolute, relative - - -def list_direct_files(folder: Path) -> list[FileMeta]: - """枚举发票目录直接子文件(忽略子目录与非普通文件)。""" - files: list[FileMeta] = [] - if not folder.is_dir(): - return files - with os.scandir(folder) as it: - for entry in it: - try: - if not entry.is_file(follow_symlinks=False): - continue - stat = entry.stat(follow_symlinks=False) - files.append( - FileMeta( - name=entry.name, - size=int(stat.st_size), - mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))), - ) - ) - except OSError: - continue - return files - - -def match_required_files( - files: list[FileMeta], - rules: tuple[RequiredFileRule, ...], - *, - case_sensitive: bool, -) -> tuple[dict[str, str], list[dict[str, str]]]: - """ - 按完整文件名精确匹配必检材料。 - 核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。 - """ - if case_sensitive: - available = {f.name: f.name for f in files} - else: - available = {f.name.lower(): f.name for f in files} - - matched: dict[str, str] = {} - missing: list[dict[str, str]] = [] - for rule in rules: - if not rule.required: - continue - hit: str | None = None - for candidate in rule.accepted_filenames: - key = candidate if case_sensitive else candidate.lower() - if key in available: - hit = available[key] - break - if hit: - matched[rule.code] = hit - else: - missing.append({"code": rule.code, "name": rule.name}) - return matched, missing - - -def scan_invoice_folder( - config: VoucherCheckConfig, - *, - root: str, - period_month: date, - invoice_no: str, -) -> InvoiceScanResult: - """ - 扫描单票目录并判定齐全/缺资料。 - 核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。 - """ - try: - absolute, relative = build_invoice_absolute_path( - config, - root=root, - period_month=period_month, - invoice_no=invoice_no, - ) - except ValidationError as exc: - return InvoiceScanResult( - invoice_no=str(invoice_no or "").strip(), - folder_path="", - absolute_path="", - folder_exists=False, - material_fingerprint=None, - result="technical_error", - error_code=exc.code, - error_message=exc.message, - ) - - folder = Path(absolute) - if not folder.exists() or not folder.is_dir(): - missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required] - return InvoiceScanResult( - invoice_no=str(invoice_no).strip(), - folder_path=relative, - absolute_path=absolute, - folder_exists=False, - material_fingerprint=None, - missing_materials=missing, - result="missing", - ) - - files = list_direct_files(folder) - fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files]) - matched, missing = match_required_files( - files, - config.required_files, - case_sensitive=config.filename_case_sensitive, - ) - return InvoiceScanResult( - invoice_no=str(invoice_no).strip(), - folder_path=relative, - absolute_path=absolute, - folder_exists=True, - material_fingerprint=fingerprint, - matched_files=matched, - missing_materials=missing, - result="complete" if not missing else "missing", - ) diff --git a/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py b/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py new file mode 100644 index 00000000..e0b15aa8 --- /dev/null +++ b/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py @@ -0,0 +1,157 @@ +"""add integration connector tables + +Revision ID: ic1a2b3c4d5f +Revises: it1a2b3c4d5e +Create Date: 2026-08-27 21:00:00.000000 + +用途:Integration Connector(外部系统连接器框架)P1 配置与运行模型建表: + CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。 +依赖:integration_* 全部新表;不依赖既有 shipping/transfer 表。 +逻辑:配置层实体维护版本与状态;IntegrationCall 记录一次技术调用(冻结绑定版本 + 脱敏摘要)。 + 连接器类型(rest/soap)与状态用 CheckConstraint 兜底;fail-closed 语义在服务层。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'ic1a2b3c4d5f' +down_revision = 'it1a2b3c4d5e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 5 张连接器框架表(先建凭据/客户端,再建接口/绑定,最后调用记录)。""" + op.create_table( + 'integration_credential_references', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('secret_ref', sa.String(length=128), nullable=False), + sa.Column('secret_provider', sa.String(length=32), nullable=False, server_default='env'), + sa.Column('credential_type', sa.String(length=32), nullable=False, server_default='password'), + sa.Column('version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=16), nullable=False, server_default='active'), + sa.Column('last_verified_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_credential_references_code'), + sa.CheckConstraint( + "status IN ('active', 'rotating', 'retired')", + name='ck_integration_credential_references_status', + ), + ) + + op.create_table( + 'integration_client_instances', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('connector_type', sa.String(length=16), nullable=False), + sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'), + sa.Column('config_json', sa.JSON(), nullable=False), + sa.Column('credential_ref_code', sa.String(length=64), sa.ForeignKey('integration_credential_references.code'), nullable=True), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_client_instances_code'), + sa.CheckConstraint( + "connector_type IN ('rest', 'soap')", + name='ck_integration_client_instances_connector_type', + ), + ) + op.create_index( + 'ix_integration_client_instances_type_env', + 'integration_client_instances', ['connector_type', 'environment'], + ) + + op.create_table( + 'integration_interface_definitions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False), + sa.Column('connector_type', sa.String(length=16), nullable=False), + sa.Column('request_spec_json', sa.JSON(), nullable=False), + sa.Column('input_schema_json', sa.JSON(), nullable=False), + sa.Column('response_mapping_json', sa.JSON(), nullable=False), + sa.Column('output_schema_json', sa.JSON(), nullable=False), + sa.Column('version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_interface_definitions_code'), + sa.CheckConstraint( + "connector_type IN ('rest', 'soap')", + name='ck_integration_interface_definitions_connector_type', + ), + sa.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_integration_interface_definitions_status', + ), + ) + op.create_index( + 'ix_integration_interface_definitions_client', + 'integration_interface_definitions', ['client_instance_code'], + ) + + op.create_table( + 'integration_bindings', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('capability', sa.String(length=128), nullable=False), + sa.Column('context_selector_json', sa.JSON().with_variant(sa.dialects.postgresql.JSONB(), 'postgresql'), nullable=False), + sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False), + sa.Column('interface_definition_code', sa.String(length=64), sa.ForeignKey('integration_interface_definitions.code'), nullable=False), + sa.Column('mapping_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('priority', sa.Integer(), nullable=False, server_default='0'), + sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'), + sa.Column('effective_from', sa.DateTime(), nullable=True), + sa.Column('effective_to', sa.DateTime(), nullable=True), + sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint( + 'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx', + ), + sa.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_integration_bindings_status', + ), + sa.CheckConstraint('priority >= 0', name='ck_integration_bindings_priority'), + ) + op.create_index( + 'ix_integration_bindings_cap_env_status', + 'integration_bindings', ['capability', 'environment', 'status'], + ) + + op.create_table( + 'integration_calls', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('operation_id', sa.String(length=128), nullable=False), + sa.Column('capability', sa.String(length=128), nullable=False), + sa.Column('binding_snapshot_json', sa.JSON(), nullable=False), + sa.Column('request_summary_json', sa.JSON(), nullable=False), + sa.Column('response_summary_json', sa.JSON(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('elapsed_ms', sa.Integer(), nullable=False, server_default='0'), + sa.Column('trace_id', sa.String(length=64), nullable=False, server_default=''), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'), + ) + op.create_index('ix_integration_calls_capability_created', 'integration_calls', ['capability', 'created_at']) + op.create_index('ix_integration_calls_trace_id', 'integration_calls', ['trace_id']) + + +def downgrade() -> None: + """回滚:按外键依赖逆序删除连接器表。""" + op.drop_index('ix_integration_calls_trace_id', table_name='integration_calls') + op.drop_index('ix_integration_calls_capability_created', table_name='integration_calls') + op.drop_table('integration_calls') + op.drop_index('ix_integration_bindings_cap_env_status', table_name='integration_bindings') + op.drop_table('integration_bindings') + op.drop_index('ix_integration_interface_definitions_client', table_name='integration_interface_definitions') + op.drop_table('integration_interface_definitions') + op.drop_index('ix_integration_client_instances_type_env', table_name='integration_client_instances') + op.drop_table('integration_client_instances') + op.drop_table('integration_credential_references') diff --git a/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py b/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py new file mode 100644 index 00000000..1eb84658 --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py @@ -0,0 +1,45 @@ +"""add purpose to inventory parsing profiles + +Revision ID: if1b2c3d4e5g +Revises: ic1a2b3c4d5f +Create Date: 2026-08-28 10:30:00.000000 + +用途:把库存解析规则泛化为通用文件解析规则——为 shipping_inventory_parsing_profiles + 增 purpose 列(inventory / movement)。inventory 沿用库存字段目录;movement + 端点用定死领域字段(MOVEMENT_FIELDS),供收料/异动文件映射。既有行默认 inventory, + 不改变既有库存语义。 +依赖:shipping_inventory_parsing_profiles 表。 +逻辑:仅加列 + CheckConstraint,无数据回填(默认 inventory)。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'if1b2c3d4e5g' +down_revision = 'ic1a2b3c4d5f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 purpose 列并加 CheckConstraint(inventory / movement)。""" + op.add_column( + 'shipping_inventory_parsing_profiles', + sa.Column('purpose', sa.String(length=16), nullable=False, server_default='inventory'), + ) + op.create_check_constraint( + 'ck_shipping_inventory_parsing_profiles_purpose', + 'shipping_inventory_parsing_profiles', + "purpose IN ('inventory', 'movement')", + ) + + +def downgrade() -> None: + """移除 purpose 约束与列。""" + op.drop_constraint( + 'ck_shipping_inventory_parsing_profiles_purpose', + 'shipping_inventory_parsing_profiles', + type_='check', + ) + op.drop_column('shipping_inventory_parsing_profiles', 'purpose') diff --git a/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py b/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py new file mode 100644 index 00000000..d8f09309 --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py @@ -0,0 +1,53 @@ +"""add parsing_profile_id to shipping_receipt_report_configs + +Revision ID: if1b2c3d4e5h +Revises: if1b2c3d4e5g +Create Date: 2026-08-28 10:45:00.000000 + +用途:收料报表配置绑定其收料文件解析规则(purpose='movement')。空则无法解析收料文件。 +依赖:shipping_receipt_report_configs 表 + shipping_inventory_parsing_profiles 表。 +逻辑:仅新增可空外键列,无数据回填。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'if1b2c3d4e5h' +down_revision = 'if1b2c3d4e5g' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 parsing_profile_id 外键列。""" + op.add_column( + 'shipping_receipt_report_configs', + sa.Column('parsing_profile_id', sa.Integer(), nullable=True), + ) + op.create_index( + 'ix_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + ['parsing_profile_id'], + ) + op.create_foreign_key( + 'fk_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + 'shipping_inventory_parsing_profiles', + ['parsing_profile_id'], + ['id'], + ) + + +def downgrade() -> None: + """移除外键、索引与列。""" + op.drop_constraint( + 'fk_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + type_='foreignkey', + ) + op.drop_index( + 'ix_shipping_receipt_report_configs_parsing_profile', + table_name='shipping_receipt_report_configs', + ) + op.drop_column('shipping_receipt_report_configs', 'parsing_profile_id') diff --git a/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py b/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py new file mode 100644 index 00000000..37bcb33f --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py @@ -0,0 +1,42 @@ +"""add file_ready to transfer_source_jobs status constraint + +Revision ID: if1b2c3d4e5i +Revises: if1b2c3d4e5h +Create Date: 2026-08-28 11:15:00.000000 + +用途:让 TransferSourceJob.status 状态集与来源准备流程阶段(file_ready)对齐。 + 原 CHECK 缺少 file_ready,导致来源文件就绪时 job 无法用 file_ready 表达 + (create_precheck 只能硬映射为 pending)。 +依赖:transfer_source_jobs 表。 +逻辑:drop 旧 CHECK → 重新 create(追加 file_ready),无数据回填。 +""" + +from alembic import op + + +revision = 'if1b2c3d4e5i' +down_revision = 'if1b2c3d4e5h' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """更新 status 检查约束,允许 file_ready。""" + op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check') + op.create_check_constraint( + 'ck_transfer_source_jobs_status', + 'transfer_source_jobs', + "status IN ('pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', " + "'parsing', 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + ) + + +def downgrade() -> None: + """恢复原检查约束(不含 file_ready)。""" + op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check') + op.create_check_constraint( + 'ck_transfer_source_jobs_status', + 'transfer_source_jobs', + "status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', " + "'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + ) diff --git a/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py b/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py new file mode 100644 index 00000000..52ab6f28 --- /dev/null +++ b/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py @@ -0,0 +1,275 @@ +"""add in-transit transfer domain tables + +Revision ID: it1a2b3c4d5e +Revises: hw6x7y8z9a0b +Create Date: 2026-08-27 14:00:00.000000 + +用途:在途仓自动调拨 Agent 一期领域模型建表:Run、SourceJob、Precheck、 + InvoiceItem、Attempt、AuditEvent 与 Archive。 +依赖:transfer_* 全部新表;不依赖既有 shipping 表(来源配置在服务层只读复用)。 +逻辑:Run 为业务真相源;InvoiceItem 按 (precheck_id, invoice_no) 唯一; + AuditEvent 只追加;Archive 记录 MinIO 对象路径与 Hash。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'it1a2b3c4d5e' +down_revision = 'hw6x7y8z9a0b' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 7 张调拨领域表。""" + op.create_table( + 'transfer_runs', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_no', sa.String(length=64), nullable=False), + sa.Column('trigger_type', sa.String(length=16), nullable=False, server_default='manual'), + sa.Column('business_date', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('source_codes_json', sa.JSON(), nullable=False), + sa.Column('counts_json', sa.JSON(), nullable=False), + sa.Column('result_summary_json', sa.JSON(), nullable=False), + sa.Column('notification_status', sa.String(length=16), nullable=False, server_default='pending'), + sa.Column('notification_error_code', sa.String(length=64), nullable=True), + sa.Column('notification_error_message', sa.Text(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('run_no', name='uq_transfer_runs_run_no'), + sa.CheckConstraint( + "status IN ('queued', 'preparing_files', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + name='ck_transfer_runs_status', + ), + sa.CheckConstraint( + "notification_status IN ('pending', 'success', 'failed')", + name='ck_transfer_runs_notification_status', + ), + sa.CheckConstraint( + "trigger_type IN ('manual', 'schedule')", + name='ck_transfer_runs_trigger_type', + ), + ) + op.create_index('ix_transfer_runs_status_created', 'transfer_runs', ['status', 'created_at']) + op.create_index('ix_transfer_runs_business_date', 'transfer_runs', ['business_date']) + + op.create_table( + 'transfer_source_jobs', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=False), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('source_config_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'), + sa.Column('file_no', sa.String(length=64), nullable=True), + sa.Column('file_sha256', sa.String(length=64), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('lease_until', sa.DateTime(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'), + sa.CheckConstraint( + "status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', " + "'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + name='ck_transfer_source_jobs_status', + ), + ) + op.create_index('ix_transfer_source_jobs_source_status', 'transfer_source_jobs', ['source_code', 'status']) + + op.create_table( + 'transfer_prechecks', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('precheck_no', sa.String(length=64), nullable=False), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True), + sa.Column('business_date', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='prechecking'), + sa.Column('scope_json', sa.JSON(), nullable=False), + sa.Column('file_snapshot_json', sa.JSON(), nullable=False), + sa.Column('mapping_version', sa.String(length=64), nullable=True), + sa.Column('strategy_version', sa.String(length=64), nullable=True), + sa.Column('counts_json', sa.JSON(), nullable=False), + sa.Column('estimated_transfer_quantity', sa.String(length=40), nullable=True), + sa.Column('estimated_erp_write_count', sa.Integer(), nullable=False, server_default='0'), + sa.Column('precheck_hash', sa.String(length=128), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.Column('confirmed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'), + sa.CheckConstraint( + "status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'failed', 'cancelled', 'expired')", + name='ck_transfer_prechecks_status', + ), + ) + op.create_index('ix_transfer_prechecks_run_status', 'transfer_prechecks', ['run_id', 'status']) + op.create_index('ix_transfer_prechecks_business_date', 'transfer_prechecks', ['business_date']) + + op.create_table( + 'transfer_invoice_items', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('precheck_id', sa.Integer(), sa.ForeignKey('transfer_prechecks.id'), nullable=False), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('invoice_no', sa.String(length=64), nullable=False), + sa.Column('material_no', sa.String(length=64), nullable=False), + sa.Column('material_name', sa.String(length=200), nullable=False, server_default=''), + sa.Column('specification', sa.String(length=200), nullable=False, server_default=''), + sa.Column('receipt_date', sa.String(length=16), nullable=True), + sa.Column('from_warehouse', sa.String(length=64), nullable=False), + sa.Column('to_warehouse', sa.String(length=64), nullable=False), + sa.Column('receipt_quantity', sa.String(length=40), nullable=False), + sa.Column('erp_quantity', sa.String(length=40), nullable=True), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('result_code', sa.String(length=64), nullable=True), + sa.Column('result_message', sa.Text(), nullable=True), + sa.Column('erp_document_no', sa.String(length=64), nullable=True), + sa.Column('raw_lines_json', sa.JSON(), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False, server_default='0'), + sa.Column('manually_closed_reason', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'), + sa.CheckConstraint( + "status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', " + "'result_unknown', 'manually_closed', 'cancelled', 'notification_failed')", + name='ck_transfer_invoice_items_status', + ), + ) + op.create_index( + 'ix_transfer_invoice_items_source_invoice_status', + 'transfer_invoice_items', ['source_code', 'invoice_no', 'status'], + ) + op.create_index('ix_transfer_invoice_items_run_id', 'transfer_invoice_items', ['run_id']) + op.create_index('ix_transfer_invoice_items_erp_document_no', 'transfer_invoice_items', ['erp_document_no']) + + op.create_table( + 'transfer_attempts', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('item_id', sa.Integer(), sa.ForeignKey('transfer_invoice_items.id'), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('kind', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('request_snapshot_json', sa.JSON(), nullable=False), + sa.Column('response_summary_json', sa.JSON(), nullable=False), + sa.Column('operation_id', sa.String(length=128), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'), + sa.CheckConstraint( + "kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')", + name='ck_transfer_attempts_kind', + ), + sa.CheckConstraint( + "status IN ('queued', 'running', 'waiting_external', 'success', 'failed', " + "'result_unknown', 'superseded')", + name='ck_transfer_attempts_status', + ), + ) + op.create_index('ix_transfer_attempts_item_created', 'transfer_attempts', ['item_id', 'created_at']) + + op.create_table( + 'transfer_audit_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('event_type', sa.String(length=64), nullable=False), + sa.Column('aggregate_type', sa.String(length=64), nullable=False), + sa.Column('aggregate_id', sa.String(length=128), nullable=False), + sa.Column('run_no', sa.String(length=64), nullable=True), + sa.Column('precheck_no', sa.String(length=64), nullable=True), + sa.Column('invoice_no', sa.String(length=64), nullable=True), + sa.Column('item_id', sa.String(length=64), nullable=True), + sa.Column('attempt_no', sa.Integer(), nullable=True), + sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'), + sa.Column('actor_id', sa.String(length=128), nullable=True), + sa.Column('actor_role', sa.String(length=64), nullable=True), + sa.Column('actor_display', sa.String(length=128), nullable=True), + sa.Column('request_id', sa.String(length=64), nullable=True), + sa.Column('operation_id', sa.String(length=64), nullable=True), + sa.Column('source', sa.String(length=32), nullable=True), + sa.Column('result', sa.String(length=16), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('before_json', sa.JSON(), nullable=False), + sa.Column('after_json', sa.JSON(), nullable=False), + sa.Column('diff_json', sa.JSON(), nullable=False), + sa.Column('before_hash', sa.String(length=64), nullable=True), + sa.Column('after_hash', sa.String(length=64), nullable=True), + sa.Column('event_hash', sa.String(length=64), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "actor_type IN ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')", + name='ck_transfer_audit_events_actor_type', + ), + sa.CheckConstraint( + "result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')", + name='ck_transfer_audit_events_result', + ), + ) + op.create_index( + 'ix_transfer_audit_events_aggregate_created', + 'transfer_audit_events', ['aggregate_type', 'aggregate_id', 'created_at'], + ) + op.create_index('ix_transfer_audit_events_run_created', 'transfer_audit_events', ['run_no', 'created_at']) + op.create_index('ix_transfer_audit_events_invoice_created', 'transfer_audit_events', ['invoice_no', 'created_at']) + op.create_index('ix_transfer_audit_events_operation_created', 'transfer_audit_events', ['operation_id', 'created_at']) + op.create_index('ix_transfer_audit_events_event_hash', 'transfer_audit_events', ['event_hash']) + + op.create_table( + 'transfer_archives', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('archive_no', sa.String(length=64), nullable=False), + sa.Column('object_type', sa.String(length=64), nullable=False), + sa.Column('object_id', sa.String(length=128), nullable=False), + sa.Column('storage_provider', sa.String(length=32), nullable=False), + sa.Column('storage_bucket', sa.String(length=128), nullable=False), + sa.Column('storage_key', sa.String(length=1024), nullable=False), + sa.Column('original_filename', sa.String(length=255), nullable=False), + sa.Column('content_type', sa.String(length=128), nullable=True), + sa.Column('file_size', sa.Integer(), nullable=False), + sa.Column('sha256', sa.String(length=64), nullable=False), + sa.Column('archive_expires_at', sa.DateTime(), nullable=True), + sa.Column('archive_deleted_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'), + sa.UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'), + sa.CheckConstraint('file_size >= 0', name='ck_transfer_archives_file_size'), + ) + op.create_index('ix_transfer_archives_object', 'transfer_archives', ['object_type', 'object_id']) + + +def downgrade() -> None: + """回滚:按外键依赖逆序删除调拨表。""" + op.drop_index('ix_transfer_archives_object', table_name='transfer_archives') + op.drop_table('transfer_archives') + op.drop_index('ix_transfer_audit_events_event_hash', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_operation_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_invoice_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_run_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_aggregate_created', table_name='transfer_audit_events') + op.drop_table('transfer_audit_events') + op.drop_index('ix_transfer_attempts_item_created', table_name='transfer_attempts') + op.drop_table('transfer_attempts') + op.drop_index('ix_transfer_invoice_items_erp_document_no', table_name='transfer_invoice_items') + op.drop_index('ix_transfer_invoice_items_run_id', table_name='transfer_invoice_items') + op.drop_index('ix_transfer_invoice_items_source_invoice_status', table_name='transfer_invoice_items') + op.drop_table('transfer_invoice_items') + op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_prechecks') + op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_prechecks') + op.drop_table('transfer_prechecks') + op.drop_index('ix_transfer_source_jobs_source_status', table_name='transfer_source_jobs') + op.drop_table('transfer_source_jobs') + op.drop_index('ix_transfer_runs_business_date', table_name='transfer_runs') + op.drop_index('ix_transfer_runs_status_created', table_name='transfer_runs') + op.drop_table('transfer_runs') diff --git a/backend/migrations/versions/iw1a2b3c4d5e_retire_line_key_contract.py b/backend/migrations/versions/iw1a2b3c4d5e_retire_line_key_contract.py new file mode 100644 index 00000000..9714d539 --- /dev/null +++ b/backend/migrations/versions/iw1a2b3c4d5e_retire_line_key_contract.py @@ -0,0 +1,385 @@ +"""订单明细身份、项次及 OT 生命周期契约的一次性硬切换。""" +from __future__ import annotations +import copy +from alembic import op +import sqlalchemy as sa + +revision = 'iw1a2b3c4d5e' +down_revision = 'if1b2c3d4e5i' +branch_labels = None +depends_on = None + +def _i(): return sa.inspect(op.get_bind()) +def _tables(): return set(_i().get_table_names()) +def _cols(t): return {x['name'] for x in _i().get_columns(t)} +def _drop_uq(t, n): + if n in {x.get('name') for x in _i().get_unique_constraints(t)}: op.drop_constraint(n, t, type_='unique') +def _drop_idx(t, n): + if n in {x.get('name') for x in _i().get_indexes(t)}: op.drop_index(n, table_name=t) + +def _drop_column_with_dependencies(t, column): + """按实际库结构先解除列级外键/索引,再删除已退役的 OT 投影列。""" + if column not in _cols(t): + return + with op.batch_alter_table(t) as b: + for fk in _i().get_foreign_keys(t): + if column in (fk.get('constrained_columns') or []) and fk.get('name'): + b.drop_constraint(fk['name'], type_='foreignkey') + for index in _i().get_indexes(t): + if column in (index.get('column_names') or []) and index.get('name'): + b.drop_index(index['name']) + b.drop_column(column) + + +def _clean_task_step_payloads(): + """删除 OT JSON 中已迁移的业务事实,仅保留 UI/解析摘要。""" + if 'shipping_order_tasks' not in _tables() or 'step_payload_json' not in _cols('shipping_order_tasks'): + return + table = sa.table('shipping_order_tasks', sa.column('id', sa.Integer()), sa.column('step_payload_json', sa.JSON())) + removed = { + 'field_conflicts', 'process_field_gate', 'inventory_rpa_skipped', + 'last_inventory_rpa_runtime', 'line_inventory_candidates', + 'candidate_inventory_prep', 'line_inventory_resolutions', + 'forced_match_source_code', 'current_match_projection', + 'resolved_ok_source_codes', 'multi_source_excel_block', + 'inventory_source_resolution', 'rpa_inventory_source', 'export_meta', + 'invalidated_from_stage', 'last_conflict_resolve_idempotency_key', + 'last_notice_edit_idempotency', + } + bind = op.get_bind() + for row in bind.execute(sa.select(table.c.id, table.c.step_payload_json)).all(): + payload = row.step_payload_json + if not isinstance(payload, dict): + continue + cleaned = {key: value for key, value in payload.items() if key not in removed} + if cleaned != payload: + bind.execute(table.update().where(table.c.id == row.id).values(step_payload_json=cleaned or None)) + +_OT_COLUMNS = { + 'order_data_version': sa.Column('order_data_version', sa.Integer(), nullable=False, server_default='1'), + 'current_order_extraction_id': sa.Column('current_order_extraction_id', sa.Integer(), nullable=True), + 'order_snapshot_id': sa.Column('order_snapshot_id', sa.Integer(), nullable=True), + 'active_inventory_candidate_set_id': sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True), + 'step_payload_json': sa.Column('step_payload_json', sa.JSON(), nullable=True), + 'active_process_execution_id': sa.Column('active_process_execution_id', sa.Integer(), nullable=True), +} +_TASK_FKS = { + 'shipping_order_snapshots': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_events': ('task_id', 'shipping_order_tasks'), + 'shipping_order_review_confirmed_revisions': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_wave_lines': ('task_id', 'shipping_order_tasks'), + 'shipping_order_review_wave_idempotency': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_line_decisions': ('task_id', 'shipping_order_tasks'), + 'shipping_inventory_candidate_sets': ('task_id', 'shipping_order_tasks'), 'shipping_process_executions': ('task_id', 'shipping_order_tasks'), + 'shipping_process_gates': ('task_id', 'shipping_order_tasks'), 'shipping_inventory_preparation_attempts': ('task_id', 'shipping_order_tasks'), + 'shipping_notice_reservations': ('task_id', 'shipping_order_tasks'), 'shipping_notice_inventory_verifications': ('task_id', 'shipping_order_tasks'), + 'shipping_task_inventory_links': ('task_id', 'shipping_order_tasks'), 'shipping_temporary_inventory_sessions': ('task_id', 'shipping_order_tasks'), + 'shipping_task_events': ('task_id', 'shipping_order_tasks'), + 'shipping_notice_line_inventory_matches': ('task_id', 'shipping_order_tasks'), 'shipping_task_field_conflicts': ('task_id', 'shipping_order_tasks'), + 'shipping_order_extractions': ('task_id', 'shipping_order_tasks'), 'shipping_order_intakes': ('consumed_task_id', 'shipping_order_tasks'), + 'shipping_order_candidates': ('consumed_task_id', 'shipping_order_tasks'), +} + +def _repoint(t, c, target): + if t not in _tables(): return + fks = [x for x in _i().get_foreign_keys(t) if c in (x.get('constrained_columns') or [])] + with op.batch_alter_table(t) as b: + for fk in fks: + if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey') + b.create_foreign_key(f'fk_{t}_{c}_order_task', target, [c], ['id'], ondelete='CASCADE') + +def upgrade() -> None: + tables = _tables() + _clean_task_step_payloads() + # Notice 的库存确认人/时间是旧的单头运行投影;正式确认事实由 + # PreparationAttempt/SourceAttempt 与 GateAttempt 承载。 + if 'shipping_notices' in tables: + for n in ( + 'inventory_connector_type', + 'active_inventory_candidate_set_id', + 'active_process_execution_id', + 'inventory_snapshot_id', + 'inventory_source_confirmed_by', + 'inventory_source_confirmed_at', + 'inventory_lines_json', + 'match_status', + 'shortage_json', + 'line_results_json', + 'inventory_source_code', + 'inventory_source_status', + 'inventory_source_method', + 'inventory_source_config_version', + 'inventory_routing_fingerprint', + 'inventory_rpa_consumed_run_no', + ): + _drop_column_with_dependencies('shipping_notices', n) + if 'shipping_order_tasks' in tables: + existing = _cols('shipping_order_tasks') + with op.batch_alter_table('shipping_order_tasks') as b: + for n, c in _OT_COLUMNS.items(): + if n not in existing: b.add_column(c) + for n in ( + 'inventory_source_code', 'inventory_connector_type', 'inventory_source_status', + 'inventory_source_method', 'inventory_source_config_version', + 'inventory_routing_fingerprint', 'inventory_snapshot_id', + ): + if n in existing: b.drop_column(n) + for n in ( + 'customer_id', 'customer_resolution_status', 'customer_resolution_method', + 'customer_identity_fingerprint', 'customer_confirmed_by', 'customer_confirmed_at', + 'pending_human_reason', + ): + _drop_column_with_dependencies('shipping_order_tasks', n) + # 已部署环境可能在本迁移到达 head 后仍残留历史 OT 投影列(例如旧分支 + # 曾先执行过迁移、再补充模型字段)。这里再次按实际 schema 幂等清理, + # 确保“模型无字段、数据库也无字段”最终一致,而不依赖迁移执行时序。 + for n in ( + 'customer_name_snapshot', 'customer_short_code_snapshot', + 'destination_code', 'destination_city', 'destination_country', 'warehouse_hint', + 'inventory_source_code', 'inventory_connector_type', 'inventory_source_status', + 'inventory_source_method', 'inventory_source_config_version', + 'inventory_routing_fingerprint', 'inventory_snapshot_id', + 'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json', + ): + _drop_column_with_dependencies('shipping_order_tasks', n) + cols = _cols('shipping_order_tasks') + if 'shipping_notice_id' in cols: + fks = [x for x in _i().get_foreign_keys('shipping_order_tasks') if 'shipping_notice_id' in (x.get('constrained_columns') or [])] + with op.batch_alter_table('shipping_order_tasks') as b: + for fk in fks: + if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey') + b.drop_column('shipping_notice_id') + # 订单/通知项次及身份硬切换(旧身份数据不回填)。 + if 'shipping_order_lines' in tables: + c = _cols('shipping_order_lines') + with op.batch_alter_table('shipping_order_lines') as b: + if 'line_key' in c: b.drop_column('line_key') + if 'draft_line_id' not in c: b.add_column(sa.Column('draft_line_id', sa.String(128), nullable=True)) + if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True)) + op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY extraction_id ORDER BY position,id) x FROM shipping_order_lines) UPDATE shipping_order_lines l SET line_no=n.x FROM n WHERE l.id=n.id''')) + with op.batch_alter_table('shipping_order_lines') as b: + b.alter_column('line_no', nullable=False, existing_type=sa.Integer()) + if 'uq_shipping_order_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_order_lines')}: b.create_unique_constraint('uq_shipping_order_lines_line_no', ['extraction_id','line_no']) + for t in ('shipping_order_review_suggestions','shipping_order_review_line_decisions'): + if t in tables: + c=_cols(t) + with op.batch_alter_table(t) as b: + if 'line_key' in c and 'draft_line_id' not in c: b.alter_column('line_key', new_column_name='draft_line_id') + elif 'line_key' in c: b.drop_column('line_key') + if 'shipping_order_snapshot_lines' in tables: + with op.batch_alter_table('shipping_order_snapshot_lines') as b: + if 'line_no' in _cols('shipping_order_snapshot_lines'): b.alter_column('line_no', existing_type=sa.String(64), type_=sa.Integer(), postgresql_using='line_no::integer') + op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY snapshot_id ORDER BY position,id) x FROM shipping_order_snapshot_lines) UPDATE shipping_order_snapshot_lines l SET line_no=n.x FROM n WHERE l.id=n.id''')) + if 'shipping_notice_lines' in tables: + c=_cols('shipping_notice_lines') + with op.batch_alter_table('shipping_notice_lines') as b: + if 'line_key' in c: b.drop_column('line_key') + if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True)) + if 'inventory_source_code' not in c: b.add_column(sa.Column('inventory_source_code', sa.String(64), nullable=True)) + if 'inventory_file_id' not in c: b.add_column(sa.Column('inventory_file_id', sa.Integer(), nullable=True)) + if 'inventory_warehouse_id' not in c: b.add_column(sa.Column('inventory_warehouse_id', sa.String(64), nullable=True)) + op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY notice_id ORDER BY position,id) x FROM shipping_notice_lines) UPDATE shipping_notice_lines l SET line_no=n.x FROM n WHERE l.id=n.id''')) + with op.batch_alter_table('shipping_notice_lines') as b: + b.alter_column('line_no', nullable=False, existing_type=sa.Integer()) + if 'uq_shipping_notice_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_notice_lines')}: b.create_unique_constraint('uq_shipping_notice_lines_line_no', ['notice_id','line_no']) + if 'fk_shipping_notice_lines_inventory_file' not in {x.get('name') for x in _i().get_foreign_keys('shipping_notice_lines')}: + b.create_foreign_key('fk_shipping_notice_lines_inventory_file', 'shipping_inventory_files', ['inventory_file_id'], ['id'], ondelete='SET NULL') + existing_indexes = {x.get('name') for x in _i().get_indexes('shipping_notice_lines')} + if 'ix_shipping_notice_lines_inventory_source_code' not in existing_indexes: + b.create_index('ix_shipping_notice_lines_inventory_source_code', ['inventory_source_code']) + if 'ix_shipping_notice_lines_inventory_file_id' not in existing_indexes: + b.create_index('ix_shipping_notice_lines_inventory_file_id', ['inventory_file_id']) + if 'ix_shipping_notice_lines_inventory_warehouse_id' not in existing_indexes: + b.create_index('ix_shipping_notice_lines_inventory_warehouse_id', ['inventory_warehouse_id']) + if 'shipping_notices' in tables and 'inventory_warehouse_id' in _cols('shipping_notices'): + with op.batch_alter_table('shipping_notices') as b: + b.drop_column('inventory_warehouse_id') + if 'shipping_order_review_wave_lines' in tables: + c=_cols('shipping_order_review_wave_lines'); _drop_uq('shipping_order_review_wave_lines','uq_shipping_review_wave_lines_case_line'); op.execute(sa.text('DELETE FROM shipping_order_review_wave_lines')) + existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_review_wave_lines')} + has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_order_review_wave_lines')) + existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_order_review_wave_lines')} + with op.batch_alter_table('shipping_order_review_wave_lines') as b: + if 'line_key' in c: b.drop_column('line_key') + if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id', sa.Integer(), nullable=False)) + if not has_snapshot_line_fk and 'fk_shipping_review_wave_lines_snapshot_line' not in existing_fks: + b.create_foreign_key('fk_shipping_review_wave_lines_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE') + if 'uq_shipping_review_wave_lines_case_snapshot_line' not in existing_uqs: + b.create_unique_constraint('uq_shipping_review_wave_lines_case_snapshot_line',['review_case_id','snapshot_line_id']) + if 'shipping_order_review_wave_idempotency' in tables: + c=_cols('shipping_order_review_wave_idempotency') + with op.batch_alter_table('shipping_order_review_wave_idempotency') as b: + if 'line_keys_json' in c and 'snapshot_line_ids_json' not in c: b.alter_column('line_keys_json',new_column_name='snapshot_line_ids_json') + if 'line_keys_hash' in c and 'snapshot_line_ids_hash' not in c: b.alter_column('line_keys_hash',new_column_name='snapshot_line_ids_hash') + if 'shipping_notice_line_inventory_matches' in tables: + c=_cols('shipping_notice_line_inventory_matches'); op.execute(sa.text('DELETE FROM shipping_notice_line_inventory_matches')); _drop_idx('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_current'); _drop_uq('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_task_line_snap') + existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches')} + has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches')) + existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_notice_line_inventory_matches')} + with op.batch_alter_table('shipping_notice_line_inventory_matches') as b: + if 'line_key' in c: b.drop_column('line_key') + if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True)) + if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id',sa.Integer(),nullable=False)) + else: b.alter_column('snapshot_line_id',nullable=False,existing_type=sa.Integer()) + if not has_snapshot_line_fk and 'fk_shipping_notice_line_inventory_matches_snapshot_line' not in existing_fks: + b.create_foreign_key('fk_shipping_notice_line_inventory_matches_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE') + if 'uq_shipping_notice_line_inv_match_task_snapshot_line_snap' not in existing_uqs: + b.create_unique_constraint('uq_shipping_notice_line_inv_match_task_snapshot_line_snap',['task_id','snapshot_line_id','inventory_snapshot_id']) + if 'uq_shipping_notice_line_inv_match_current' not in {x.get('name') for x in _i().get_indexes('shipping_notice_line_inventory_matches')}: + b.create_index('uq_shipping_notice_line_inv_match_current',['task_id','snapshot_line_id'],unique=True,postgresql_where=sa.text('is_current IS TRUE')) + op.execute(sa.text(""" + UPDATE shipping_notice_line_inventory_matches m + SET line_no = COALESCE(sl.line_no, m.line_index + 1, 1) + FROM shipping_order_snapshot_lines sl + WHERE m.snapshot_line_id = sl.id + AND m.line_no IS NULL + """)) + with op.batch_alter_table('shipping_notice_line_inventory_matches') as b: + b.alter_column('line_no', nullable=False, existing_type=sa.Integer(), server_default='1') + # shipping_task_events.task_id 记录正式 ShippingOrderTask.id;部分旧环境 + # 的外键错误指向 shipping_notices,导致确认建单写审计事件时触发 FK 违反。 + if 'shipping_task_events' in tables and 'shipping_order_tasks' in tables: + event_fk = next( + ( + fk for fk in _i().get_foreign_keys('shipping_task_events') + if tuple(fk.get('constrained_columns') or []) == ('task_id',) + ), + None, + ) + if not event_fk or event_fk.get('referred_table') != 'shipping_order_tasks': + old_fk_name = str(event_fk.get('name') or 'shipping_task_events_task_id_fkey') if event_fk else None + if old_fk_name: + with op.batch_alter_table('shipping_task_events') as b: + b.drop_constraint(old_fk_name, type_='foreignkey') + invalid_count = op.get_bind().execute(sa.text( + """ + SELECT COUNT(*) + FROM shipping_task_events e + WHERE NOT EXISTS ( + SELECT 1 FROM shipping_order_tasks t WHERE t.id = e.task_id + ) + """ + )).scalar_one() + if int(invalid_count or 0): + raise RuntimeError( + 'shipping_task_events contains rows whose task_id is not a ' + 'shipping_order_tasks.id; repair those audit rows before migration' + ) + with op.batch_alter_table('shipping_task_events') as b: + b.create_foreign_key( + 'fk_shipping_task_events_task_id_order_task', + 'shipping_order_tasks', ['task_id'], ['id'], ondelete='CASCADE', + ) + bind=op.get_bind() + if 'shipping_excel_templates' in tables: + t=sa.table('shipping_excel_templates',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON())) + def rw(v): + if isinstance(v,dict): + r={k:rw(x) for k,x in v.items()} + if r.get('source_kind') == 'system_fact' and r.get('source_key') == 'export_sequence': + r['source_key'] = 'notice_line_no' + return r + return [rw(x) for x in v] if isinstance(v,list) else v + for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all(): + v=rw(row.definition_json) + if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v)) + if 'shipping_order_schema_versions' in tables: + t=sa.table('shipping_order_schema_versions',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON())) + for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all(): + v=copy.deepcopy(row.definition_json) + if isinstance(v,dict): + # line_no 是系统项次标准字段,必须保留;这里只移除已废弃的派生规则配置。 + v.pop('derivation_rules',None); v.pop('derivation_rules_checksum',None) + if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v)) + if 'shipping_order_fields' in tables: + # line_no 已硬切换为系统生成整数项次;纠偏旧资产种子遗留的 string 类型。 + op.execute(sa.text(""" + UPDATE shipping_order_fields + SET value_type = 'integer', updated_at = CURRENT_TIMESTAMP + WHERE field_code = 'line_no' + AND scope = 'line' + AND asset_kind = 'system_standard' + """)) + if 'shipping_order_tasks' in tables: + with op.batch_alter_table('shipping_order_tasks') as b: + for n,c in _OT_COLUMNS.items(): + pass + if 'lifecycle_status' not in _cols('shipping_order_tasks'): b.add_column(sa.Column('lifecycle_status',sa.String(16),nullable=False,server_default='active')) + for n, typ in (('current_step', sa.String(64)), ('review_status', sa.String(32)), ('pending_human_reason', sa.String(64))): + if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n, typ, nullable=True)) + for n in ('deleted_at','voided_at','archived_at'): + if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.DateTime(),nullable=True)) + for n in ('deletion_reason','void_reason'): + if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Text(),nullable=True)) + for n in ('deleted_by_id','voided_by_id','archived_by_id'): + if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Integer(),nullable=True)) + if 'lifecycle_status' not in _cols('shipping_order_tasks'): + b.create_check_constraint('ck_shipping_order_tasks_lifecycle_status', "lifecycle_status IN ('active', 'voided', 'archived')") + existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_tasks')} + for name, column in ( + ('fk_shipping_order_tasks_deleted_by', 'deleted_by_id'), + ('fk_shipping_order_tasks_voided_by', 'voided_by_id'), + ('fk_shipping_order_tasks_archived_by', 'archived_by_id'), + ): + if name not in existing_fks: + b.create_foreign_key(name, 'users', [column], ['id']) + obsolete_cols = { + 'customer_name_snapshot', 'customer_short_code_snapshot', + 'destination_code', 'destination_city', 'destination_country', 'warehouse_hint', + 'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json', + } & _cols('shipping_order_tasks') + if obsolete_cols: + with op.batch_alter_table('shipping_order_tasks') as b: + for column in sorted(obsolete_cols): + b.drop_column(column) + + if 'shipping_notices' in tables: + _drop_idx('shipping_notices', 'ix_shipping_notices_current_step') + _drop_idx('shipping_notices', 'ix_shipping_notices_upload_status') + _drop_idx('shipping_notices', 'ix_shipping_notices_order_snapshot_id') + _drop_idx('shipping_notices', 'ix_shipping_tasks_order_snapshot_id') + obsolete_notice_cols = { + 'export_file_path', 'export_file_name', 'export_version', 'freight_ref_no', + 'upload_status', 'upload_mode', 'upload_attempt', 'idempotency_key', + 'upload_started_at', 'upload_finished_at', 'upload_error_code', + 'upload_error_message', 'upload_receipt_json', + 'current_step', 'review_status', 'step_payload_json', 'pending_human_reason', 'error_message', + 'customer_id', 'customer_name_snapshot', 'customer_short_code_snapshot', + 'customer_resolution_status', 'customer_resolution_method', 'customer_identity_fingerprint', + 'customer_confirmed_by', 'customer_confirmed_at', + 'destination_code', 'destination_city', 'destination_country', 'warehouse_hint', + 'parse_confidence', 'order_data_version', 'current_order_extraction_id', + 'order_snapshot_id', 'raw_content', 'source_file_name', 'source_file_type', 'source_content_hash', + 'business_fingerprint', 'fingerprint_version', 'content_fingerprint', 'content_fingerprint_version', + 'batch_index', 'batch_total', + } & _cols('shipping_notices') + for column in sorted(obsolete_notice_cols): + _drop_column_with_dependencies('shipping_notices', column) + + if 'shipping_order_tasks' in tables: + _drop_idx('shipping_order_tasks', 'ix_shipping_tasks_order_snapshot_id') + _drop_idx('shipping_order_tasks', 'ix_shipping_order_tasks_order_snapshot_id') + _drop_uq('shipping_order_tasks', 'uq_shipping_order_tasks_order_snapshot_id') + + + # 统一所有履约事实的 task_id 外键目标;旧通知表中的孤儿数据不做猜测回填。 + for table, (column, target) in _TASK_FKS.items(): + if table not in _tables(): + continue + # 不同历史表的任务关联列名并不统一;列不存在时跳过该映射,避免生成无效 SQL。 + if column not in _cols(table): + continue + # 已被发货通知引用的快照不能作为孤儿删除,否则会触发外键冲突。 + keep_referenced = ( + " AND NOT EXISTS (SELECT 1 FROM shipping_notices sn WHERE sn.order_task_id = t.task_id)" + if table == 'shipping_order_snapshots' and 'shipping_notices' in _tables() + else '' + ) + op.execute(sa.text( + f'DELETE FROM {table} t WHERE t.{column} IS NOT NULL AND NOT EXISTS ' + f'(SELECT 1 FROM shipping_order_tasks ot WHERE ot.id = t.{column})' + f'{keep_referenced}' + )) + _repoint(table, column, target) + if 'shipping_order_review_cases' in _tables(): + _repoint('shipping_order_review_cases', 'confirmed_task_id', 'shipping_order_tasks') + +def downgrade() -> None: + raise RuntimeError('order line identity contract is intentionally irreversible') diff --git a/backend/migrations/versions/ix1a2b3c4d5e_split_integration_connector_columns.py b/backend/migrations/versions/ix1a2b3c4d5e_split_integration_connector_columns.py new file mode 100644 index 00000000..e3fe70ba --- /dev/null +++ b/backend/migrations/versions/ix1a2b3c4d5e_split_integration_connector_columns.py @@ -0,0 +1,43 @@ +"""split integration connector columns + +Revision ID: ix1a2b3c4d5e +Revises: iy1a2b3c4d5e +Create Date: 2026-09-01 09:00:00.000000 + +用途:把集成连接器"真正强类型的关键字段"从 JSON 拆成独立列,JSON 保留作兜底。 + ClientInstance:endpoint(连接地址:REST=接口地址,SOAP=WSDL 地址)/ timeout_seconds; + InterfaceDefinition:http_method / request_path; + Binding:context_source_code。 +依赖:ic1a2b3c4d5f 建表;不新建表,仅加列。 +逻辑:SOAP 只需 WSDL(其内已含服务端点),故合一为 endpoint 字段;列可为空(存量数据 + 回填后由应用层拼回 JSON);不删 JSON,保证兼容层运行时零改动。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'ix1a2b3c4d5e' +down_revision = 'iy1a2b3c4d5e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """在三张连接器表上新增关键字段列(nullable:存量数据回填后走兼容层)。""" + op.add_column('integration_client_instances', sa.Column('endpoint', sa.String(length=512), nullable=True)) + op.add_column('integration_client_instances', sa.Column('timeout_seconds', sa.Integer(), nullable=True)) + + op.add_column('integration_interface_definitions', sa.Column('http_method', sa.String(length=16), nullable=True)) + op.add_column('integration_interface_definitions', sa.Column('request_path', sa.String(length=512), nullable=True)) + + op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True)) + + +def downgrade() -> None: + """回滚:删除新增列(JSON 兜底仍在,数据不丢)。""" + op.drop_column('integration_bindings', 'context_source_code') + op.drop_column('integration_interface_definitions', 'request_path') + op.drop_column('integration_interface_definitions', 'http_method') + op.drop_column('integration_client_instances', 'timeout_seconds') + op.drop_column('integration_client_instances', 'endpoint') diff --git a/backend/migrations/versions/iy1a2b3c4d5e_drop_shipping_order_customer_matches.py b/backend/migrations/versions/iy1a2b3c4d5e_drop_shipping_order_customer_matches.py new file mode 100644 index 00000000..e837242b --- /dev/null +++ b/backend/migrations/versions/iy1a2b3c4d5e_drop_shipping_order_customer_matches.py @@ -0,0 +1,125 @@ +"""收敛客户确认主链并删除已退役的订单角色匹配表。""" +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + +revision = 'iy1a2b3c4d5e' +down_revision = 'iw1a2b3c4d5e' +branch_labels = None +depends_on = None + + +def _columns(table_name: str) -> set[str]: + """返回表当前列名,支持工作区迁移的幂等升级。""" + return {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)} + + +def upgrade() -> None: + """补齐当前主链字段后删除已无生产读写方的旧角色匹配表。""" + # [STEP 1] 合并原 35d4 任务进度补列。 + with op.batch_alter_table('shipping_order_tasks') as batch: + columns = _columns('shipping_order_tasks') + if 'current_step' not in columns: + batch.add_column(sa.Column('current_step', sa.String(length=64), nullable=True)) + if 'review_status' not in columns: + batch.add_column(sa.Column('review_status', sa.String(length=32), nullable=True)) + + # [STEP 2] 合并原 ix1 客户 Resolution 确认字段升级。 + if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()): + columns = _columns('shipping_customer_shadow_resolutions') + with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch: + constraints = { + item.get('name') + for item in sa.inspect(op.get_bind()).get_check_constraints('shipping_customer_shadow_resolutions') + } + if 'ck_shipping_customer_shadow_status' in constraints: + batch.drop_constraint('ck_shipping_customer_shadow_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_customer_shadow_status', + "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')", + ) + if 'confirmed_customer_id' not in columns: + batch.add_column(sa.Column('confirmed_customer_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_customer_resolution_confirmed_customer', + 'shipping_customers', ['confirmed_customer_id'], ['id'], + ) + if 'confirmation_method' not in columns: + batch.add_column(sa.Column('confirmation_method', sa.String(length=32), nullable=True)) + if 'confirmation_reason' not in columns: + batch.add_column(sa.Column('confirmation_reason', sa.String(length=500), nullable=True)) + if 'confirmed_by_id' not in columns: + batch.add_column(sa.Column('confirmed_by_id', sa.Integer(), nullable=True)) + batch.create_foreign_key('fk_shipping_customer_resolution_confirmed_by', 'users', ['confirmed_by_id'], ['id']) + if 'confirmed_at' not in columns: + batch.add_column(sa.Column('confirmed_at', sa.DateTime(), nullable=True)) + + # [STEP 3] 旧表物理删除。 + bind = op.get_bind() + if 'shipping_order_customer_matches' in set(sa.inspect(bind).get_table_names()): + op.drop_table('shipping_order_customer_matches') + + +def downgrade() -> None: + """恢复旧表空结构并回退本迁移合并的新增字段;不恢复已删除数据。""" + op.create_table( + 'shipping_order_customer_matches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('extraction_id', sa.Integer(), nullable=False), + sa.Column('role', sa.String(length=16), nullable=False), + sa.Column('raw_name', sa.Text(), nullable=True), + sa.Column('normalized_name', sa.String(length=500), nullable=True), + sa.Column('source_system', sa.String(length=64), nullable=True), + sa.Column('external_code', sa.String(length=128), nullable=True), + sa.Column('identity_fingerprint', sa.String(length=64), nullable=True), + sa.Column('identity_rule_version', sa.String(length=32), nullable=True), + sa.Column('identity_components_json', sa.JSON(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('site_id', sa.Integer(), nullable=True), + sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True), + sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True), + sa.Column('candidates_json', sa.JSON(), nullable=False), + sa.Column('resolution_method', sa.String(length=32), nullable=True), + sa.Column('confirmation_reason', sa.Text(), nullable=True), + sa.Column('confirmed_by_id', sa.Integer(), nullable=True), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'), + sa.CheckConstraint( + "status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')", + name='ck_shipping_order_customer_matches_status', + ), + sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']), + sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['site_id'], ['shipping_customer_sites.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'), + ) + op.create_index('ix_shipping_order_customer_matches_extraction_id', 'shipping_order_customer_matches', ['extraction_id']) + op.create_index('ix_shipping_order_customer_matches_customer_role', 'shipping_order_customer_matches', ['customer_id', 'role']) + op.create_index('ix_shipping_order_customer_matches_identity_fingerprint', 'shipping_order_customer_matches', ['identity_fingerprint']) + + if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()): + with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch: + for name in ( + 'fk_shipping_customer_resolution_confirmed_by', + 'fk_shipping_customer_resolution_confirmed_customer', + ): + try: + batch.drop_constraint(name, type_='foreignkey') + except Exception: + pass + columns = _columns('shipping_customer_shadow_resolutions') + for name in ('confirmed_at', 'confirmed_by_id', 'confirmation_reason', 'confirmation_method', 'confirmed_customer_id'): + if name in columns: + batch.drop_column(name) + + with op.batch_alter_table('shipping_order_tasks') as batch: + columns = _columns('shipping_order_tasks') + for name in ('review_status', 'current_step'): + if name in columns: + batch.drop_column(name) diff --git a/backend/migrations/versions/n9a0b1c2d3e4_merge_integration_connector_and_contract_payment_heads.py b/backend/migrations/versions/n9a0b1c2d3e4_merge_integration_connector_and_contract_payment_heads.py new file mode 100644 index 00000000..294c2b1b --- /dev/null +++ b/backend/migrations/versions/n9a0b1c2d3e4_merge_integration_connector_and_contract_payment_heads.py @@ -0,0 +1,30 @@ +"""合并集成连接器列拆分与合同付款/发货通知两条 Alembic 头。 + +Revision ID: n9a0b1c2d3e4 +Revises: ix1a2b3c4d5e, n8f9a0b1c2d3 +Create Date: 2026-09-07 10:00:00.000000 + +用途:将 ``ix1a2b3c4d5e``(集成连接器强类型列拆分)与 + ``n8f9a0b1c2d3``(合同付款与发货通知 head 合并)收成单一升级路径, + 避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。 +依赖:``ix1a2b3c4d5e``、``n8f9a0b1c2d3``。 +逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。 +""" + +from alembic import op # noqa: F401 - Alembic migration module contract + + +revision = "n9a0b1c2d3e4" +down_revision = ("ix1a2b3c4d5e", "n8f9a0b1c2d3") +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """合并集成连接器 head 与合同付款/发货通知 head,不执行数据库结构变更。""" + pass + + +def downgrade() -> None: + """撤销合并节点;不会回滚两个父分支的业务变更。""" + pass diff --git a/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py b/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py new file mode 100644 index 00000000..daa7c41a --- /dev/null +++ b/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py @@ -0,0 +1,30 @@ +"""合并立账凭证引擎表与 dev 集成连接器两条 Alembic 头。 + +Revision ID: na0b1c2d3e4f5 +Revises: n9a0b1c2d3e4, vc1a2b3c4d5e +Create Date: 2026-09-07 14:25:00.000000 + +用途:将 ``invoice-check`` 的 ``vc1a2b3c4d5e``(立账凭证引擎表)与 + ``dev`` 的 ``n9a0b1c2d3e4``(集成连接器 / 合同付款 head 合并)收成单一升级路径, + 避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。 +依赖:``n9a0b1c2d3e4``、``vc1a2b3c4d5e``。 +逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。 +""" + +from alembic import op # noqa: F401 - Alembic migration module contract + + +revision = "na0b1c2d3e4f5" +down_revision = ("n9a0b1c2d3e4", "vc1a2b3c4d5e") +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """合并立账凭证引擎 head 与 dev 集成连接器 head,不执行数据库结构变更。""" + pass + + +def downgrade() -> None: + """撤销合并节点;不会回滚两个父分支的业务变更。""" + pass diff --git a/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py b/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py new file mode 100644 index 00000000..1d3d8f1e --- /dev/null +++ b/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py @@ -0,0 +1,237 @@ +""" +backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py + +用途:新增立账凭证检核引擎表(Profile/批次/主体/单文件结果/通知),并把默认排程改为每周二。 +依赖:Alembic revision n8f9a0b1c2d3;旧 voucher_check_invoice_states / run_items 保留只读。 +逻辑:建五张新表;仅当默认任务仍是日批 cron 时改为周二 06:00。 + +Revision ID: vc1a2b3c4d5e +Revises: n8f9a0b1c2d3 +Create Date: 2026-09-04 10:30:00.000000 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "vc1a2b3c4d5e" +down_revision = "n8f9a0b1c2d3" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK" +_OLD_CRON = "0 6 * * *" +_NEW_CRON = "0 6 * * 2" +_TZ_NAME = "Asia/Shanghai" + + +def _compute_next_run_at_utc_naive() -> datetime: + try: + from croniter import croniter + from zoneinfo import ZoneInfo + + tz = ZoneInfo(_TZ_NAME) + base = datetime.now(tz) + next_local = croniter(_NEW_CRON, base).get_next(datetime) + if next_local.tzinfo is None: + next_local = next_local.replace(tzinfo=tz) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + except Exception: + tz = timezone(timedelta(hours=8)) + now_local = datetime.now(tz) + next_local = now_local.replace(hour=6, minute=0, second=0, microsecond=0) + while next_local <= now_local or next_local.weekday() != 1: + next_local = next_local + timedelta(days=1) + next_local = next_local.replace(hour=6, minute=0, second=0, microsecond=0) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> None: + op.create_table( + "voucher_check_profiles", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column("profile_code", sa.String(length=32), nullable=False), + sa.Column("version", sa.String(length=32), nullable=False), + sa.Column("definition_json", sa.JSON(), nullable=False), + sa.Column("status", sa.String(length=24), nullable=False, server_default="published"), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"), + ) + op.create_index("ix_voucher_check_profiles_status", "voucher_check_profiles", ["status"]) + + op.create_table( + "voucher_check_runs", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "schedule_run_id", + sa.BigInteger(), + sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("run_no", sa.String(length=64), nullable=False), + sa.Column("profile_code", sa.String(length=32), nullable=False), + sa.Column("profile_version", sa.String(length=32), nullable=False), + sa.Column("profile_snapshot_json", sa.JSON(), nullable=False), + sa.Column("period_month", sa.Date(), nullable=False), + sa.Column("mode", sa.String(length=24), nullable=False, server_default="incremental"), + sa.Column("status", sa.String(length=24), nullable=False, server_default="running"), + sa.Column("subject_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("archived_file_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("skipped_file_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("missing_file_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("missing_invoice_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("technical_error_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("staged_file_count", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("stats_json", sa.JSON(), nullable=True), + sa.Column("started_at", sa.DateTime(), nullable=True), + sa.Column("finished_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + ) + op.create_index("ix_voucher_check_runs_schedule_run_id", "voucher_check_runs", ["schedule_run_id"]) + op.create_index( + "ix_voucher_check_runs_period_profile", + "voucher_check_runs", + ["period_month", "profile_code"], + ) + op.create_index("ix_voucher_check_runs_status", "voucher_check_runs", ["status"]) + op.create_index("ix_voucher_check_runs_finished_at", "voucher_check_runs", ["finished_at"]) + + op.create_table( + "voucher_check_subjects", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "run_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("invoice_date", sa.Date(), nullable=True), + sa.Column("source_fingerprint", sa.String(length=64), nullable=True), + sa.Column("attributes_json", sa.JSON(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"), + ) + op.create_index("ix_voucher_check_subjects_run_id", "voucher_check_subjects", ["run_id"]) + op.create_index("ix_voucher_check_subjects_invoice_no", "voucher_check_subjects", ["invoice_no"]) + + op.create_table( + "voucher_check_file_results", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "run_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column( + "subject_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("rule_code", sa.String(length=64), nullable=False), + sa.Column("rule_name", sa.String(length=128), nullable=False), + sa.Column("source_type", sa.String(length=32), nullable=False), + sa.Column("expected_name", sa.String(length=512), nullable=True), + sa.Column("matched_name", sa.String(length=512), nullable=True), + sa.Column("source_folder_id", sa.String(length=64), nullable=True), + sa.Column("source_item_id", sa.String(length=64), nullable=True), + sa.Column("archive_folder_id", sa.String(length=64), nullable=True), + sa.Column("archive_item_id", sa.String(length=64), nullable=True), + sa.Column("source_path", sa.String(length=1024), nullable=True), + sa.Column("archive_path", sa.String(length=1024), nullable=True), + sa.Column("status", sa.String(length=24), nullable=False), + sa.Column("missing_reason", sa.String(length=255), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("source_fingerprint", sa.String(length=64), nullable=True), + sa.Column("checked_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint( + "run_id", + "invoice_no", + "rule_code", + name="uq_voucher_check_file_results_run_invoice_rule", + ), + ) + op.create_index("ix_voucher_check_file_results_run_id", "voucher_check_file_results", ["run_id"]) + op.create_index( + "ix_voucher_check_file_results_status", + "voucher_check_file_results", + ["run_id", "status"], + ) + op.create_index("ix_voucher_check_file_results_invoice", "voucher_check_file_results", ["invoice_no"]) + + op.create_table( + "voucher_check_notifications", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "run_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("excel_filename", sa.String(length=255), nullable=True), + sa.Column("recipient_user_ids_json", sa.JSON(), nullable=True), + sa.Column("send_status", sa.String(length=32), nullable=False), + sa.Column("skip_reason", sa.String(length=255), nullable=True), + sa.Column("summary_json", sa.JSON(), nullable=True), + sa.Column("sent_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint("run_id", name="uq_voucher_check_notifications_run_id"), + ) + op.create_index( + "ix_voucher_check_notifications_status", + "voucher_check_notifications", + ["send_status"], + ) + + conn = op.get_bind() + conn.execute( + sa.text( + """ + UPDATE schedule_tasks + SET cron_expr = :new_cron, + name = CASE + WHEN name = '立账凭证检核(日批)' THEN '立账凭证检核(周批)' + ELSE name + END, + next_run_at = :next_run, + updated_at = :now + WHERE schedule_no = :sno + AND cron_expr = :old_cron + """ + ), + { + "new_cron": _NEW_CRON, + "next_run": _compute_next_run_at_utc_naive(), + "now": datetime.utcnow(), + "sno": _SCHEDULE_NO, + "old_cron": _OLD_CRON, + }, + ) + + +def downgrade() -> None: + op.drop_index("ix_voucher_check_notifications_status", table_name="voucher_check_notifications") + op.drop_table("voucher_check_notifications") + op.drop_index("ix_voucher_check_file_results_invoice", table_name="voucher_check_file_results") + op.drop_index("ix_voucher_check_file_results_status", table_name="voucher_check_file_results") + op.drop_index("ix_voucher_check_file_results_run_id", table_name="voucher_check_file_results") + op.drop_table("voucher_check_file_results") + op.drop_index("ix_voucher_check_subjects_invoice_no", table_name="voucher_check_subjects") + op.drop_index("ix_voucher_check_subjects_run_id", table_name="voucher_check_subjects") + op.drop_table("voucher_check_subjects") + op.drop_index("ix_voucher_check_runs_finished_at", table_name="voucher_check_runs") + op.drop_index("ix_voucher_check_runs_status", table_name="voucher_check_runs") + op.drop_index("ix_voucher_check_runs_period_profile", table_name="voucher_check_runs") + op.drop_index("ix_voucher_check_runs_schedule_run_id", table_name="voucher_check_runs") + op.drop_table("voucher_check_runs") + op.drop_index("ix_voucher_check_profiles_status", table_name="voucher_check_profiles") + op.drop_table("voucher_check_profiles") diff --git a/backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py b/backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py new file mode 100644 index 00000000..0ed705e8 --- /dev/null +++ b/backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py @@ -0,0 +1,133 @@ +""" +backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py + +用途:删除旧共享盘方案的 voucher_check_invoice_states / voucher_check_run_items。 +依赖:Alembic revision na0b1c2d3e4f5。 +逻辑:先删 run_items(外键指向 states),再删 states;引擎表不受影响。 + +Revision ID: vc2b3c4d5e6f +Revises: na0b1c2d3e4f5 +Create Date: 2026-09-08 09:20:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "vc2b3c4d5e6f" +down_revision = "na0b1c2d3e4f5" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """删除旧一票一状态表;检核结果以 voucher_check_file_results 为准。""" + op.drop_index("ix_voucher_check_run_items_period_result", table_name="voucher_check_run_items") + op.drop_index("ix_voucher_check_run_items_run_result", table_name="voucher_check_run_items") + op.drop_index("ix_voucher_check_run_items_schedule_run_id", table_name="voucher_check_run_items") + op.drop_table("voucher_check_run_items") + op.drop_index("ix_voucher_check_invoice_states_notified_on", table_name="voucher_check_invoice_states") + op.drop_index("ix_voucher_check_invoice_states_invoice_no", table_name="voucher_check_invoice_states") + op.drop_index("ix_voucher_check_invoice_states_period_status", table_name="voucher_check_invoice_states") + op.drop_table("voucher_check_invoice_states") + + +def downgrade() -> None: + """回建旧表结构,不恢复历史数据。""" + op.create_table( + "voucher_check_invoice_states", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column("scope_code", sa.String(length=32), nullable=False), + sa.Column("period_month", sa.Date(), nullable=False), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("invoice_date", sa.Date(), nullable=True), + sa.Column("status", sa.String(length=24), nullable=False), + sa.Column("folder_path", sa.String(length=1024), nullable=True), + sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")), + sa.Column("material_fingerprint", sa.String(length=64), nullable=True), + sa.Column("matched_files_json", sa.JSON(), nullable=True), + sa.Column("missing_materials_json", sa.JSON(), nullable=True), + sa.Column( + "last_actual_run_id", + sa.BigInteger(), + sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("last_checked_at", sa.DateTime(), nullable=True), + sa.Column("last_seen_erp_at", sa.DateTime(), nullable=True), + sa.Column("last_missing_notified_on", sa.Date(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint( + "scope_code", + "period_month", + "invoice_no", + name="uq_voucher_check_invoice_states_scope_period_invoice", + ), + ) + op.create_index( + "ix_voucher_check_invoice_states_period_status", + "voucher_check_invoice_states", + ["period_month", "status"], + ) + op.create_index( + "ix_voucher_check_invoice_states_invoice_no", + "voucher_check_invoice_states", + ["invoice_no"], + ) + op.create_index( + "ix_voucher_check_invoice_states_notified_on", + "voucher_check_invoice_states", + ["last_missing_notified_on"], + ) + op.create_table( + "voucher_check_run_items", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "schedule_run_id", + sa.BigInteger(), + sa.ForeignKey("schedule_runs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column( + "invoice_state_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("scope_code", sa.String(length=32), nullable=False), + sa.Column("period_month", sa.Date(), nullable=False), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("invoice_date", sa.Date(), nullable=True), + sa.Column("result", sa.String(length=24), nullable=False), + sa.Column("folder_path", sa.String(length=1024), nullable=True), + sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")), + sa.Column("material_fingerprint", sa.String(length=64), nullable=True), + sa.Column("matched_files_json", sa.JSON(), nullable=True), + sa.Column("missing_materials_json", sa.JSON(), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("checked_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint( + "schedule_run_id", + "invoice_no", + name="uq_voucher_check_run_items_run_invoice", + ), + ) + op.create_index( + "ix_voucher_check_run_items_schedule_run_id", + "voucher_check_run_items", + ["schedule_run_id"], + ) + op.create_index( + "ix_voucher_check_run_items_run_result", + "voucher_check_run_items", + ["schedule_run_id", "result"], + ) + op.create_index( + "ix_voucher_check_run_items_period_result", + "voucher_check_run_items", + ["period_month", "result"], + ) diff --git a/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py b/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py new file mode 100644 index 00000000..c3138889 --- /dev/null +++ b/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py @@ -0,0 +1,146 @@ +""" +backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py + +用途:清掉立账凭证检核排程里共享盘时代的 job_params,避免 worker 报 unknown params。 +依赖:Alembic revision vc2b3c4d5e6f;schedule_tasks 已存在。 +逻辑:保留 scope_code / profile_code / 通知开关 / _advanced;日批 cron 改为周二。 + +Revision ID: vc3d4e5f6a7b +Revises: vc2b3c4d5e6f +Create Date: 2026-09-08 10:10:00.000000 +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "vc3d4e5f6a7b" +down_revision = "vc2b3c4d5e6f" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK" +_WEEKLY_CRON = "0 6 * * 2" +_WEEKLY_NAME = "立账凭证检核(周批)" +_DAILY_CRON = "0 6 * * *" +_DAILY_NAME = "立账凭证检核(日批)" +_TZ_NAME = "Asia/Shanghai" + +_DEFAULTS = { + "profile_code": "sales", + "scope_code": "HXJM", + "notify_missing_enabled": True, + "notify_failure_enabled": True, +} + + +def _as_dict(raw) -> dict: + """把 JSON 列读成 dict;驱动可能返回 dict 或字符串。""" + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + if isinstance(raw, str): + text = raw.strip() + if not text: + return {} + loaded = json.loads(text) + return dict(loaded) if isinstance(loaded, dict) else {} + return {} + + +def _clean_job_params(raw) -> dict: + """只保留当前 schema 字段,丢掉 directory_template / required_files 等旧键。""" + current = _as_dict(raw) + cleaned = {} + for key, default in _DEFAULTS.items(): + value = current.get(key) + cleaned[key] = default if value is None else value + advanced = current.get("_advanced") + if isinstance(advanced, dict): + cleaned["_advanced"] = advanced + return cleaned + + +def _next_weekly_run_utc_naive() -> datetime: + """计算下一个周二 06:00 Asia/Shanghai,写入 naive UTC。""" + try: + from croniter import croniter + from zoneinfo import ZoneInfo + + tz = ZoneInfo(_TZ_NAME) + next_local = croniter(_WEEKLY_CRON, datetime.now(tz)).get_next(datetime) + if next_local.tzinfo is None: + next_local = next_local.replace(tzinfo=tz) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + except Exception: + tz = timezone(timedelta(hours=8)) + now_local = datetime.now(tz) + days = (1 - now_local.weekday()) % 7 + next_local = (now_local + timedelta(days=days)).replace( + hour=6, minute=0, second=0, microsecond=0 + ) + if next_local <= now_local: + next_local = next_local + timedelta(days=7) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> None: + """清洗 accounting-voucher-check 排程参数;无任务时跳过。""" + conn = op.get_bind() + rows = conn.execute( + sa.text( + """ + SELECT id, job_params, cron_expr, name + FROM schedule_tasks + WHERE schedule_no = :sno + OR platform_api_path = 'accounting-voucher-check' + """ + ), + {"sno": _SCHEDULE_NO}, + ).mappings().all() + now = datetime.utcnow() + next_run = _next_weekly_run_utc_naive() + for row in rows: + cleaned = _clean_job_params(row["job_params"]) + cron_expr = row["cron_expr"] + name = row["name"] + next_run_at = None + if cron_expr == _DAILY_CRON: + cron_expr = _WEEKLY_CRON + next_run_at = next_run + if name == _DAILY_NAME: + name = _WEEKLY_NAME + conn.execute( + sa.text( + """ + UPDATE schedule_tasks + SET job_params = CAST(:job_params AS JSONB), + cron_expr = :cron_expr, + name = :name, + next_run_at = COALESCE(:next_run_at, next_run_at), + updated_at = :now + WHERE id = :id + """ + ).bindparams( + sa.bindparam("job_params", type_=sa.String()), + sa.bindparam("next_run_at", type_=sa.DateTime(), required=False), + ), + { + "id": int(row["id"]), + "job_params": json.dumps(cleaned, ensure_ascii=False), + "cron_expr": cron_expr, + "name": name, + "now": now, + "next_run_at": next_run_at, + }, + ) + + +def downgrade() -> None: + """旧共享盘字段无法无损恢复,downgrade 为空操作。""" + return diff --git a/backend/scripts/export_voucher_check_openapi.py b/backend/scripts/export_voucher_check_openapi.py deleted file mode 100644 index da8c97ce..00000000 --- a/backend/scripts/export_voucher_check_openapi.py +++ /dev/null @@ -1,39 +0,0 @@ -""" -backend/scripts/export_voucher_check_openapi.py - -用途:导出立账凭证检核 Tool OpenAPI 到 docs/openapi,供 Dify 粘贴/对比。 -依赖:voucher_check.openapi_spec。 -逻辑:仓库静态 JSON 使用占位地址;各环境请用 URL 导入 GET .../openapi.json。 -""" - -from __future__ import annotations - -import json -import os -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -# 不经 app 包导入,避免导出脚本依赖本机 Flask venv -_SPEC_PATH = ROOT / "backend" / "app" / "services" / "voucher_check" / "openapi_base.json" - - -def main() -> None: - base = ( - os.getenv("HXOPS_TOOLS_API_BASE") - or os.getenv("PUBLIC_BASE_URL") - or "http://127.0.0.1:5052" - ).rstrip("/") - spec = json.loads(_SPEC_PATH.read_text(encoding="utf-8")) - if isinstance(spec.get("servers"), list) and spec["servers"]: - spec["servers"][0]["url"] = base - spec["servers"][0]["description"] = "HXOPS_TOOLS_API_BASE" - out_dir = ROOT / "docs" / "openapi" - out_dir.mkdir(parents=True, exist_ok=True) - json_path = out_dir / "accounting_voucher_check_tools_openapi.json" - json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(f"Wrote {json_path}") - print(f"Import URL: {base}/api/accounting-voucher-check/tools/openapi.json") - - -if __name__ == "__main__": - main() diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py new file mode 100644 index 00000000..3bf190ef --- /dev/null +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -0,0 +1,448 @@ +"""在途调拨预检 API 契约测试(L2,Flask test client)。 + +用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与 + GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。 +依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。 +逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或 + in_transit_transfer Agent 授权校验。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import Agent, User +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +API_PREFIX = "/api/in-transit-transfer" + + +def _jwt_headers(user: User) -> dict: + """为指定用户签发 Bearer JWT 请求头。""" + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def transfer_deps(monkeypatch, dbs_ready_file): + """注入 Fake 预检依赖,并预置可执行库存。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + return deps + + +@pytest.fixture +def admin_headers(app): + """创建 admin 用户并返回 JWT 请求头(token 在 app context 内签发)。""" + with app.app_context(): + user = db.session.query(User).filter_by(username="admin").first() + if not user: + user = User(username="admin", email="admin@example.com", role="admin", status="active") + user.set_password("admin") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def warehouse_headers(app): + """创建持有 in_transit_transfer Agent 权限的仓库管理员并返回 JWT 请求头。""" + with app.app_context(): + agent = Agent.query.filter_by(agent_code="in_transit_transfer").first() + if not agent: + agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer", + type="api", is_active=True) + db.session.add(agent) + db.session.flush() + user = db.session.query(User).filter_by(username="warehouse").first() + if not user: + user = User(username="warehouse", email="warehouse@example.com", + role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.flush() + if agent not in user.agents: + user.agents.append(agent) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def unauthorized_headers(app): + """无 Agent 权限的普通用户 JWT 请求头。""" + with app.app_context(): + user = db.session.query(User).filter_by(username="no_perm").first() + if not user: + user = User(username="no_perm", email="no_perm@example.com", role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps): + """POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }) + assert response.status_code == 201 + body = response.get_json() + assert body["success"] is True + data = body["data"] + assert data["precheck_id"].startswith("TPC-") + assert data["precheck_hash"].startswith("sha256:") + assert data["estimated_erp_write_count"] == 2 + assert body.get("request_id") + + +def test_create_precheck_requires_authentication(client): + """未认证 → 401(envelope error)。""" + response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]}) + assert response.status_code == 401 + assert response.get_json()["success"] is False + + +def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers): + """无 in_transit_transfer Agent 权限 → 403。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={ + "source_codes": ["DBS-AWSBI"], + }) + assert response.status_code == 403 + assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" + + +def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps): + """持有 Agent 权限的仓库管理员可创建预检。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }) + assert response.status_code == 201 + assert response.get_json()["data"]["precheck_id"] + + +def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps): + """缺少 source_codes → 400 参数错误。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"}) + assert response.status_code == 400 + assert response.get_json()["success"] is False + + +def test_restore_precheck_progress(app, client, admin_headers, transfer_deps): + """GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers) + assert restored.status_code == 200 + body = restored.get_json()["data"] + assert body["summary"]["precheck_hash"] == created["precheck_hash"] + assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"} + + +def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps): + """未知 precheck → 404。""" + response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers) + assert response.status_code == 404 + + +def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps): + """执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + assert executed.status_code == 201 + run_no = executed.get_json()["data"]["run_no"] + assert run_no.startswith("RUN-") + + run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers) + assert run.status_code == 200 + result = run.get_json()["data"]["result"] + assert len(result["erp_documents"]) == 2 + assert result["exceptions"] == [] + + +def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps): + """预检未就绪时执行 → 400 领域错误,不产生 Run。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferPrecheck + + precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first() + precheck.status = "prechecking" + db.session.commit() + response = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001"]}, + ) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED" + + +def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps): + """取消缺少原因 → 400。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""}) + assert response.status_code == 400 + + +def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps): + """取消未开始项并保留成功单据。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + # 模拟执行中状态:Run 回退 executing,INV-002 尚未开始 + with app.app_context(): + from app.models import TransferInvoiceItem, TransferRun + + run = TransferRun.query.filter_by(run_no=run_no).first() + run.status = "executing" + item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first() + item.status = "ready_to_execute" + item.erp_document_no = None + db.session.commit() + response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={ + "reason": "货源调整,停止剩余", + }) + assert response.status_code == 200 + assert response.get_json()["data"]["cancelled_count"] == 1 + + +def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps): + """人工关闭缺少原因 → 400。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + db.session.commit() + item_id = item.id + response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={"reason": ""}) + assert response.status_code == 400 + + +def test_manual_close_item_success(app, client, admin_headers, transfer_deps): + """人工关闭成功 → 状态 manually_closed。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + db.session.commit() + item_id = item.id + response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={ + "reason": "线下已处理", + }) + assert response.status_code == 200 + assert response.get_json()["data"]["status"] == "manually_closed" + + +def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps): + """下载异常 Excel → 200 xlsx,且记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers) + assert response.status_code == 200 + assert response.content_type.startswith("application/vnd.openxmlformats") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXCEL_DOWNLOADED").first() + assert audit is not None + assert audit.run_no == run_no + + +def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): + """下载收料来源文件 → 200(zip),记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers) + assert response.status_code == 200 + assert response.content_type.startswith("application/zip") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first() + assert audit is not None + + +def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): + """下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers) + assert response.status_code == 200 + assert "csv" in response.content_type + assert b"INV-001" in response.data + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first() + assert audit is not None + + +def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps): + """无权限下载 → 403(越权检查)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={}, + ) + run_no = executed.get_json()["data"]["run_no"] + for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files", + f"{API_PREFIX}/runs/{run_no}/erp-inventory", + f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"): + response = client.get(path, headers=unauthorized_headers) + assert response.status_code == 403, path + + +def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps): + """前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={ + "invoice_nos": ["INV-001"], + "from_warehouse": "FAKE-TRANSIT", + "to_warehouse": "FAKE-HUB", + "quantity": "1", + }, + ) + assert executed.status_code == 201 + run_no = executed.get_json()["data"]["run_no"] + run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"] + documents = run["result"]["erp_documents"] + assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值 + assert documents[0]["to_warehouse"] == "HUB-CN01" + assert documents[0]["total_quantity"] == "1200" + + +def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps): + """待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。""" + # 预检含 1 个数量不一致(blocked)项 + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + item.result_message = "收料 1200 / ERP 1000" + db.session.commit() + + listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers) + assert listed.status_code == 200 + invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]} + assert "INV-001" in invoice_set + assert "INV-002" not in invoice_set # 可执行项不在待处理池 + assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"} + + summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers) + assert summary.status_code == 200 + assert summary.get_json()["data"]["recoverable"] >= 1 + + +def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthorized_headers, transfer_deps): + """无权限访问待处理池 → 403(越权检查)。""" + response = client.get(f"{API_PREFIX}/backlog", headers=unauthorized_headers) + assert response.status_code == 403 + + +def test_list_transfer_sources(app, client, admin_headers): + """来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。""" + response = client.get(f"{API_PREFIX}/sources", headers=admin_headers) + assert response.status_code == 200 + sources = response.get_json()["data"] + assert isinstance(sources, list) + # 测试种子来源 DSV360_AWSDU(dbs)应在列表中 + assert any(item["source_code"] == "DSV360_AWSDU" for item in sources) + for item in sources: + assert item["source_code"] + assert item["platform"] in {"dbs", "crane"} + assert item["enabled"] is True + + +def test_list_transfer_sources_forbidden(app, client, unauthorized_headers): + """无权限查看来源实例 → 403。""" + response = client.get(f"{API_PREFIX}/sources", headers=unauthorized_headers) + assert response.status_code == 403 + + +def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps): + """运营指标端点:返回 Run/明细/待处理/通知失败结构。""" + response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers) + assert response.status_code == 200 + data = response.get_json()["data"] + assert "runs" in data and "items" in data and "backlog" in data + assert "notification_failed_runs" in data["runs"] diff --git a/backend/tests/api/test_integration_connector_api.py b/backend/tests/api/test_integration_connector_api.py new file mode 100644 index 00000000..8b0ea8a2 --- /dev/null +++ b/backend/tests/api/test_integration_connector_api.py @@ -0,0 +1,290 @@ +"""tests/api/test_integration_connector_api.py + +用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、 + interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。 +依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。 +逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import User +from app.services.integration_connector.transports.base import IntegrationCallResult +from app.services.integration_connector.gateway import set_capability_gateway + +API_PREFIX = "/api/integration-connector" + + +class FakeTransport: + connector_type = "rest" + + def call(self, *, client, interface, request): + return {"found": True, "quantity": "100"} + + +class _FakeGateway: + """纯替代网关:call 直接返回,不解析绑定;transports 供连接测试。""" + + def __init__(self): + self.transports = {"rest": FakeTransport()} + + def call(self, **kwargs): + return IntegrationCallResult(status="success", data={"found": True, "quantity": None}) + + +@pytest.fixture +def admin_headers(app): + with app.app_context(): + user = db.session.query(User).filter_by(username="admin").first() + if not user: + user = User(username="admin", email="admin@example.com", role="admin", status="active") + user.set_password("admin") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def plain_headers(app): + with app.app_context(): + user = db.session.query(User).filter_by(username="plain").first() + if not user: + user = User(username="plain", email="plain@example.com", role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def fake_gateway(): + gw = _FakeGateway() + set_capability_gateway(gw) + yield gw + set_capability_gateway(None) + + +def _params(): + return {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} + + +def test_list_capabilities(app, client, admin_headers): + """GET /capabilities → 200,含 3 个在途调拨能力。""" + response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers) + assert response.status_code == 200 + names = {item["name"] for item in response.get_json()["data"]} + assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) + + +def test_create_and_list_client_instance(app, client, admin_headers): + """POST /client-instances → 201;GET 列表可查。""" + created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "ERP-T100", "name": "T100 ERP", "connector_type": "soap", "environment": "prod", + "config_json": {"endpoint": "https://t100.invalid/ws"}, + }) + assert created.status_code == 201 + assert created.get_json()["data"]["code"] == "ERP-T100" + + listed = client.get(f"{API_PREFIX}/client-instances", headers=admin_headers) + assert listed.status_code == 200 + assert any(item["code"] == "ERP-T100" for item in listed.get_json()["data"]) + + +def test_client_instance_invalid_connector_type(app, client, admin_headers): + """非法 connector_type → 400。""" + response = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "X", "name": "x", "connector_type": "ftp", + }) + assert response.status_code == 400 + + +def test_call_capability_success(app, client, admin_headers, fake_gateway): + """POST /capabilities/ → 200 success。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + headers=admin_headers, json={"params": _params(), "context": {}}) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["status"] == "success" + assert data["data"]["found"] is True + + +def test_call_capability_rejects_interface_id(app, client, admin_headers, fake_gateway): + """body 携带 interface_id → 400(禁止覆盖 Binding)。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + headers=admin_headers, json={"params": _params(), "context": {}, "interface_id": "X"}) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_ID_NOT_ALLOWED" + + +def test_call_requires_authentication(client): + """未认证 → 401。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + json={"params": _params()}) + assert response.status_code == 401 + + +def test_admin_only_forbidden(app, client, plain_headers): + """普通用户访问 Admin API → 403。""" + response = client.get(f"{API_PREFIX}/client-instances", headers=plain_headers) + assert response.status_code == 403 + + +def test_client_instance_test_connection(app, client, admin_headers, fake_gateway): + """POST /client-instances//test → 200(用注入的 Fake transport)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-A", "name": "client", "connector_type": "rest", "environment": "prod", + "config_json": {"endpoint": "https://erp.invalid"}, + }) + response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers) + assert response.status_code == 200 + assert response.get_json()["data"]["ok"] is True + + +def test_update_client_instance(app, client, admin_headers): + """PUT /client-instances/ → 200,更新 name/config/enabled。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-U", "name": "old", "connector_type": "rest", "environment": "prod", + "config_json": {"endpoint": "https://old.invalid"}, + }) + response = client.put(f"{API_PREFIX}/client-instances/CLI-U", headers=admin_headers, json={ + "name": "new", "config_json": {"endpoint": "https://new.invalid"}, "enabled": False, + }) + assert response.status_code == 200 + assert response.get_json()["data"]["name"] == "new" + assert response.get_json()["data"]["enabled"] is False + assert response.get_json()["data"]["config_json"] == {"endpoint": "https://new.invalid"} + + +def test_update_interface_definition(app, client, admin_headers): + """PUT /interface-definitions/ → 200,更新模板/回传映射/状态。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod", + "config_json": {}, + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest", + "request_spec_json": {"path": "/v1/old"}, "status": "draft", + }) + response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={ + "request_spec_json": {"path": "/v1/new"}, "response_mapping_json": {"qty": "data.quantity"}, + "status": "published", + }) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["status"] == "published" + assert data["request_spec_json"] == {"path": "/v1/new"} + + +def test_update_binding(app, client, admin_headers): + """PUT /bindings/ → 200,更新映射版本/优先级/状态。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod", + "config_json": {}, + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-B", "name": "iface", "client_instance_code": "CLI-B", "connector_type": "rest", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B", + "interface_definition_code": "IF-B", "status": "draft", + }) + binding_id = created.get_json()["data"]["id"] + response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "priority": 5, "mapping_version": 2, "status": "published", + }) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["priority"] == 5 + assert data["mapping_version"] == 2 + assert data["status"] == "published" + + +def test_update_credential_reference(app, client, admin_headers): + """PUT /credential-references/ → 200,更新 secret_ref/status,且不回显明文。""" + client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD", + }) + response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={ + "secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating", + }) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED" + assert data["status"] == "rotating" + assert "secret" not in str(data).lower() or data.get("secret") is None + + +def test_client_instance_split_columns(app, client, admin_headers): + """POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。""" + created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-COL", "name": "col client", "connector_type": "soap", "environment": "prod", + "endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 90, + "config_json": {"headers": {"X-Tenant": "A"}}, + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["endpoint"] == "https://erp.invalid/wsdl" + assert data["timeout_seconds"] == 90 + assert data["config_json"] == {"headers": {"X-Tenant": "A"}} + + updated = client.put(f"{API_PREFIX}/client-instances/CLI-COL", headers=admin_headers, json={ + "endpoint": "https://erp2.invalid/wsdl", "timeout_seconds": 120, + }) + assert updated.status_code == 200 + assert updated.get_json()["data"]["endpoint"] == "https://erp2.invalid/wsdl" + assert updated.get_json()["data"]["timeout_seconds"] == 120 + + +def test_interface_definition_split_columns(app, client, admin_headers): + """POST/PUT /interface-definitions 写 http_method/request_path 独立列。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-IF", "name": "cli", "connector_type": "rest", "environment": "prod", + "endpoint": "https://erp.invalid", + }) + created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-COL", "name": "iface", "client_instance_code": "CLI-IF", "connector_type": "rest", + "http_method": "post", "request_path": "/transfer/{invoice_no}", + "request_spec_json": {"template": {"qty": "{quantity}"}}, + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["http_method"] == "POST" + assert data["request_path"] == "/transfer/{invoice_no}" + + updated = client.put(f"{API_PREFIX}/interface-definitions/IF-COL", headers=admin_headers, json={ + "http_method": "get", "request_path": "/inventory/{invoice_no}", + }) + assert updated.status_code == 200 + assert updated.get_json()["data"]["http_method"] == "GET" + assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}" + + +def test_binding_split_columns(app, client, admin_headers): + """POST/PUT /bindings 写 context_source_code 独立列并回显。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod", + "endpoint": "https://erp.invalid", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC", + "context_source_code": "DBS-AWSBI", "status": "published", + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["context_source_code"] == "DBS-AWSBI" + + updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={ + "context_source_code": "CRANE-SZ", + }) + assert updated.status_code == 200 + assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 2fe061df..ecc150dd 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -26,38 +26,6 @@ def pytest_configure(config): ) -@pytest.fixture(autouse=True) -def _capture_legacy_order_rows_for_tests(monkeypatch): - """将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。""" - from app.models import ShippingNotice - - original_init = ShippingNotice.__init__ - legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date') - - def _init(self, **kwargs): - rows = kwargs.pop('lines_json', None) - kwargs.pop('order_lines_migration_status', None) - header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs} - original_init(self, **kwargs) - if rows is not None: - self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)] - for key, value in header_values.items(): - setattr(self, f'_test_{key}', value) - - monkeypatch.setattr(ShippingNotice, '__init__', _init) - for key in (*legacy_headers, 'lines_json'): - storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows' - monkeypatch.setattr( - ShippingNotice, - key, - property( - lambda task, name=storage: getattr(task, name, None), - lambda task, value, name=storage: setattr(task, name, value), - ), - raising=False, - ) - - def parse_api_error(body: dict) -> dict: """ 从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。 @@ -193,12 +161,17 @@ def seed_task_inventory_source( *, source_code: str = "DSV360_AWSDU", ) -> None: - """测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。""" + """测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。""" _ensure_test_task_dynamic_order(task) - from app.services.shipping_notice.inventory_source_rules import ( - compute_routing_fingerprint, - extract_routing_context, - ) + from app import db + from app.models import ShippingOrderTask + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + _ensure_test_task_dynamic_order(task) + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task + from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication from app.services.shipping_notice.inventory_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, @@ -207,35 +180,39 @@ def seed_task_inventory_source( source = get_database_inventory_source(source_code) if not source: raise ValueError(f"unknown inventory source for tests: {source_code}") - from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity - - context = extract_routing_context(task) - resolution = resolve_inventory_source_identity(source, context) - if not resolution.ok or not resolution.identity: - raise ValueError( - f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}" - ) - identity = resolution.identity - task.inventory_source_code = identity.source_code - task.inventory_connector_type = identity.connector_type - task.inventory_warehouse_id = identity.warehouse_id - task.inventory_source_status = "resolved" - task.inventory_source_method = "rule_exact" - task.inventory_source_config_version = inventory_sources_runtime_version() - task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) - if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id: + if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id: freeze_test_task_order_snapshot(task) + if not owner.order_snapshot_id: + raise ValueError('test task must have a frozen order snapshot before inventory source selection') + freeze_candidates_for_task( + owner, + adjudication=InventorySourceAdjudication( + status='resolved', + method='test_fixture', + source_code=str(source.get('source_code') or source_code).strip().upper(), + candidates=[source], + config_version=inventory_sources_runtime_version(), + ), + ) def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: """将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。""" from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - if task.order_snapshot_id: + from app import db + from app.models import ShippingOrderTask + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + _ensure_test_task_dynamic_order(task) + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + if owner.order_snapshot_id: return rows = list(getattr(task, '_test_order_rows', []) or []) if not rows: - lines = task.lines_json if isinstance(task.lines_json, list) else [] + lines = getattr(task, 'lines_json', None) + lines = lines if isinstance(lines, list) else [] rows = [ { 'part_number': row.get('part_number'), @@ -244,33 +221,19 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: } for row in lines if isinstance(row, dict) ] - task._test_order_rows = rows - _ensure_test_task_dynamic_order(task) - task.order_data_version = int(task.order_data_version or 1) - from app import db - from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction + owner._test_order_rows = rows + _ensure_test_task_dynamic_order(owner) + owner.order_data_version = int(owner.order_data_version or 1) + from app.models import ShippingOrderExtraction db.session.flush() - extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - customer = getattr(task, 'customer', None) - if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by( - extraction_id=extraction.id, role='bill_to', - ).one_or_none() is None: - db.session.add(ShippingOrderCustomerMatch( - extraction_id=extraction.id, role='bill_to', - raw_name=customer.standard_name, - normalized_name=str(customer.standard_name or '').upper(), status='confirmed', - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - identity_fingerprint='r' * 64, - identity_rule_version='test.v1', resolution_method='manual', - confirmation_reason='测试确认', confirmed_by_id=None, - )) - db.session.flush() + extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id) + customer = getattr(owner, 'customer', None) + if extraction is not None and customer is not None: + confirm_test_customer_resolution(owner, customer=customer, extraction=extraction) freeze_order_snapshot( - task, + owner, actor_id=None, - expected_order_data_version=int(task.order_data_version), + expected_order_data_version=int(owner.order_data_version), freeze_mode='auto', auto_freeze_policy={ 'test_fixture': True, @@ -284,6 +247,47 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: db.session.flush() +def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None: + """为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。""" + from app import db + from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake + + candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None + if candidate is None: + intake = ShippingOrderIntake( + intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id), + user_id=int(task.user_id), parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id, + primary_document_id=1, candidate_key=f'test-resolution-{task.id}', + candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task.candidate_id = candidate.id + if extraction is not None: + candidate.order_extraction_id = int(extraction.id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none() + if resolution is None: + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=candidate.intake_id, + resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + db.session.add(resolution) + resolution.status = 'confirmed' + resolution.confirmed_customer_id = customer.id + resolution.confirmation_method = 'test_fixture' + db.session.flush() + + def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: """将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。""" from decimal import Decimal @@ -292,16 +296,35 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, + ShippingOrderTask, User, ) from app.services.shipping_notice.order_schema import service as order_schema_service - if task.current_order_extraction_id is not None: + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + if task.id is None: + db.session.add(task) + db.session.flush() + user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first() + user_id = user_id[0] if isinstance(user_id, tuple) else user_id + owner = ShippingOrderTask( + task_no=f'OT-TEST-{task.task_no}', + user_id=int(user_id or 1), + status='ready', + current_step='customer_review', + ) + db.session.add(owner) + db.session.flush() + task.order_task_id = owner.id + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + if owner.current_order_extraction_id is not None: return rows = list(getattr(task, '_test_order_rows', []) or []) if not rows: return - if task.id is None: - db.session.add(task) + if owner.id is None: + db.session.add(owner) db.session.flush() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() if version is None: @@ -335,11 +358,11 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: required = {'part_number', 'reservation_id', 'qty'} if not required.issubset(field_ids): raise ValueError('RPA test schema lacks required order business purposes') - extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted') + extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted') db.session.add(extraction) db.session.flush() for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1) db.session.add(line) db.session.flush() for code in required: @@ -358,7 +381,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=json_value, )) - task.current_order_extraction_id = extraction.id + owner.current_order_extraction_id = extraction.id db.session.flush() @@ -425,9 +448,14 @@ def inventory_csv_with_warehouse( def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: """构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。""" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source = get_database_inventory_source(source_code) or {} return { - "source_code": str(task.inventory_source_code or ""), - "warehouse_id": str(task.inventory_warehouse_id or ""), + "source_code": str(source_code or ""), + "warehouse_id": str(source.get("fixed_warehouse_id") or ""), } @@ -464,6 +492,11 @@ def rpa_callback_payload( status: str = "success", ) -> dict: """构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。""" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source = get_database_inventory_source(source_code) or {} return { "schema_version": "shipping_inventory_rpa.v2", "callback_id": f"test-callback:{run_no}", @@ -472,8 +505,8 @@ def rpa_callback_payload( "file_path": str(file_path), "run_no": run_no, "source_run_no": run_no, - "source_code": task.inventory_source_code, - "warehouse_id": task.inventory_warehouse_id, + "source_code": source_code, + "warehouse_id": str(source.get("fixed_warehouse_id") or ""), "attempt_no": 1, "lease_token": "test-lease-token", "candidate_set_id": 1, @@ -651,6 +684,77 @@ def client(app): return app.test_client() +@pytest.fixture +def dbs_ready_file() -> dict: + """当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。""" + return { + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-001", + "file_version": "v3", + "checksum": "d" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001", + "material_name": "连接器组件", "specification": "A 型 / 24PIN", + "receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"}, + {"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001", + "material_name": "连接器组件", "specification": "A 型 / 24PIN", + "receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"}, + {"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002", + "material_name": "控制器组件", "specification": "标准型 / 48V", + "receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"}, + ], + } + + +@pytest.fixture +def crane_ready_file() -> dict: + """当日 ready 收料全量文件(CRANE-SZ),独立来源。""" + return { + "source_code": "CRANE-SZ", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-002", + "file_version": "v4", + "checksum": "c" * 64, + "status": "ready", + "rows": [ + {"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200", + "material_name": "传感器模组", "specification": "SZ-8 / IP67", + "receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"}, + ], + } + + +@pytest.fixture +def same_day_receipt_file() -> dict: + """含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。""" + return { + "source_code": "DBS-AWSSG", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-003", + "file_version": "v2", + "checksum": "s" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041", + "material_name": "连接器组件", "specification": "C 型", + "receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"}, + ], + } + + +@pytest.fixture +def transfer_db(app): + """请求 app 后返回 db 实例;表由 create_all/drop_all 随 app 生命周期隔离。""" + from app import db + + return db + + @pytest.fixture def admin_headers(): return { diff --git a/backend/tests/jobs/test_in_transit_transfer_jobs.py b/backend/tests/jobs/test_in_transit_transfer_jobs.py new file mode 100644 index 00000000..d4837588 --- /dev/null +++ b/backend/tests/jobs/test_in_transit_transfer_jobs.py @@ -0,0 +1,101 @@ +"""在途调拨预检 Job Handler 测试(L1)。 + +用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动 + precheck_service 落库更新预检状态;缺失 precheck 时报错。 +依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。 +逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。 +""" + +from __future__ import annotations + +import app.jobs.handlers # noqa: F401 —— 触发 @register_handler 注册 +import pytest + +from app import db +from app.jobs.registry import get_handler +from app.jobs.types import JobType +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +@pytest.fixture +def transfer_deps(monkeypatch, dbs_ready_file): + """注入 Fake 依赖并预置库存。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + return deps + + +def test_precheck_job_type_registered(): + """in_transit_transfer_precheck handler 必须注册于 JobType 注册表。""" + handler = get_handler(JobType.TRANSFER_PRECHECK) + assert handler is not None + + +def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps): + """handler 执行后预检状态进入 ready_to_execute,明细落库。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + handler = get_handler(JobType.TRANSFER_PRECHECK) + handler(None, {"precheck_id": summary.precheck_id}) + + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + assert precheck is not None + assert precheck.status == "ready_to_execute" + assert precheck.precheck_hash.startswith("sha256:") + assert len(precheck.items) == 2 + + +def test_precheck_job_handler_missing_precheck_raises(transfer_db): + """缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。""" + handler = get_handler(JobType.TRANSFER_PRECHECK) + with pytest.raises(RuntimeError): + handler(None, {"precheck_id": "TPC-NOT-EXIST"}) + + +def test_run_and_item_job_types_registered(): + """TRANSFER_RUN / TRANSFER_ITEM handler 必须注册。""" + assert get_handler(JobType.TRANSFER_RUN) is not None + assert get_handler(JobType.TRANSFER_ITEM) is not None + + +def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps): + """run handler 执行预检并创建成功 Run。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + handler = get_handler(JobType.TRANSFER_RUN) + handler(None, {"precheck_id": summary.precheck_id}) + + from app.models import TransferRun as RunModel + + run = db.session.query(RunModel).filter( + RunModel.status != "prechecking", + ).order_by(RunModel.id.desc()).first() + assert run is not None + assert run.status == "success" + + +def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps): + """item handler 执行单个 Invoice 写入并置 success。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + from app.services.in_transit_transfer.orchestrator import create_execution_run + + create_execution_run(precheck, deps=transfer_deps, actor_id=None) + item = db.session.query(TransferInvoiceItem).filter_by( + invoice_no="INV-001", + ).first() + handler = get_handler(JobType.TRANSFER_ITEM) + handler(None, {"item_id": item.id}) + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "success" + assert refreshed.erp_document_no + diff --git a/backend/tests/jobs/test_schedule_queue.py b/backend/tests/jobs/test_schedule_queue.py index acb22d02..61377698 100644 --- a/backend/tests/jobs/test_schedule_queue.py +++ b/backend/tests/jobs/test_schedule_queue.py @@ -1,7 +1,7 @@ """ backend/tests/jobs/test_schedule_queue.py -用途:验证排程迁出 Web 后的手动入队、Cron 扫描与 Job handler 状态闭环。 +用途:验证排程迁出 Web 后的手动入队、Cron 扫描、Job 业务身份字段与 handler 状态闭环。 依赖:通用 app fixture、models.Job/ScheduleRun/ScheduleTask、schedule.queue_service。 逻辑:只替换真正的排程执行器,不启动后台线程,断言 API/worker 之间的数据契约。 """ @@ -16,8 +16,16 @@ from app.models import Job, ScheduleRun, ScheduleTask, User from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run -def _create_task(*, due: bool = False) -> ScheduleTask: - """创建测试用户与排程;due=True 时令 next_run_at 已到期。""" +def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask: + """ + 创建测试用户与排程。 + 核心逻辑:due=True 时令 next_run_at 已到期;可指定 platform_api_path 覆盖默认 data_pipeline。 + + Args: + due: 是否立即到期,供 Cron 扫描测试。 + platform_api_path: 平台任务 key;有值时 schedule_type 改为 platform_job。 + name: 排程显示名,写入 jobs.message。 + """ suffix = str(datetime.utcnow().timestamp()).replace(".", "-") user = User( username=f"schedule-owner-{suffix}", @@ -30,8 +38,9 @@ def _create_task(*, due: bool = False) -> ScheduleTask: db.session.flush() task = ScheduleTask( schedule_no=f"SCH-TEST-{datetime.utcnow().timestamp()}", - name="schedule queue test", - schedule_type="data_pipeline", + name=name, + schedule_type="platform_job" if platform_api_path else "data_pipeline", + platform_api_path=platform_api_path, owner_user_id=user.id, cron_expr="0 3 * * *", schedule_timezone="Asia/Shanghai", @@ -57,6 +66,8 @@ def test_manual_schedule_run_creates_queued_job(app): assert job.domain == "schedule" assert job.job_type == JobType.SCHEDULE_RUN.value assert job.payload_json["schedule_run_id"] == run.id + assert job.business_ref == f"schedule_run:{run.id}:untagged" + assert job.message == "schedule queue test等待后台执行" def test_due_schedule_scan_is_idempotent(app): @@ -101,3 +112,51 @@ def test_schedule_handler_finishes_generic_job(app, monkeypatch): db.session.expire_all() assert db.session.get(ScheduleRun, run.id).status == "success" assert db.session.get(Job, job_id).status == "success" + + +def test_schedule_job_identity_uses_platform_api_path(app): + """关键断言:立账凭证等平台任务在 jobs 表用 business_ref/payload 区分,不改 job_type。""" + from app.services.schedule.queue_service import query_jobs_for_schedule_run + from app.services.schedule.scheduler_service import request_cancel_run + + with app.app_context(): + task = _create_task(platform_api_path="accounting-voucher-check", name="立账凭证检核") + run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + job = db.session.get(Job, job_id) + + assert created is True + assert job.domain == "schedule" + assert job.job_type == JobType.SCHEDULE_RUN.value + assert job.business_ref == f"schedule_run:{run.id}:accounting-voucher-check" + assert job.payload_json["platform_api_path"] == "accounting-voucher-check" + assert job.payload_json["task_name"] == "立账凭证检核" + assert job.payload_json["schedule_no"] == task.schedule_no + assert job.message == "立账凭证检核等待后台执行" + assert query_jobs_for_schedule_run(run.id).filter(Job.status == "queued").one().id == job_id + + request_cancel_run(run.id) + db.session.commit() + db.session.expire_all() + cancelled = db.session.get(Job, job_id) + assert cancelled.status == "cancelled" + + +def test_query_jobs_for_schedule_run_matches_legacy_business_ref(app): + """关键断言:取消/回收仍能命中升级前 `schedule_run:{id}` 旧格式。""" + from app.services.schedule.queue_service import query_jobs_for_schedule_run + from app.services.schedule.scheduler_service import request_cancel_run + + with app.app_context(): + task = _create_task() + run, job_id, _created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + job = db.session.get(Job, job_id) + job.business_ref = f"schedule_run:{run.id}" + db.session.commit() + + found = query_jobs_for_schedule_run(run.id).one() + assert found.id == job_id + + request_cancel_run(run.id) + db.session.commit() + db.session.expire_all() + assert db.session.get(Job, job_id).status == "cancelled" diff --git a/backend/tests/performance/test_in_transit_transfer.py b/backend/tests/performance/test_in_transit_transfer.py new file mode 100644 index 00000000..bbc11973 --- /dev/null +++ b/backend/tests/performance/test_in_transit_transfer.py @@ -0,0 +1,53 @@ +"""在途调拨性能与规模测试(Phase 4,L6 子集)。 + +用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。 +依赖:transfer_db、precheck_service、repo_fakes。 +逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。 +""" + +from __future__ import annotations + +import time + +import pytest + +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _bulk_file(count: int) -> dict: + """生成 count 行收料文件(每 Invoice 单行)。""" + rows = [] + for index in range(1, count + 1): + rows.append({ + "sheet": "Receipt", + "row_no": index, + "invoice_no": f"INV-BULK-{index:04d}", + "material_no": f"MAT-{index:04d}", + "material_name": "批量物料", + "specification": "T-100", + "receipt_date": "2026-08-05", + "receipt_quantity": "100", + "source_code": "DBS-AWSBI", + }) + return { + "source_code": "DBS-AWSBI", "business_date": "2026-08-06", + "file_no": "REC-BULK", "file_version": "v1", "checksum": "b" * 64, + "status": "ready", "rows": rows, + } + + +def test_bulk_precheck_300_invoices(transfer_db): + """300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。""" + deps, erp, _ = make_transfer_deps(_bulk_file(300)) + for index in range(1, 301): + erp.seed_inventory(f"INV-BULK-{index:04d}", "100") + + started = time.perf_counter() + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + elapsed = time.perf_counter() - started + assert summary.counts.executable_count == 300 + assert summary.counts.file_invoice_count == 300 + restored = restore_precheck(summary.precheck_id) + assert len(restored["items"]) == 300 + print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s") diff --git a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py index 08e34f3e..1f0edc0d 100644 --- a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py +++ b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py @@ -16,7 +16,8 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingNotice, + ShippingNotice, ShippingOrderTask, ShippingOrderExtraction, + ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -53,6 +54,41 @@ def _context_field() -> ShippingOrderField: return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one() +def _notice_for_customer(customer: ShippingCustomer, task_no: str) -> ShippingNotice: + """按当前事实链构造带客户引用的正式 Notice,避免写入已删除的 Notice.customer_id。""" + schema = ShippingOrderSchema( + schema_code=f'LIFECYCLE-{task_no}', + display_name='生命周期测试 Schema', + status='active', + ) + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + definition_json={'fields': []}, + checksum='lifecycle-test', + ) + task = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='completed') + db.session.add_all([version, task]) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, + schema_version_id=version.id, + input_snapshot_hash=f'{task_no:0<64}'[:64], + status='accepted', + ) + db.session.add(extraction) + db.session.flush() + task.current_order_extraction_id = extraction.id + from tests.conftest import confirm_test_customer_resolution + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + notice = ShippingNotice(task_no=task_no, order_task_id=task.id) + db.session.add(notice) + return notice + + def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app): """仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。""" with app.app_context(): @@ -74,15 +110,13 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app): @pytest.mark.parametrize('reference_kind', [ - 'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', + 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', ]) def test_business_and_audit_references_block_delete(app, reference_kind: str): """每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。""" with app.app_context(): customer = _customer() - if reference_kind == 'notice': - db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id)) - elif reference_kind == 'sequence': + if reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1')) @@ -201,7 +235,7 @@ def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str): with app.app_context(): customer = _customer('BLK') if reference_kind == 'notice': - db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id)) + _notice_for_customer(customer, 'SN-DELETE-BLOCK') elif reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': @@ -267,7 +301,7 @@ def test_delete_blocks_reference_created_after_preview(app): preview = get_customer_lifecycle_impact(customer.id) assert preview['can_delete'] is True - db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id)) + _notice_for_customer(customer, 'SN-DELETE-RACE') db.session.commit() with pytest.raises(ConflictError) as exc_info: delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None) diff --git a/backend/tests/services/admin/test_shipping_customer_merge_service.py b/backend/tests/services/admin/test_shipping_customer_merge_service.py index 0d311e3f..e2d160c7 100644 --- a/backend/tests/services/admin/test_shipping_customer_merge_service.py +++ b/backend/tests/services/admin/test_shipping_customer_merge_service.py @@ -26,7 +26,8 @@ from app.models import ( ShippingCustomerMerge, ShippingCustomerShadowResolution, ShippingOrderField, - ShippingOrderSchema, + ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, + ShippingOrderExtraction, ) from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer @@ -52,6 +53,30 @@ def _context_field() -> ShippingOrderField: return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one() +def _notice_with_customer_history(customer: ShippingCustomer) -> ShippingNotice: + """按 OT→Resolution 构造历史 Notice 客户事实。""" + schema = ShippingOrderSchema(schema_code='MERGE-HISTORY', display_name='归并历史测试', status='active') + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='merge-history', + ) + task = ShippingOrderTask(task_no='OT-SN-MERGE-HISTORY', user_id=1, status='completed') + db.session.add_all([version, task]) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='m' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + task.current_order_extraction_id = extraction.id + from tests.conftest import confirm_test_customer_resolution + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + notice = ShippingNotice(task_no='SN-MERGE-HISTORY', business_no='SRC26071601', order_task_id=task.id) + db.session.add(notice) + return notice + + def test_merge_moves_future_configuration_and_preserves_history(app): """归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。""" with app.app_context(): @@ -71,10 +96,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app): normalized_value='same@example.com', status='approved', source='manual', ), ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'), - ShippingNotice( - task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', - customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code, - ), + _notice_with_customer_history(source), ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1), ]) db.session.commit() @@ -106,9 +128,12 @@ def test_merge_moves_future_configuration_and_preserves_history(app): assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2 assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1 historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one() - assert historical_notice.customer_id == source_id + historical_task = db.session.get(ShippingOrderTask, historical_notice.order_task_id) + historical_resolution = ShippingCustomerShadowResolution.query.filter_by( + candidate_id=historical_task.candidate_id, + ).one() + assert historical_resolution.confirmed_customer_id == source_id assert historical_notice.business_no == 'SRC26071601' - assert historical_notice.customer_short_code_snapshot == 'SRC' assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1 merge = db.session.get(ShippingCustomerMerge, result['merge_id']) assert merge is not None and merge.source_customer_id_snapshot == source_id diff --git a/backend/tests/services/admin/test_shipping_customer_service.py b/backend/tests/services/admin/test_shipping_customer_service.py index cf69f314..b19a8c8a 100644 --- a/backend/tests/services/admin/test_shipping_customer_service.py +++ b/backend/tests/services/admin/test_shipping_customer_service.py @@ -13,7 +13,11 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice +from app.models import ( + ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice, + ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingOrderTask, +) from app.services.admin.shipping_customer_service import ( create_customer, create_identifier, @@ -28,6 +32,30 @@ def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None) +def _notice_for_customer(customer_id: int) -> ShippingNotice: + """按正式客户事实链创建 Notice,列表统计不得依赖已删除的 Notice.customer_id。""" + schema = ShippingOrderSchema(schema_code='CUSTOMER-LIST', display_name='客户列表测试', status='active') + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='customer-list', + ) + task = ShippingOrderTask(task_no='OT-CUSTOMER-LIST', user_id=1, status='completed') + db.session.add_all([version, task]) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + task.current_order_extraction_id = extraction.id + from tests.conftest import confirm_test_customer_resolution + confirm_test_customer_resolution(task, customer=db.session.get(ShippingCustomer, customer_id), extraction=extraction) + notice = ShippingNotice(task_no='SN-COUNT-1', order_task_id=task.id) + db.session.add(notice) + return notice + + def test_customer_short_code_is_normalized_and_unique(app): """简码统一转大写,且标准化后重复必须返回冲突。""" with app.app_context(): @@ -219,7 +247,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app): """列表返回业务单和识别证据数量,避免管理端逐客户补查。""" with app.app_context(): customer = _create_customer() - db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id'])) + _notice_for_customer(customer['id']) db.session.add(ShippingCustomerIdentifier( customer_id=customer['id'], identifier_type='name_alias', diff --git a/backend/tests/services/in_transit_transfer/__init__.py b/backend/tests/services/in_transit_transfer/__init__.py new file mode 100644 index 00000000..1cd88f8f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/__init__.py @@ -0,0 +1 @@ +"""在途仓自动调拨 Agent 领域测试包。""" diff --git a/backend/tests/services/in_transit_transfer/assertions.py b/backend/tests/services/in_transit_transfer/assertions.py new file mode 100644 index 00000000..e296add9 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/assertions.py @@ -0,0 +1,44 @@ +"""在途调拨测试断言辅助。 + +用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。 +依赖:fakes.ErpCallRecord。 +逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP + + +def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None: + """断言 ERP 调用次数(可按 Invoice 过滤)。""" + calls = erp.calls(invoice_no=invoice_no) + assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}" + + +def assert_erp_write_zero(erp: FakeERP) -> None: + """断言没有任何 ERP 写调用(fail-closed 场景通用断言)。""" + writes = erp.write_calls() + assert not writes, f"unexpected ERP write calls: {writes}" + + +def assert_call_fields(record: ErpCallRecord) -> None: + """断言单次 ERP 调用携带全部必需追踪字段。""" + assert record.operation_id + assert record.invoice_no + assert record.erp_org + assert record.from_warehouse + assert record.to_warehouse + assert isinstance(record.quantity, Decimal) + assert record.call_seq > 0 + assert record.returned_status + + +def assert_audit_complete(event: dict[str, Any]) -> None: + """断言一条审计事件字段完整(操作者、关联、前后快照、Hash)。""" + for key in ("event_type", "aggregate_type", "aggregate_id", "actor_type", "operation_id", + "request_id", "before_hash", "after_hash", "event_hash"): + assert event.get(key), f"audit event missing {key}: {event}" diff --git a/backend/tests/services/in_transit_transfer/conftest.py b/backend/tests/services/in_transit_transfer/conftest.py new file mode 100644 index 00000000..4bb86bd9 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/conftest.py @@ -0,0 +1,39 @@ +"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。 + +用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入 + (fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、 + same_day_receipt_file),并组装 FakeERP/FakeRPA/FakeWeCom。 +依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。 +逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB; + 请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。 +""" + +from __future__ import annotations + +import pytest + +from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom + + +@pytest.fixture +def fixed_clock() -> FakeClock: + """固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。""" + return FakeClock() + + +@pytest.fixture +def erp_fake() -> FakeERP: + """FakeERP:账面库存与写响应全部可注入,调用记录可断言。""" + return FakeERP() + + +@pytest.fixture +def rpa_fake() -> FakeRPA: + """FakeRPA:按来源实例独立注入失败/延迟。""" + return FakeRPA() + + +@pytest.fixture +def wecom_fake() -> FakeWeCom: + """FakeWeCom:记录投递事实,可注入附件失败。""" + return FakeWeCom() diff --git a/backend/tests/services/in_transit_transfer/factories.py b/backend/tests/services/in_transit_transfer/factories.py new file mode 100644 index 00000000..e7281579 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/factories.py @@ -0,0 +1,63 @@ +"""在途调拨领域测试的对象工厂。 + +用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。 +依赖:标准库(dataclasses / decimal)。 +逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import Any + + +@dataclass(frozen=True) +class ReceiptRow: + """单行收料文件记录(含 Sheet/行号追溯证据)。""" + + sheet: str = "Receipt" + row_no: int = 1 + invoice_no: str = "INV-001" + material_no: str = "MAT-001" + material_name: str = "连接器组件" + specification: str = "A 型 / 24PIN" + receipt_date: str = "2026-08-05" + receipt_quantity: str = "1200" + source_code: str = "DBS-AWSBI" + + def to_dict(self) -> dict[str, Any]: + """转 dict,供 parser/aggregator 输入。""" + return { + "sheet": self.sheet, + "row_no": self.row_no, + "invoice_no": self.invoice_no, + "material_no": self.material_no, + "material_name": self.material_name, + "specification": self.specification, + "receipt_date": self.receipt_date, + "receipt_quantity": self.receipt_quantity, + "source_code": self.source_code, + } + + +def make_invoice_item( + *, + invoice_no: str = "INV-001", + source_code: str = "DBS-AWSBI", + material_no: str = "MAT-001", + receipt_quantity: Decimal | str | int = "1200", + erp_quantity: Decimal | str | int | None = "1200", + receipt_date: str = "2026-08-05", +) -> dict[str, Any]: + """构造一条预检明细项(默认严格匹配、可执行)。""" + return { + "invoice_no": invoice_no, + "source_code": source_code, + "material_no": material_no, + "material_name": "连接器组件", + "specification": "A 型 / 24PIN", + "receipt_date": receipt_date, + "receipt_quantity": Decimal(str(receipt_quantity)), + "erp_quantity": None if erp_quantity is None else Decimal(str(erp_quantity)), + } diff --git a/backend/tests/services/in_transit_transfer/fakes.py b/backend/tests/services/in_transit_transfer/fakes.py new file mode 100644 index 00000000..dd070678 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/fakes.py @@ -0,0 +1,242 @@ +"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。 + +用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支, + 并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。 +依赖:标准库(dataclasses / decimal / zoneinfo)。 +逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据; + create_transfer 按注入的 scenario 返回 success / duplicate_success / + business_failed / timeout_before_commit / timeout_after_commit; + 所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、 + 来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from typing import Any +from zoneinfo import ZoneInfo + +from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError + + +class FakeClock: + """固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。""" + + def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None: + self.now_value = datetime.fromisoformat(iso) + + def now(self) -> datetime: + """返回当前固定时刻(带 Asia/Shanghai 时区)。""" + return self.now_value + + def advance(self, *, seconds: int = 0, days: int = 0) -> None: + """按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。""" + self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai")) + if seconds: + self.now_value = self.now_value + timedelta(seconds=seconds) + if days: + self.now_value = self.now_value + timedelta(days=days) + + +@dataclass(frozen=True) +class ErpCallRecord: + """FakeERP 单次调用的事实记录;测试断言优先读取该记录。""" + + operation_id: str + invoice_no: str + erp_org: str + from_warehouse: str + to_warehouse: str + quantity: Decimal + call_seq: int + returned_status: str + method: str + document_no: str | None = None + + +class FakeERP: + """可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。""" + + def __init__(self) -> None: + self.inventory: dict[str, dict[str, Any]] = {} + self.documents: dict[str, str] = {} + self.verified_posted: dict[str, bool] = {} + self.query_scenario: str = "normal" + self.write_scenario: str = "success" + # 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。 + self.write_scenarios: dict[str, str] = {} + self.call_log: list[ErpCallRecord] = [] + self._seq = 0 + + # -- 控制注入 ---------------------------------------------------------- + def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None: + """设置指定 Invoice 的账面库存。""" + self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))} + + def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None: + """预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。""" + self.documents[str(invoice_no).strip()] = document_no + self.verified_posted[str(invoice_no).strip()] = posted + + def set_query_scenario(self, scenario: str) -> None: + """normal | inventory_not_found | timeout。""" + self.query_scenario = scenario + + def set_write_scenario(self, scenario: str) -> None: + """success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。""" + self.write_scenario = scenario + + # -- ERP 能力 ---------------------------------------------------------- + def query_inventory(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """按 Invoice 返回账面库存;timeout 场景抛超时异常。""" + self._seq += 1 + key = str(invoice_no).strip() + if self.query_scenario == "timeout": + raise TimeoutError(f"query timeout operation_id={operation_id}") + if self.query_scenario == "inventory_not_found" or key not in self.inventory: + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "inventory_not_found", "query_inventory") + self.call_log.append(record) + return {"found": False, "quantity": Decimal("0")} + qty = self.inventory[key]["quantity"] + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "success", "query_inventory") + self.call_log.append(record) + return {"found": True, "quantity": qty} + + def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """原子建单/审核/过账;按注入场景返回结果并记录调用。""" + self._seq += 1 + key = str(invoice_no).strip() + scenario = self.write_scenarios.get(key, self.write_scenario) + if scenario == "timeout_before_commit": + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "timeout_before_commit", "create_transfer") + self.call_log.append(record) + raise ErpWriteTimeoutError( + "write timeout before commit", committed=False, operation_id=operation_id, + ) + if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit": + # 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。 + self.documents.setdefault(key, f"TRF-{self._seq:05d}") + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "timeout_after_commit", "create_transfer", + self.documents[key]) + self.call_log.append(record) + raise ErpWriteTimeoutError( + "write timeout after commit", committed=True, + document_no=self.documents[key], operation_id=operation_id, + ) + if scenario == "business_failed" or self.write_scenario == "business_failed": + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "business_failed", "create_transfer") + self.call_log.append(record) + return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True} + if key in self.documents: + document_no = self.documents[key] + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "duplicate_success", "create_transfer", + document_no) + self.call_log.append(record) + return { + "status": "duplicate_success", + "document_no": document_no, + "verified_posted": self.verified_posted.get(key, False), + } + document_no = f"TRF-{self._seq:05d}" + self.documents[key] = document_no + self.verified_posted[key] = True + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "success", "create_transfer", document_no) + self.call_log.append(record) + return {"status": "success", "document_no": document_no, "posted": True} + + def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """核实重复 Invoice 原单状态(已审核过账/未确认)。""" + self._seq += 1 + key = str(invoice_no).strip() + if key not in self.documents: + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "duplicate_unverified", "verify_duplicate") + self.call_log.append(record) + return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False} + document_no = self.documents[key] + posted = self.verified_posted.get(key, False) + status = "duplicate_success" if posted else "duplicate_unverified" + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, status, "verify_duplicate", document_no) + self.call_log.append(record) + return {"status": status, "document_no": document_no, "verified_posted": posted} + + # -- 断言辅助 ---------------------------------------------------------- + def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]: + """按 Invoice 过滤调用记录(默认返回全部)。""" + if invoice_no is None: + return list(self.call_log) + return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()] + + def write_calls(self) -> list[ErpCallRecord]: + """仅返回 create_transfer 调用记录(写副作用断言)。""" + return [record for record in self.call_log if record.method == "create_transfer"] + + +class FakeRPA: + """可独立按来源注入失败/延迟的收料 RPA 替身。""" + + def __init__(self) -> None: + self.triggered: list[dict[str, Any]] = [] + self.fail_on: set[str] = set() + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + """触发一次来源收料抓取并记录。""" + self.triggered.append({ + "source_code": source_code, + "business_date": business_date, + "reason": reason, + }) + if source_code in self.fail_on: + return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"} + return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} + + +class FakeWeCom: + """企业微信通知替身;记录投递事实,可注入附件失败。""" + + def __init__(self) -> None: + self.deliveries: list[dict[str, Any]] = [] + self.attach_fail = False + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """发送一次汇总通知;附件失败时返回 failed 但不抛异常。""" + if self.attach_fail and excel_path: + record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"} + self.deliveries.append(record) + return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"} + record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path} + self.deliveries.append(record) + return {"status": "success"} + + +@dataclass +class FakeAuditSink: + """审计落点替身;记录 before/after、Diff、Hash 与关联上下文。""" + + events: list[dict[str, Any]] = field(default_factory=list) + + def append(self, event: dict[str, Any]) -> None: + """追加一条审计事件 dict。""" + self.events.append(event) + + +def utc_now_iso() -> str: + """返回当前 UTC 时间的 ISO 字符串(测试断言用)。""" + return datetime.now(timezone.utc).isoformat() diff --git a/backend/tests/services/in_transit_transfer/repo_fakes.py b/backend/tests/services/in_transit_transfer/repo_fakes.py new file mode 100644 index 00000000..552731d1 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/repo_fakes.py @@ -0,0 +1,88 @@ +"""在途调拨测试的仓库/路由/依赖替身。 + +用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的 + ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。 +依赖:app.services.in_transit_transfer(仅类型)、fakes。 +逻辑:所有替身只返回测试注入的值,不触碰真实存储; + TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。 +""" + +from __future__ import annotations + +from app.services.in_transit_transfer.erp_adapter import ErpAdapter +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile +from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps +from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA + + +class FakeReceiptFileRepository: + """按 (source_code, business_date) 返回可注入 ready 文件。""" + + def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None: + self.files = files or {} + self.lookups: list[tuple[str, str]] = [] + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """记录查询并返回匹配文件。""" + self.lookups.append((source_code, business_date)) + return self.files.get((source_code, business_date)) + + +def make_ready_repo(*files: dict) -> FakeReceiptFileRepository: + """由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。""" + repository = FakeReceiptFileRepository() + for item in files: + repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile( + source_code=item["source_code"], + business_date=item["business_date"], + file_no=item["file_no"], + file_version=item["file_version"], + checksum=item["checksum"], + rows=tuple(item["rows"]), + ) + return repository + + +def make_transfer_deps( + *files: dict, + erp: FakeERP | None = None, + rpa: FakeRPA | None = None, + routes: dict[str, RouteMapping] | None = None, +) -> tuple[TransferDeps, FakeERP, FakeRPA]: + """组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。 + + Returns: + (deps, erp_fake, rpa_fake) 元组。 + """ + erp = erp or FakeERP() + rpa = rpa or FakeRPA() + deps = TransferDeps( + file_repository=make_ready_repo(*files), + rpa_trigger=rpa, + route_resolver=FakeRouteResolver(routes=routes), + erp=ErpAdapter(transport=erp, default_org="HX-CN01"), + ) + return deps, erp, rpa + + +class FakeRouteResolver: + """按来源返回固定路由(ERP 组织/拨出仓/拨入仓)。""" + + def __init__(self, routes: dict[str, RouteMapping] | None = None) -> None: + self.routes = routes if routes is not None else { + "DBS-AWSBI": RouteMapping(erp_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"), + "DBS-AWSSG": RouteMapping(erp_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"), + "CRANE-SZ": RouteMapping(erp_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"), + } + self.raised_on: set[str] = set() + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """返回来源路由;未配置来源抛 RouteNotResolvedError。""" + if source_code in self.raised_on: + raise RuntimeError("route resolution failed") + mapping = self.routes.get(source_code) + if mapping is None: + from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError + + raise RouteNotResolvedError(source_code=source_code) + return mapping diff --git a/backend/tests/services/in_transit_transfer/test_archive.py b/backend/tests/services/in_transit_transfer/test_archive.py new file mode 100644 index 00000000..6a167f32 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_archive.py @@ -0,0 +1,97 @@ +"""在途调拨 MinIO 归档与 Hash 校验测试(Phase 4,L1)。 + +用途:验证归档对象写入 MinIO(Fake 替身)并持久化索引记录, + 归档 Hash 可复算,损坏数据复核失败。 +依赖:transfer_db、archive、FakeObjectStore。 +逻辑:归档记录含 provider/bucket/key/sha256;校验重新下载并复算。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app import db +from app.models import TransferArchive, TransferAuditEvent +from app.services.in_transit_transfer.archive import ( + archive_snapshot, + restore_archive_bytes, + verify_archive_hash, +) + + +class FakeObjectStore: + """内存对象存储替身(Key → bytes)。""" + + def __init__(self) -> None: + self.objects: dict[str, bytes] = {} + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """保存对象并返回对象键。""" + self.objects[f"{bucket}/{key}"] = data + return key + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + return self.objects[f"{bucket}/{key}"] + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + self.objects.pop(f"{bucket}/{key}", None) + + +def _sample_data() -> bytes: + return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n" + + +def test_archive_snapshot_persists_index_and_audit(transfer_db): + """归档后记录 TransferArchive(含 sha256)并写入审计。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", + object_id="TPC-20260806-001", + data=data, + original_filename="erp-inventory-20260806.csv", + content_type="text/csv", + object_store=store, + bucket="hxops-transfer", + ) + assert archive.sha256 == hashlib.sha256(data).hexdigest() + assert archive.storage_provider == "minio" + assert archive.object_type == "erp_inventory_snapshot" + assert store.objects # 对象已写入存储 + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first() + assert audit is not None + assert audit.aggregate_id == "TPC-20260806-001" + + +def test_verify_archive_hash_ok_and_corruption_detected(transfer_db): + """Hash 复算一致;对象损坏 → 复核失败。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data, + original_filename="a.csv", content_type="text/csv", + object_store=store, bucket="hxops-transfer", + ) + assert verify_archive_hash(archive, object_store=store) is True + + # 篡改存储对象后复核必须失败 + key = f"{archive.storage_bucket}/{archive.storage_key}" + store.objects[key] = data + b"tampered" + assert verify_archive_hash(archive, object_store=store) is False + + +def test_restore_archive_bytes_roundtrip(transfer_db): + """归档对象可恢复为原始字节。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", object_id="OBJ-2", data=data, + original_filename="a.csv", content_type="text/csv", + object_store=store, bucket="hxops-transfer", + ) + restored = restore_archive_bytes(archive, object_store=store) + assert restored == data diff --git a/backend/tests/services/in_transit_transfer/test_audit.py b/backend/tests/services/in_transit_transfer/test_audit.py new file mode 100644 index 00000000..c32e8677 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_audit.py @@ -0,0 +1,145 @@ +"""在途调拨审计完整性测试(L0 纯单元 + 一次 DB 落库冒烟)。 + +用途:验证审计快照脱敏(Secret 不进快照/Hash)、Hash 可复算、Diff 语义正确, + 以及审计事件携带操作者、operation_id、request_id 等关联上下文。 +依赖:app.services.in_transit_transfer.audit(纯函数)+ transfer_db(模型冒烟)。 +逻辑:L0 部分不创建 Flask;模型冒烟用例请求 app fixture 验证落库字段。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.audit import ( + canonical_hash, + build_transfer_audit_event, + compute_event_hash, + sanitize_snapshot, + snapshot_diff, +) + + +@pytest.mark.pure_unit +def test_canonical_hash_is_deterministic(): + """相同快照两次计算 Hash 必须一致(键排序 + 紧凑 JSON)。""" + snapshot = {"invoice_no": "INV-001", "quantity": "1200", "org": "HX-CN01"} + assert canonical_hash(snapshot) == canonical_hash(snapshot) + + +@pytest.mark.pure_unit +def test_hash_changes_when_snapshot_changes(): + """任一字段变化 Hash 必须变化。""" + before = {"invoice_no": "INV-001", "quantity": "1200"} + after = {"invoice_no": "INV-001", "quantity": "1201"} + assert canonical_hash(before) != canonical_hash(after) + + +@pytest.mark.pure_unit +def test_hash_ignores_key_order(): + """字段顺序不影响 Hash。""" + a = {"x": 1, "y": 2} + b = {"y": 2, "x": 1} + assert canonical_hash(a) == canonical_hash(b) + + +@pytest.mark.pure_unit +def test_sanitize_snapshot_strips_secrets(): + """快照必须剔除密码/Token/密钥等敏感字段,绝不进入 Hash。""" + snapshot = { + "invoice_no": "INV-001", + "password": "P@ssw0rd", + "credential": {"api_key": "sk-xxx", "username_ciphertext": "abc"}, + "webhook_url": "https://hooks.example/secret-token", + } + clean = sanitize_snapshot(snapshot) + serialized = str(clean) + assert "P@ssw0rd" not in serialized + assert "sk-xxx" not in serialized + assert "abc" not in serialized + assert "secret-token" not in serialized + assert clean["invoice_no"] == "INV-001" + + +@pytest.mark.pure_unit +def test_snapshot_diff_reports_added_removed_changed(): + """Diff 必须区分新增/删除/修改三类变化。""" + diff = snapshot_diff( + {"invoice_no": "INV-001", "quantity": "1200", "old_key": "x"}, + {"invoice_no": "INV-001", "quantity": "1100", "new_key": "y"}, + ) + assert diff["changed"]["quantity"] == ("1200", "1100") + assert diff["removed"] == {"old_key": "x"} + assert diff["added"] == {"new_key": "y"} + + +@pytest.mark.pure_unit +def test_build_event_carries_actor_and_correlation_ids(): + """审计事件必须包含 actor、operation_id、request_id 与前后快照 Hash。""" + event = build_transfer_audit_event( + event_type="TRANSFER_CONFIRMED", + aggregate_type="transfer_item", + aggregate_id="item-1", + run_no="RUN-20260806-001", + precheck_no="TPC-20260806-001", + invoice_no="INV-001", + actor_type="user", + actor_id="u-42", + actor_role="warehouse_manager", + actor_display="李仓储", + request_id="req_001", + operation_id="op_001", + result="success", + before={"status": "prechecking"}, + after={"status": "ready_to_execute"}, + ) + assert event.actor_id == "u-42" + assert event.operation_id == "op_001" + assert event.request_id == "req_001" + assert event.run_no == "RUN-20260806-001" + assert event.before_hash and event.after_hash and event.event_hash + + +@pytest.mark.pure_unit +def test_event_hash_recomputable_from_fields(): + """审计 Hash 必须可由存储字段复算(Phase 4 Hash 校验基础)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_EXECUTED", + aggregate_type="transfer_item", + aggregate_id="item-2", + run_no="RUN-20260806-001", + invoice_no="INV-002", + actor_type="worker", + operation_id="op_002", + result="success", + after={"erp_document_no": "TRF-10001"}, + ) + assert compute_event_hash(event) == event.event_hash + + +def test_audit_event_persists_with_required_fields(transfer_db): + """DB 冒烟:审计事件可落库并回读(含 Hash 与关联字段)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_CREATED", + aggregate_type="transfer_run", + aggregate_id="RUN-20260806-001", + run_no="RUN-20260806-001", + actor_type="user", + actor_id="u-1", + operation_id="op_003", + request_id="req_003", + result="success", + after={"status": "queued"}, + ) + transfer_db.session.add(event) + transfer_db.session.commit() + + from app.models import TransferAuditEvent + + loaded = transfer_db.session.get(TransferAuditEvent, event.id) + assert loaded is not None + assert loaded.run_no == "RUN-20260806-001" + assert loaded.operation_id == "op_003" + assert loaded.event_hash == event.event_hash + # 复算一致率 100% 的落库断言 + assert compute_event_hash(loaded) == loaded.event_hash + diff --git a/backend/tests/services/in_transit_transfer/test_backlog_service.py b/backend/tests/services/in_transit_transfer/test_backlog_service.py new file mode 100644 index 00000000..eab581dc --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_backlog_service.py @@ -0,0 +1,75 @@ +"""在途调拨历史待处理池与老化测试(Phase 3,L1)。 + +用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。 +依赖:transfer_db、precheck_service、backlog_service、repo_fakes。 +逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.backlog_service import ( + aging_level_for, + backlog_summary, + list_backlog, +) +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _blocked_precheck(dbs_ready_file): + """构造含数量不一致(blocked)项的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # 1200 ≠ 1000 → blocked + erp.seed_inventory("INV-002", "1200") # executable + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return summary + + +def test_aging_level_thresholds(): + """3/5/7 天老化阈值正确。""" + assert aging_level_for(0) == "normal" + assert aging_level_for(1) == "normal" + assert aging_level_for(2) == "normal" + assert aging_level_for(3) == "warn_3d" + assert aging_level_for(5) == "escalate_5d" + assert aging_level_for(7) == "critical_7d" + assert aging_level_for(10) == "critical_7d" + + +def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file): + """待处理池收纳 blocked_recoverable,排除 success / not_matured。""" + _blocked_precheck(dbs_ready_file) + items = list_backlog() + invoice_set = {item.invoice_no for item in items} + assert "INV-001" in invoice_set + assert "INV-002" not in invoice_set + + +def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file): + """老化等级按明细更新日期计算。""" + _blocked_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.updated_at = datetime.utcnow() - timedelta(days=6) + db.session.commit() + items = list_backlog(now=datetime.utcnow()) + target = next(item_dto for item_dto in items if item_dto.invoice_no == "INV-001") + assert target.age_days == 6 + assert target.aging_level == "escalate_5d" + + +def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file): + """汇总包含可恢复/已关闭/未知计数与老化分级。""" + _blocked_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.status = "manually_closed" + item.manually_closed_reason = "线下处理" + db.session.commit() + summary = backlog_summary() + assert summary.closed_count == 1 + assert summary.recoverable_count == 0 diff --git a/backend/tests/services/in_transit_transfer/test_cancellation.py b/backend/tests/services/in_transit_transfer/test_cancellation.py new file mode 100644 index 00000000..58bd20c4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_cancellation.py @@ -0,0 +1,59 @@ +"""在途调拨请求停止(取消)测试(Phase 2,L1)。 + +用途:验证停止剩余任务只取消未开始项、已成功单据保留、原因必填。 +依赖:transfer_db、execution_service、cancellation、repo_fakes。 +逻辑:取消前快照与原因写入审计;成功后不可取消。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.cancellation import cancel_run +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(dbs_ready_file): + erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeERP"]).FakeERP() + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp) + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, summary + + +def test_cancel_requires_reason(transfer_db, dbs_ready_file): + """取消原因必填;无副作用(不创建执行 Run)。""" + deps, summary = _ready_precheck(dbs_ready_file) + with pytest.raises(ValidationError): + cancel_run(run_no="RUN-X", reason="") + # 仅存在预检关联 Run(prechecking),无执行 Run + runs = db.session.query(TransferRun).all() + assert len(runs) == 1 + assert runs[0].status != "executing" + + +def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file): + """取消只作用于未开始项;已成功单据保留。""" + deps, summary = _ready_precheck(dbs_ready_file) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() + # 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success + run.status = "executing" + item = db.session.query(TransferInvoiceItem).filter_by( + run_id=run.id, invoice_no="INV-002", + ).first() + item.status = "ready_to_execute" + item.erp_document_no = None + db.session.commit() + + result = cancel_run(run_no=outcome.run_no, reason="业务原因") + items = {i.invoice_no: i for i in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()} + assert items["INV-001"].status == "success" # 已成功单据保留 + assert items["INV-002"].status == "cancelled" # 未开始项取消 + assert result["cancelled_count"] == 1 diff --git a/backend/tests/services/in_transit_transfer/test_chat_actions.py b/backend/tests/services/in_transit_transfer/test_chat_actions.py new file mode 100644 index 00000000..620bd07f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_chat_actions.py @@ -0,0 +1,114 @@ +"""在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。 + +用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、 + stream 产出结构化卡片事件(transfer-precheck / transfer-result)。 +依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。 +逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ForbiddenError +from app.services.chat.action_registry import ACTION_AGENT_CODES, ensure_handlers_loaded, resolve_action_handler +from app.services.chat.action_schema import TurnInput +from app.services.chat.turn_context import TurnContext +from app.services.in_transit_transfer.chat_actions import ( + ACTION_TRANSFER_EXECUTE, + ACTION_TRANSFER_PRECHECK, + TransferExecuteAction, + TransferPrecheckAction, +) +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +class _Agent: + """带 agent_code 的假 Agent。""" + + def __init__(self, agent_code: str) -> None: + self.agent_code = agent_code + self.id = 1 + self.name = "test-agent" + + +class _User: + id = 99 + + +def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext: + return TurnContext( + turn_id="turn-1", + run_id="run-1", + session_id="session-1", + request_id="req-1", + user=_User(), + agent=_Agent(agent_code), + input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload), + refs={}, + ) + + +def test_transfer_actions_registered(): + """两个 transfer action 必须注册。""" + ensure_handlers_loaded() + assert "transfer." in ACTION_AGENT_CODES + assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",) + assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK + assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE + + +def test_transfer_action_agent_permission_enforced(): + """transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。""" + ensure_handlers_loaded() + ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) + with pytest.raises(ForbiddenError): + resolve_action_handler(ctx) + allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) + assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK + + +def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): + """transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, { + "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", + }))) + assert len(events) == 1 + event = events[0] + assert event.event == "message.completed" + assert event.data["message_type"] == "transfer-precheck" + payload = event.data["payload"] + assert payload["kind"] == "precheck" + assert payload["summary"]["estimated_erp_write_count"] == 2 + assert {item["invoice_no"] for item in payload["items"]} == {"INV-001", "INV-002"} + assert payload["sources"][0]["source_code"] == "DBS-AWSBI" + + +def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch): + """transfer.execute 流式产出 transfer-result 卡片(按 ERP 单号聚合)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + # 先跑预检拿 precheck_id + precheck_events = list(TransferPrecheckAction().stream(_ctx( + "in_transit_transfer", ACTION_TRANSFER_PRECHECK, + {"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"}, + ))) + precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"] + + execute_events = list(TransferExecuteAction().stream(_ctx( + "in_transit_transfer", ACTION_TRANSFER_EXECUTE, + {"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]}, + ))) + assert len(execute_events) == 1 + payload = execute_events[0].data["payload"] + assert payload["kind"] == "result" + assert payload["status"] == "success" + assert len(payload["run"]["result"]["erp_documents"]) == 2 diff --git a/backend/tests/services/in_transit_transfer/test_contracts.py b/backend/tests/services/in_transit_transfer/test_contracts.py new file mode 100644 index 00000000..18181dee --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_contracts.py @@ -0,0 +1,145 @@ +"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。 + +用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、 + ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。 +依赖:app.services.in_transit_transfer.contracts。 +逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.contracts import ( + KNOWN_TRANSFER_ERROR_CODES, + TRANSFER_PERMISSION_DENIED, + TRANSFER_PRECHECK_EXPIRED, + TRANSFER_QUANTITY_MISMATCH, + TRANSFER_RESULT_UNKNOWN, + PrecheckCountsDTO, + PrecheckInvoiceItemDTO, + PrecheckSummaryDTO, + aggregate_erp_documents, + require_known_error_code, +) + +pytestmark = pytest.mark.pure_unit + +EXPECTED_ERROR_CODES = { + "TRANSFER_PERMISSION_DENIED", + "TRANSFER_RECEIPT_NOT_MATURED", + "TRANSFER_FILE_NOT_READY", + "TRANSFER_FILE_SCHEMA_INVALID", + "TRANSFER_INVOICE_CONFLICT", + "TRANSFER_QUANTITY_MISMATCH", + "TRANSFER_ERP_INVENTORY_NOT_FOUND", + "TRANSFER_PRECHECK_EXPIRED", + "TRANSFER_CONFIRMATION_REQUIRED", + "TRANSFER_DUPLICATE_NOT_VERIFIED", + "TRANSFER_RESULT_UNKNOWN", + "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED", + "TRANSFER_CONFIG_PUBLISH_BLOCKED", + "TRANSFER_SECRET_NOT_EXPOSED", + "TRANSFER_NOTIFICATION_FAILED", +} + + +def test_error_codes_match_tdd_frozen_list(): + """TDD §7.3 冻结的 15 个错误码必须全部存在且唯一。""" + assert EXPECTED_ERROR_CODES <= KNOWN_TRANSFER_ERROR_CODES + assert len(KNOWN_TRANSFER_ERROR_CODES) == len(EXPECTED_ERROR_CODES) + + +def test_require_known_error_code_accepts_frozen_codes(): + """冻结错误码可被契约校验接受。""" + require_known_error_code(TRANSFER_QUANTITY_MISMATCH) + require_known_error_code(TRANSFER_PRECHECK_EXPIRED) + require_known_error_code(TRANSFER_RESULT_UNKNOWN) + require_known_error_code(TRANSFER_PERMISSION_DENIED) + + +def test_require_known_error_code_rejects_unknown(): + """未知错误码必须抛 ValueError。""" + with pytest.raises(ValueError): + require_known_error_code("TRANSFER_NO_SUCH_CODE") + + +def test_precheck_counts_dto_fields(): + """预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。""" + counts = PrecheckCountsDTO( + file_invoice_count=40, not_matured_count=8, prechecked_count=32, + executable_count=27, blocked_count=5, + ) + assert counts.executable_count == 27 + assert counts.not_matured_count == 8 + + +def test_precheck_summary_dto_carries_estimate_and_hash(): + """预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。""" + summary = PrecheckSummaryDTO( + precheck_id="TPC-20260806-001", + status="ready_to_execute", + business_date="2026-08-06", + eligible_receipt_date_to="2026-08-05", + expires_at="2026-08-06T09:20:00+08:00", + counts=PrecheckCountsDTO(40, 8, 32, 27, 5), + estimated_transfer_quantity="18460", + estimated_erp_write_count=27, + precheck_hash="sha256:abc", + ) + assert summary.estimated_transfer_quantity == "18460" + assert summary.estimated_erp_write_count == 27 + assert summary.precheck_hash.startswith("sha256:") + + +def test_invoice_item_dto_carries_warehouse_and_quantity_pairs(): + """预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。""" + item = PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", invoice_no="INV-001", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), + to_warehouse="HUB-CN01", to_quantity=Decimal("1200"), + result="executable", + ) + assert item.from_warehouse == "DBS-TRANSIT" + assert item.to_warehouse == "HUB-CN01" + assert item.from_quantity == item.to_quantity + + +def test_aggregate_erp_documents_groups_by_document_no(): + """结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。""" + items = [ + PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", invoice_no="INV-001", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"), + to_warehouse="HUB-CN01", to_quantity=Decimal("500"), + result="success", erp_document_no="TRF-10001", + ), + PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件", + specification="标准型 / 48V", invoice_no="INV-002", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), + to_warehouse="HUB-CN01", to_quantity=Decimal("1200"), + result="success", erp_document_no="TRF-10001", + ), + PrecheckInvoiceItemDTO( + source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组", + specification="SZ-8 / IP67", invoice_no="INV-008", + from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"), + to_warehouse="HUB-SH", to_quantity=Decimal("600"), + result="success", erp_document_no="TRF-10008", + ), + ] + documents = aggregate_erp_documents(items) + assert len(documents) == 2 + by_no = {document.document_no: document for document in documents} + first = by_no["TRF-10001"] + assert first.material_count == 2 + assert first.total_quantity == Decimal("1700") + assert first.from_warehouse == "DBS-TRANSIT" + assert first.to_warehouse == "HUB-CN01" + assert first.posting_status == "posted" + assert [line.invoice_no for line in first.lines] == ["INV-001", "INV-002"] diff --git a/backend/tests/services/in_transit_transfer/test_date_policy.py b/backend/tests/services/in_transit_transfer/test_date_policy.py new file mode 100644 index 00000000..d24e5dd5 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_date_policy.py @@ -0,0 +1,78 @@ +"""在途调拨日期成熟度策略测试(L0 纯单元)。 + +用途:验证 D+1 成熟规则、当天 not_matured、未来日期阻断与上海业务时区。 +依赖:app.services.in_transit_transfer.date_policy(纯函数)。 +逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。 +""" + +from __future__ import annotations + +from datetime import date, datetime, timezone +from zoneinfo import ZoneInfo + +import pytest + +from app.services.in_transit_transfer.date_policy import ( + business_date_now, + eligible_receipt_date_to, + maturity_status, +) + +pytestmark = pytest.mark.pure_unit + +BUSINESS_T = date(2026, 8, 6) + + +def test_same_day_receipt_is_not_matured(): + """当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。""" + assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured" + + +def test_yesterday_receipt_is_eligible(): + """昨天(T-1)收料进入预检。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "eligible" + + +def test_older_receipt_is_eligible(): + """更早收料同样可预检。""" + assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible" + + +def test_future_receipt_is_blocked(): + """未来日期收料返回结构化阻断值。""" + assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future" + + +def test_maturity_status_accepts_iso_strings(): + """字符串日期与 date 对象等价。""" + assert maturity_status("2026-08-05", "2026-08-06") == "eligible" + assert maturity_status("2026-08-06", "2026-08-06") == "not_matured" + + +def test_eligible_receipt_date_to_is_previous_day(): + """可调拨收料截止日期 = 业务日期 - 1 天。""" + assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 5) + + +def test_business_date_now_uses_shanghai_across_utc_midnight(): + """UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。""" + moment = datetime(2026, 8, 5, 17, 0, 0, tzinfo=timezone.utc) + assert business_date_now(moment) == date(2026, 8, 6) + + +def test_business_date_now_naive_moment_treated_as_utc(): + """naive 时刻按 UTC 兼容处理(与 business_numbering_service 口径一致)。""" + moment = datetime(2026, 8, 6, 0, 30, 0) + assert business_date_now(moment) == date(2026, 8, 6) + + +def test_business_date_now_defaults_to_shanghai_now(): + """无参调用返回 Asia/Shanghai 当前日期。""" + today = datetime.now(ZoneInfo("Asia/Shanghai")).date() + assert business_date_now() == today + + +def test_invalid_date_string_raises(): + """非法日期字符串必须抛 ValueError,不得静默解析。""" + with pytest.raises(ValueError): + maturity_status("2026/13/99", BUSINESS_T) diff --git a/backend/tests/services/in_transit_transfer/test_erp_adapter.py b/backend/tests/services/in_transit_transfer/test_erp_adapter.py new file mode 100644 index 00000000..bcce342d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_erp_adapter.py @@ -0,0 +1,219 @@ +"""在途调拨 ERP Adapter 查询契约测试(L0 纯单元)。 + +用途:验证 query_inventory 请求携带全部必需追踪字段(operation_id/run_no/ + attempt_no/invoice_no/erp_org/拨出仓/拨入仓/数量),并正确分类 + 有库存/无库存/超时;SOAP 传输在 WSDL 未冻结前 fail-closed。 +依赖:app.services.in_transit_transfer.erp_adapter + fakes.FakeERP。 +逻辑:Adapter 是唯一 ERP 访问边界;测试注入 FakeERP 作为 transport。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.erp_adapter import ( + ErpAdapter, + ErpNotFrozenError, + ErpQueryTimeoutError, + ErpTransport, + ErpWriteTimeoutError, + InventoryQuery, + SoapErpTransport, + TransferWriteResult, +) +from tests.services.in_transit_transfer.assertions import assert_call_fields +from tests.services.in_transit_transfer.fakes import FakeERP + +pytestmark = pytest.mark.pure_unit + + +def _adapter(erp: FakeERP) -> ErpAdapter: + return ErpAdapter(transport=erp, default_org="HX-CN01") + + +def _query_kwargs(**overrides): + kwargs = { + "operation_id": "op-001", + "run_no": "RUN-20260806-001", + "attempt_no": 1, + "invoice_no": "INV-001", + "erp_org": "HX-CN01", + "from_warehouse": "DBS-TRANSIT", + "to_warehouse": "HUB-CN01", + "quantity": Decimal("1200"), + } + kwargs.update(overrides) + return kwargs + + +def test_query_inventory_found(): + """有库存 → InventoryQuery(found=True, quantity)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + adapter = _adapter(erp) + result = adapter.query_inventory(**_query_kwargs()) + assert isinstance(result, InventoryQuery) + assert result.found is True + assert result.quantity == Decimal("1200") + + +def test_query_inventory_not_found(): + """无库存 → found=False。""" + erp = FakeERP() + adapter = _adapter(erp) + result = adapter.query_inventory(**_query_kwargs()) + assert result.found is False + assert result.quantity is None + + +def test_query_request_carries_all_trace_fields(): + """调用记录包含全部追踪字段(提示词 §五 强制字段)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + adapter = _adapter(erp) + adapter.query_inventory(**_query_kwargs()) + records = erp.calls(invoice_no="INV-001") + assert len(records) == 1 + assert_call_fields(records[0]) + assert records[0].operation_id == "op-001" + assert records[0].erp_org == "HX-CN01" + assert records[0].from_warehouse == "DBS-TRANSIT" + assert records[0].to_warehouse == "HUB-CN01" + + +def test_query_timeout_classified_retryable(): + """查询超时 → ErpQueryTimeoutError(可重试,只读路径不落未知态)。""" + erp = FakeERP() + erp.set_query_scenario("timeout") + adapter = _adapter(erp) + with pytest.raises(ErpQueryTimeoutError) as excinfo: + adapter.query_inventory(**_query_kwargs()) + assert excinfo.value.retryable is True + + +def test_soap_transport_fails_closed_before_wsdl_frozen(): + """WSDL/endpoint 未冻结 → SoapErpTransport 调用必须抛 ErpNotFrozenError。""" + transport = SoapErpTransport(config={}) + adapter = ErpAdapter(transport=transport, default_org="HX-CN01") + with pytest.raises(ErpNotFrozenError): + adapter.query_inventory(**_query_kwargs()) + + +def test_soap_transport_refuses_without_frozen_config(): + """未配置 endpoint 的传输对象直接拒绝查询。""" + transport = SoapErpTransport(config={}) + with pytest.raises(ErpNotFrozenError): + transport.query_inventory(**_query_kwargs()) + + +def test_request_payload_never_contains_credentials(): + """Adapter 请求体不得携带任何凭据字段(Secret 边界)。""" + + class RecordingTransport: + def __init__(self) -> None: + self.seen: dict | None = None + + def query_inventory(self, **kwargs): + self.seen = kwargs + return {"found": True, "quantity": Decimal("1200")} + + def create_transfer(self, **kwargs): + self.seen = kwargs + return {"status": "success", "document_no": "TRF-1", "posted": True} + + def verify_duplicate(self, **kwargs): + return {"status": "duplicate_success", "document_no": "TRF-1", "verified_posted": True} + + transport = RecordingTransport() + adapter = ErpAdapter(transport=transport, default_org="HX-CN01") + adapter.query_inventory(**_query_kwargs()) + serialized = str(transport.seen) + for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key"): + assert fragment not in serialized.lower() + + +# ---- Phase 2:create_transfer / verify_duplicate --------------------------- + +def test_create_transfer_success(): + """成功写入 → TransferWriteResult(success, document_no)。""" + erp = FakeERP() + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert isinstance(result, TransferWriteResult) + assert result.status == "success" + assert result.document_no.startswith("TRF-") + + +def test_create_transfer_duplicate_success_when_posted(): + """重复 Invoice 且原单已审核过账 → duplicate_success(含原单号)。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-00001", posted=True) + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "duplicate_success" + assert result.document_no == "TRF-00001" + assert result.verified_posted is True + + +def test_create_transfer_duplicate_unverified_blocks(): + """重复 Invoice 但无法证明原单已过账 → duplicate_unverified(阻断)。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-00001", posted=False) + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "duplicate_unverified" + assert result.document_no == "TRF-00001" + assert result.verified_posted is False + + +def test_create_transfer_business_failed(): + """明确业务失败且原子回滚 → business_failed(不得产生单据)。""" + erp = FakeERP() + erp.set_write_scenario("business_failed") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "business_failed" + assert result.error_code == "ERP_BUSINESS_REJECT" + assert result.document_no is None + + +def test_create_transfer_timeout_before_commit_is_technical_failed(): + """提交前超时(可证明未落单)→ technical_failed,非 result_unknown。""" + erp = FakeERP() + erp.set_write_scenario("timeout_before_commit") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "technical_failed" + assert result.document_no is None + + +def test_create_transfer_timeout_after_commit_is_result_unknown(): + """提交后超时(无法确认是否落单)→ result_unknown,禁止自动重试。""" + erp = FakeERP() + erp.set_write_scenario("timeout_after_commit") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "result_unknown" + assert result.document_no is not None # Fake 已知落单,但业务层视为无法确认 + + +def test_verify_duplicate_returns_original_document(): + """verify_duplicate 获取原 ERP 单号并确认已过账。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-OLD-1", posted=True) + adapter = _adapter(erp) + result = adapter.verify_duplicate(**_query_kwargs()) + assert result.status == "duplicate_success" + assert result.document_no == "TRF-OLD-1" + + +def test_verify_duplicate_unverified_when_not_posted(): + """原单未确认过账 → duplicate_unverified。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-OLD-1", posted=False) + adapter = _adapter(erp) + result = adapter.verify_duplicate(**_query_kwargs()) + assert result.status == "duplicate_unverified" + assert result.verified_posted is False diff --git a/backend/tests/services/in_transit_transfer/test_excel_export.py b/backend/tests/services/in_transit_transfer/test_excel_export.py new file mode 100644 index 00000000..1a8e09d8 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_excel_export.py @@ -0,0 +1,79 @@ +"""在途调拨七 Sheet 异常 Excel 测试(Phase 3,L1)。 + +用途:验证异常 Excel 七 Sheet 齐全、内容按状态归类、原始行追溯存在、 + Secret 明文不出现(凭据不出现在 Excel)。 +依赖:transfer_db、execution_service、excel_export、openpyxl。 +逻辑:以真实 Run 数据生成 workbook 字节并回读断言。 +""" + +from __future__ import annotations + +import io + +import pytest +from openpyxl import load_workbook + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executed_run(dbs_ready_file): + """构造含 1 成功 + 1 业务失败(未生成单据)的 Run。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + erp.write_scenarios["INV-001"] = "business_failed" + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + return outcome.run_no, deps + + +def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file): + """异常 Excel 必须包含规格定义的 7 个 Sheet。""" + run_no, _ = _executed_run(dbs_ready_file) + data = build_exceptions_workbook(run_no) + workbook = load_workbook(io.BytesIO(data)) + assert workbook.sheetnames == EXCEL_SHEET_NAMES + + +def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file): + """业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + summary_sheet = workbook["执行汇总"] + summary_text = _sheet_text(summary_sheet) + assert "INV-002" in summary_text + failed_sheet = workbook["ERP技术失败"] + failed_text = _sheet_text(failed_sheet) + assert "INV-001" in failed_text + + +def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file): + """原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + trace_sheet = workbook["原始文件追溯"] + text = _sheet_text(trace_sheet) + assert "Receipt" in text and "10" in text + + +def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file): + """Secret 明文不得出现在 Excel(密码/Token/密文片段)。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + for sheet in workbook.worksheets: + text = _sheet_text(sheet).lower() + for fragment in ("password", "secret", "token", "ciphertext", "api_key", "webhook"): + assert fragment not in text + + +def _sheet_text(sheet) -> str: + """拼接 Sheet 全部单元格文本。""" + rows = [] + for row in sheet.iter_rows(values_only=True): + rows.append(" ".join(str(cell) for cell in row if cell is not None)) + return "\n".join(rows) diff --git a/backend/tests/services/in_transit_transfer/test_execution_service.py b/backend/tests/services/in_transit_transfer/test_execution_service.py new file mode 100644 index 00000000..a3ce8e25 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_execution_service.py @@ -0,0 +1,224 @@ +"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。 + +用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、 + Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、 + 选择子集执行、重复点击防重与按 ERP 单号投影最终结果。 +依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。 +逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.contracts import ( + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_PRECHECK_EXPIRED, +) +from app.services.in_transit_transfer.execution_service import execute_precheck, get_run +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.fakes import FakeERP +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple: + """创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。""" + deps, erp_fake, _ = make_transfer_deps(*files, erp=erp) + source_codes = source_codes or [files[0]["source_code"]] + summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps) + return deps, erp_fake, summary + + +def _erp_with_stock(dbs_ready_file, *seeds) -> FakeERP: + """按 Invoice 预置账面库存的 FakeERP。""" + erp = FakeERP() + for invoice_no, quantity in seeds: + erp.seed_inventory(invoice_no, quantity) + return erp + + +def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]: + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + return { + item.invoice_no: item + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + } + + +def test_execute_happy_path(transfer_db, dbs_ready_file): + """两个可执行 Invoice → Run 成功,按 ERP 单号投影两张单据,Attempt 落库。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "success" + assert outcome.run_no.startswith("RUN-") + assert len(outcome.result.erp_documents) == 2 + assert outcome.result.exceptions == () + + items = _load_items(outcome.run_no) + assert all(item.status == "success" for item in items.values()) + assert all(item.erp_document_no for item in items.values()) + run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() + attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter( + TransferInvoiceItem.run_id == run.id, + ).all() + assert len([a for a in attempts if a.kind == "erp_write"]) == 2 + + +def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file): + """重复 Invoice(原单已过账)→ item duplicate_success + 原单号。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.seed_document("INV-002", "TRF-OLD-002", posted=True) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "success" + items = _load_items(outcome.run_no) + assert items["INV-002"].status == "duplicate_success" + assert items["INV-002"].erp_document_no == "TRF-OLD-002" + # 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用 + assert len(erp.write_calls()) == 2 + + +def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file): + """单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.write_scenarios["INV-001"] = "business_failed" + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "partial_failed" + items = _load_items(outcome.run_no) + assert items["INV-001"].status == "blocked_recoverable" + assert items["INV-002"].status == "success" + # 异常项进入结果页"未生成单据"区 + assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions) + + +def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file): + """result_unknown:状态终态、每 Invoice 写调用仅 1 次。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.set_write_scenario("timeout_after_commit") + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "partial_failed" + items = _load_items(outcome.run_no) + assert all(item.status == "result_unknown" for item in items.values()) + # 禁止自动重试:每个 Invoice 写调用恰 1 次 + assert len(erp.write_calls()) == 2 + + +def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file): + """预检未就绪(prechecking)→ 拒绝执行,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + precheck.status = "prechecking" + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED + assert erp.write_calls() == [] + + +def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file): + """确认过期(超过 10 分钟)→ 拒绝执行,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + precheck.expires_at = datetime.utcnow() - timedelta(seconds=1) + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED + assert erp.write_calls() == [] + + +def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file): + """预检快照(数量)变化 → fail-closed,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first() + item.receipt_quantity = "999" + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED + assert erp.write_calls() == [] + + +def test_execute_selected_subset_only(transfer_db, dbs_ready_file): + """仅选择 INV-001 → 只写入该 Invoice。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck( + precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"], + ) + assert outcome.status == "success" + assert len(outcome.result.erp_documents) == 1 + assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"] + + +def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file): + """勾选当天收料项 → 拒绝,ERP 写入为 0。""" + deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"]) + with pytest.raises(AppError): + execute_precheck( + precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"], + ) + assert erp_fake.write_calls() == [] + + +def test_execute_double_click_rejected(transfer_db, dbs_ready_file): + """重复点击执行 → 第二次 409,不创建重复 Run。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + first = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.http_status == 409 + # 只存在一个执行 Run(其余为预检关联 Run) + execution_runs = db.session.query(TransferRun).filter( + TransferRun.status != "prechecking", + ).count() + assert execution_runs == 1 + assert first.run_no + + +def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file): + """写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + erp.seed_inventory("INV-001", "999") # 预检后库存变化 + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + items = _load_items(outcome.run_no) + assert items["INV-001"].status == "blocked_recoverable" + assert items["INV-002"].status == "success" + assert [record.invoice_no for record in erp.write_calls()] == ["INV-002"] + + +def test_get_run_restores_document_projection(transfer_db, dbs_ready_file): + """GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.write_scenarios["INV-001"] = "business_failed" + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + + restored = get_run(outcome.run_no) + assert restored["run_no"] == outcome.run_no + assert len(restored["result"]["erp_documents"]) == 1 + assert any(exc["invoice_no"] == "INV-001" for exc in restored["result"]["exceptions"]) diff --git a/backend/tests/services/in_transit_transfer/test_file_preparation.py b/backend/tests/services/in_transit_transfer/test_file_preparation.py new file mode 100644 index 00000000..a48becc4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_file_preparation.py @@ -0,0 +1,128 @@ +"""在途调拨文件 Ready 复用与 RPA 触发测试(L0 纯单元)。 + +用途:验证当日 ready 文件可复用(不触发 RPA)、缺文件时同一来源只触发一次 + RPA、存在活动 Source Job 时绑定已有任务、触发失败 fail-closed。 +依赖:app.services.in_transit_transfer.file_preparation + fakes。 +逻辑:仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.file_preparation import ( + FilePreparationResult, + ReadyReceiptFile, + ReceiptFileRepository, + ensure_receipt_file_ready, +) +from tests.services.in_transit_transfer.fakes import FakeRPA +from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository + + +def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile: + return ReadyReceiptFile( + source_code=source_code, + business_date=business_date, + file_no=f"REC-{source_code}-001", + file_version="v3", + checksum="d" * 64, + rows=(), + ) + + +def test_ready_file_reused_without_rpa_trigger(): + """当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。""" + repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()}) + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "file_ready" + assert result.file is not None + assert rpa.triggered == [] + + +def test_missing_file_triggers_rpa_once(): + """缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "waiting_rpa_callback" + assert result.file is None + assert len(rpa.triggered) == 1 + assert rpa.triggered[0]["source_code"] == "DBS-AWSBI" + + +def test_active_source_job_binds_existing_task_no_new_trigger(): + """存在活动 Source Job → 绑定已有任务,不重复触发 RPA。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", + ) + assert result.stage == "waiting_rpa_callback" + assert rpa.triggered == [] + + +def test_concurrent_requests_share_one_trigger(): + """并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + for _ in range(3): + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", + ) + assert result.stage == "waiting_rpa_callback" + assert rpa.triggered == [] + + +def test_without_active_key_each_call_triggers_once(): + """无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert len(rpa.triggered) == 2 + + +def test_rpa_trigger_failure_is_fail_closed(): + """RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + rpa.fail_on.add("DBS-AWSBI") + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "failed" + assert result.error_code == "RPA_TRIGGER_FAILED" + + +def test_dbs_and_crane_sources_isolated(): + """DBS 失败不影响 Crane 的文件准备(来源隔离)。""" + repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")}) + rpa = FakeRPA() + rpa.fail_on.add("DBS-AWSBI") + dbs_result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + crane_result = ensure_receipt_file_ready( + source_code="CRANE-SZ", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert dbs_result.stage == "failed" + assert crane_result.stage == "file_ready" diff --git a/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py new file mode 100644 index 00000000..106624aa --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py @@ -0,0 +1,117 @@ +"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。 + +用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯; + 同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。 +依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。 +逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import parse_receipt_rows +from app.services.in_transit_transfer.invoice_aggregator import ( + AggregatedInvoice, + InvoiceConflictError, + aggregate_invoices, +) + +pytestmark = pytest.mark.pure_unit + + +def _parsed(rows: list[dict]) -> list: + """将原始行解析为 ParsedReceiptRow。""" + return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) + + +def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件", + specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05", + quantity: str = "500", row_no: int = 10, sheet: str = "Receipt") -> dict: + return { + "sheet": sheet, "row_no": row_no, "invoice_no": invoice_no, + "material_no": material_no, "material_name": material_name, + "specification": specification, "receipt_date": receipt_date, + "receipt_quantity": quantity, "source_code": "DBS-AWSBI", + } + + +def test_same_invoice_multiple_rows_sum_quantity(): + """同 Invoice 同料号两行 → 数量相加,保留两条原始行。""" + rows = [ + _row("INV-001", quantity="500", row_no=10), + _row("INV-001", quantity="700", row_no=11), + ] + invoices = aggregate_invoices(_parsed(rows)) + assert len(invoices) == 1 + invoice = invoices[0] + assert invoice.invoice_no == "INV-001" + assert invoice.receipt_quantity == Decimal("1200") + assert len(invoice.raw_lines) == 2 + assert invoice.raw_lines[0].row_no == 10 + assert invoice.raw_lines[1].row_no == 11 + assert all(line.sheet == "Receipt" for line in invoice.raw_lines) + + +def test_distinct_invoices_stay_separate_and_sorted(): + """不同 Invoice 保持独立并按 Invoice 排序。""" + rows = [ + _row("INV-002", row_no=5), + _row("INV-001", row_no=3), + ] + invoices = aggregate_invoices(_parsed(rows)) + assert [item.invoice_no for item in invoices] == ["INV-001", "INV-002"] + + +def test_multiple_material_no_conflict_blocks_invoice(): + """同一 Invoice 出现多个料号 → 整单阻断。""" + rows = [ + _row("INV-001", material_no="MAT-001", row_no=1), + _row("INV-001", material_no="MAT-002", row_no=2), + ] + with pytest.raises(InvoiceConflictError) as excinfo: + aggregate_invoices(_parsed(rows)) + assert excinfo.value.details.get("invoice_no") == "INV-001" + + +def test_multiple_receipt_date_conflict_blocks_invoice(): + """同一 Invoice 出现多个收料日期 → 整单阻断。""" + rows = [ + _row("INV-001", receipt_date="2026-08-05", row_no=1), + _row("INV-001", receipt_date="2026-08-06", row_no=2), + ] + with pytest.raises(InvoiceConflictError): + aggregate_invoices(_parsed(rows)) + + +def test_aggregated_invoice_keeps_material_identity(): + """汇总结果保留料号、品名、规格与收料日期。""" + rows = [ + _row("INV-001", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1), + _row("INV-001", material_no="MAT-001", row_no=2), + ] + invoices = aggregate_invoices(_parsed(rows)) + invoice = invoices[0] + assert invoice.material_no == "MAT-001" + assert invoice.material_name == "连接器组件" + assert invoice.specification == "A 型 / 24PIN" + assert invoice.receipt_date == date(2026, 8, 5) + + +def test_raw_lines_carry_file_version(): + """原始行追溯包含文件版本(决策 11:来源证据)。""" + rows = [ + _row("INV-001", row_no=10), + _row("INV-001", row_no=11), + ] + invoices = aggregate_invoices(_parsed(rows), file_version="v3") + assert all(line.file_version == "v3" for line in invoices[0].raw_lines) + + +def test_empty_input_returns_empty(): + """空行输入返回空汇总。""" + assert aggregate_invoices([]) == [] diff --git a/backend/tests/services/in_transit_transfer/test_metrics.py b/backend/tests/services/in_transit_transfer/test_metrics.py new file mode 100644 index 00000000..00616c1f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_metrics.py @@ -0,0 +1,46 @@ +"""在途调拨运营指标测试(Phase 4,L1)。 + +用途:验证指标聚合(Run/明细状态分布、待处理老化、通知失败数)正确。 +依赖:transfer_db、precheck/execution/metrics、repo_fakes。 +逻辑:指标由数据库现状投影,便于上线观察板使用。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.metrics import collect_metrics +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file): + """指标包含 Run 状态分布与明细状态分布。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + + metrics = collect_metrics() + assert metrics["runs"]["success"] >= 1 + assert metrics["items"]["success"] >= 2 + + +def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready_file): + """指标含待处理老化与通知失败计数。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # mismatch → blocked + erp.seed_inventory("INV-002", "1200") + create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.updated_at = item.updated_at # 保持默认年龄 + db.session.commit() + + metrics = collect_metrics() + assert metrics["backlog"]["recoverable"] == 1 + assert "aging" in metrics["backlog"] + assert "notification_failed_runs" in metrics["runs"] diff --git a/backend/tests/services/in_transit_transfer/test_migration_execution.py b/backend/tests/services/in_transit_transfer/test_migration_execution.py new file mode 100644 index 00000000..2f1f4e5a --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_execution.py @@ -0,0 +1,72 @@ +"""在途调拨迁移升级/回滚执行测试。 + +用途:在 SQLite 内存库上真实执行 it1a2b3c4d5e 迁移的 upgrade 与 downgrade, + 证明建表/回滚 DDL 可运行(Phase 0 验收:迁移 upgrade/downgrade 成功)。 +依赖:Alembic Operations、SQLAlchemy SQLite、it1a2b3c4d5e 迁移模块。 +逻辑:upgrade 后断言 7 张调拨表存在;downgrade 后断言全部删除。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +pytestmark = pytest.mark.pure_unit + +EXPECTED_TABLES = { + "transfer_runs", + "transfer_source_jobs", + "transfer_prechecks", + "transfer_invoice_items", + "transfer_attempts", + "transfer_audit_events", + "transfer_archives", +} + + +def _load_migration(): + """加载新增调拨迁移模块。""" + path = Path(__file__).parents[3] / "migrations" / "versions" / "it1a2b3c4d5e_add_in_transit_transfer.py" + spec = importlib.util.spec_from_file_location("in_transit_transfer_migration", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_transfer_migration_upgrade_creates_all_tables(): + """升级必须创建全部 7 张调拨表。""" + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert EXPECTED_TABLES <= tables, f"missing tables: {EXPECTED_TABLES - tables}" + + # 关键约束抽查:Invoice 唯一键与状态检查约束落库 + columns = {item["name"] for item in sa.inspect(connection).get_columns("transfer_invoice_items")} + assert "invoice_no" in columns and "raw_lines_json" in columns + + +def test_transfer_migration_downgrade_drops_all_tables(): + """回滚必须删除全部调拨表且不残留索引。""" + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + migration.downgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert not (EXPECTED_TABLES & tables), f"leftover tables: {EXPECTED_TABLES & tables}" diff --git a/backend/tests/services/in_transit_transfer/test_migration_revision.py b/backend/tests/services/in_transit_transfer/test_migration_revision.py new file mode 100644 index 00000000..f9a64ba0 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_revision.py @@ -0,0 +1,59 @@ +"""在途调拨数据库迁移链测试。 + +用途:验证新增迁移 revision 存在、正确挂在当前 head 之后,且不产生分叉。 +依赖:alembic 迁移脚本目录(backend/migrations/versions)。 +逻辑:读取版本文件头部 revision/down_revision 文本,不加载 Flask 应用。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" +# 在途调拨迁移根:ic1a2b3c4d5f(Add integration connector)挂在其上。 +NEW_REVISION = "ic1a2b3c4d5f" +# ic1a2b3c4d5f 的直接 parent(仍是线性链,未被分叉)。 +CURRENT_HEAD = "it1a2b3c4d5e" + +pytestmark = pytest.mark.pure_unit + + +def _migration_file(revision: str) -> Path: + """按 revision 定位迁移文件(命名规则 _.py)。""" + for path in MIGRATIONS_DIR.glob("*.py"): + if path.name.startswith(f"{revision}_"): + return path + raise AssertionError(f"migration file for revision {revision} not found") + + +def test_migration_file_exists_and_chains_from_head(): + """新增迁移必须存在并挂在当前 head(it1a2b3c4d5e)之后。""" + path = _migration_file(NEW_REVISION) + text = path.read_text(encoding="utf-8") + assert f"revision = '{NEW_REVISION}'" in text or f'revision = "{NEW_REVISION}"' in text + assert f"down_revision = '{CURRENT_HEAD}'" in text or f'down_revision = "{CURRENT_HEAD}"' in text + + +def test_new_revision_is_not_referenced_as_parent(): + """没有歧义分叉:ic1a2b3c4d5f 后续仅允许线性延伸(if1b2c3d4e5g),禁止其余分支。""" + allowed_children = {"if1b2c3d4e5g"} + for path in MIGRATIONS_DIR.glob("*.py"): + if path.name.startswith(f"{NEW_REVISION}_"): + continue + text = path.read_text(encoding="utf-8", errors="ignore") + match = re.search(rf"down_revision\s*=\s*['\"]{NEW_REVISION}['\"]", text) + if match and path.name.split("_", 1)[0] not in allowed_children: + raise AssertionError(f"unexpected branch from {NEW_REVISION}: {path.name}") + + +def test_head_still_linear_after_new_migration(): + """当前 in_transit_transfer 链保持线性:it1a2b3c4d5e 之后仅 ic1a2b3c4d5f 一个后继。""" + allowed_children = {"ic1a2b3c4d5f"} + for path in MIGRATIONS_DIR.glob("*.py"): + text = path.read_text(encoding="utf-8", errors="ignore") + match = re.search(rf"down_revision\s*=\s*['\"]{CURRENT_HEAD}['\"]", text) + if match and path.name.split("_", 1)[0] not in allowed_children: + raise AssertionError(f"unexpected branch from head: {path.name}") diff --git a/backend/tests/services/in_transit_transfer/test_models.py b/backend/tests/services/in_transit_transfer/test_models.py new file mode 100644 index 00000000..304def6f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_models.py @@ -0,0 +1,213 @@ +"""在途调拨领域模型测试(L1,使用 SQLite 内存库)。 + +用途:验证 7 个核心模型可建表、可持久化回读,唯一约束与状态约束生效, + 审计事件只追加不可改删。 +依赖:app fixture(create_all 自动建表)、models/in_transit_transfer。 +逻辑:全部走真实 ORM 落库,不 Mock 模型本身。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy.exc import IntegrityError +from sqlalchemy import inspect + +from app import db +from app.models import ( + TransferArchive, + TransferAttempt, + TransferAuditEvent, + TransferInvoiceItem, + TransferPrecheck, + TransferRun, + TransferSourceJob, +) + +TRANSFER_TABLES = { + "transfer_runs", "transfer_source_jobs", "transfer_prechecks", + "transfer_invoice_items", "transfer_attempts", "transfer_audit_events", + "transfer_archives", +} + + +def test_create_all_includes_transfer_tables(app): + """create_all 必须包含全部调拨表(迁移与测试建表同源)。""" + inspector = inspect(db.engine) + tables = set(inspector.get_table_names()) + assert TRANSFER_TABLES <= tables + + +def test_run_source_job_item_attempt_roundtrip(transfer_db): + """Run → SourceJob → InvoiceItem → Attempt 全链路持久化回读。""" + run = TransferRun( + run_no="RUN-20260806-001", + trigger_type="manual", + business_date="2026-08-06", + status="prechecking", + source_codes_json=["DBS-AWSBI"], + counts_json={"file_invoice_count": 3, "executable_count": 2}, + ) + transfer_db.session.add(run) + transfer_db.session.flush() + + source_job = TransferSourceJob( + run_id=run.id, + source_code="DBS-AWSBI", + source_config_version=5, + status="checking_file", + ) + precheck = TransferPrecheck( + precheck_no="TPC-20260806-001", + run_id=run.id, + business_date="2026-08-06", + status="ready_to_execute", + scope_json={"source_codes": ["DBS-AWSBI"]}, + counts_json={"executable_count": 1}, + precheck_hash="sha256:test", + ) + item = TransferInvoiceItem( + precheck=precheck, + run_id=run.id, + source_code="DBS-AWSBI", + invoice_no="INV-001", + material_no="MAT-001", + material_name="连接器组件", + specification="A 型 / 24PIN", + receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", + to_warehouse="HUB-CN01", + receipt_quantity="1200", + erp_quantity="1200", + status="ready_to_execute", + raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}], + ) + transfer_db.session.add_all([source_job, precheck, item]) + transfer_db.session.flush() + + attempt = TransferAttempt( + item_id=item.id, + attempt_no=1, + kind="erp_query", + status="success", + request_snapshot_json={"invoice_no": "INV-001"}, + operation_id="op_001", + ) + transfer_db.session.add(attempt) + transfer_db.session.commit() + + loaded_run = transfer_db.session.get(TransferRun, run.id) + assert loaded_run.run_no == "RUN-20260806-001" + loaded_item = transfer_db.session.get(TransferInvoiceItem, item.id) + assert loaded_item.raw_lines_json[0]["row_no"] == 10 + loaded_attempt = transfer_db.session.get(TransferAttempt, attempt.id) + assert loaded_attempt.operation_id == "op_001" + assert loaded_attempt.attempt_no == 1 + + +def test_invoice_item_unique_per_precheck(transfer_db): + """同一预检内同一 Invoice 只能出现一次(防重复建单底座)。""" + precheck = TransferPrecheck( + precheck_no="TPC-20260806-002", + business_date="2026-08-06", + status="prechecking", + scope_json={}, + counts_json={}, + precheck_hash="sha256:test2", + ) + transfer_db.session.add(precheck) + transfer_db.session.flush() + + def _item(invoice_no: str) -> TransferInvoiceItem: + return TransferInvoiceItem( + precheck_id=precheck.id, + source_code="DBS-AWSBI", + invoice_no=invoice_no, + material_no="MAT-001", + receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", + to_warehouse="HUB-CN01", + receipt_quantity="1200", + erp_quantity="1200", + status="ready_to_execute", + raw_lines_json=[], + ) + + transfer_db.session.add(_item("INV-001")) + transfer_db.session.flush() + transfer_db.session.add(_item("INV-001")) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_run_no_unique(transfer_db): + """run_no 唯一约束生效。""" + transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual", + business_date="2026-08-06", status="queued")) + transfer_db.session.flush() + transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual", + business_date="2026-08-06", status="queued")) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_invoice_item_status_check_constraint(transfer_db): + """Invoice 状态必须属于冻结枚举(数据库级门禁兜底)。""" + precheck = TransferPrecheck( + precheck_no="TPC-20260806-003", business_date="2026-08-06", + status="prechecking", scope_json={}, counts_json={}, precheck_hash="x", + ) + transfer_db.session.add(precheck) + transfer_db.session.flush() + transfer_db.session.add(TransferInvoiceItem( + precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999", + material_no="MAT-9", receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + receipt_quantity="1", erp_quantity="1", + status="no_such_status", raw_lines_json=[], + )) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_audit_event_is_append_only(transfer_db): + """审计事件禁止更新与删除(ORM 门禁)。""" + event = TransferAuditEvent( + event_type="TRANSFER_READ", aggregate_type="transfer_run", + aggregate_id="RUN-X", run_no="RUN-X", actor_type="user", + actor_id="u-1", result="success", + ) + transfer_db.session.add(event) + transfer_db.session.commit() + + event.result = "failure" + with pytest.raises(Exception): + transfer_db.session.commit() + transfer_db.session.rollback() + + transfer_db.session.delete(event) + with pytest.raises(Exception): + transfer_db.session.commit() + transfer_db.session.rollback() + + +def test_archive_roundtrip(transfer_db): + """归档记录保存对象路径与 Hash,供 Phase 4 MinIO 归档校验。""" + archive = TransferArchive( + archive_no="ARC-20260806-001", + object_type="erp_inventory_snapshot", + object_id="TPC-20260806-001", + storage_provider="minio", + storage_bucket="hxops-transfer", + storage_key="transfer/20260806/snapshot.xlsx", + original_filename="erp-inventory-20260806.xlsx", + file_size=1024, + sha256="a" * 64, + ) + transfer_db.session.add(archive) + transfer_db.session.commit() + loaded = transfer_db.session.get(TransferArchive, archive.id) + assert loaded.sha256 == "a" * 64 + assert loaded.object_type == "erp_inventory_snapshot" diff --git a/backend/tests/services/in_transit_transfer/test_movement_contract.py b/backend/tests/services/in_transit_transfer/test_movement_contract.py new file mode 100644 index 00000000..bb41c93d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_contract.py @@ -0,0 +1,62 @@ +"""在途调拨通用异动表领域字段契约测试(L0 纯单元)。 + +用途:锁定调拨定死的 10 个通用异动/移动字段契约(领域定死、不配置化), + 以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedReceiptRow。 +依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。 +逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ParsedReceiptRow +from app.services.in_transit_transfer.movement_contract import ( + MOVEMENT_FIELDS, + MovementField, + movement_match_key, + movement_quantity_field, + movement_identity_fields, +) + +pytestmark = pytest.mark.pure_unit + + +def test_movement_fields_contract_is_frozen_and_complete(): + """领域字段契约定死:10 个字段、名称唯一、不可变。""" + assert len(MOVEMENT_FIELDS) == 10 + codes = {field.code for field in MOVEMENT_FIELDS} + assert codes == { + "doc_no", "line_no", "in_out_flag", "material_code", "material_name", + "warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", + } + + +def test_movement_field_metadata(): + """每个字段携带中文名、类型与使用标记。""" + by_code = {field.code: field for field in MOVEMENT_FIELDS} + doc_no = by_code["doc_no"] + assert doc_no.label == "单号" + assert doc_no.value_type == "text" + assert doc_no.is_identity is True + assert by_code["quantity"].value_type == "decimal" + assert by_code["movement_date"].value_type == "date" + + +def test_match_key_is_doc_no(): + """调拨幂等/汇总键为 doc_no(单号)。""" + assert movement_match_key() == "doc_no" + + +def test_quantity_field_is_quantity(): + """数量严格匹配字段为 quantity。""" + assert movement_quantity_field() == "quantity" + + +def test_identity_fields_cover_match_predicates(): + """幂等/匹配字段集至少含 doc_no + material_code + movement_date。""" + ids = movement_identity_fields() + assert {"doc_no", "material_code", "movement_date"} <= ids diff --git a/backend/tests/services/in_transit_transfer/test_movement_file_repository.py b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py new file mode 100644 index 00000000..b6bdd0d1 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py @@ -0,0 +1,81 @@ +"""真实异动文件仓库的 xlsx→领域行解析测试。 + +用途:验证 _extract_movement_rows 用 movement field_mapping(定死领域字段 code→表头别名) + 把 xlsx 原始列映射为领域行 dict,供 parse_movement_rows 校验。纯单元(内存 xlsx)。 +依赖:openpyxl(构造内存工作簿)、movement_file_repository._extract_movement_rows。 +""" + +from __future__ import annotations + +from io import BytesIO + +import pytest +from openpyxl import Workbook + +from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows + +pytestmark = pytest.mark.pure_unit + +MOVEMENT_MAPPING = { + 'doc_no': '单据编号', + 'line_no': '项次', + 'in_out_flag': '进出库别', + 'material_code': '料号', + 'material_name': '品名', + 'warehouse_code': '仓库', + 'storage_code': '储位', + 'lot_no': '批号', + 'quantity': '数量', + 'movement_date': '异动日期', +} + + +def _movement_xlsx_bytes() -> bytes: + """构造含表头 + 两行数据的 xlsx。""" + wb = Workbook() + ws = wb.active + ws.title = 'Movement' + ws.append(['单据编号', '项次', '进出库别', '料号', '品名', '仓库', '储位', '批号', '数量', '异动日期']) + ws.append(['MOV-001', 1, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 500, '2026-08-05']) + ws.append(['MOV-001', 2, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 300, '2026-08-05']) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_extract_movement_rows_maps_columns_to_domain_fields(): + """表头别名被映射为定死领域字段 code 的行字段。""" + rows = _extract_movement_rows( + _movement_xlsx_bytes(), + field_mapping=MOVEMENT_MAPPING, + sheet_name='Movement', + header_row_index=1, + ) + assert len(rows) == 2 + first = rows[0] + assert first['doc_no'] == 'MOV-001' + assert first['material_code'] == 'MAT-001' + assert first['quantity'] == 500 + assert str(first['movement_date']) == '2026-08-05' + second = rows[1] + assert second['quantity'] == 300 + + +def test_extract_movement_rows_skips_missing_alias_columns(): + """表头缺某别名列时,对应领域字段不输出(行仍保留其余字段)。""" + wb = Workbook() + ws = wb.active + ws.title = 'S' + ws.append(['单据编号', '料号', '数量']) + ws.append(['MOV-9', 'MAT-9', 120]) + buf = BytesIO() + wb.save(buf) + rows = _extract_movement_rows( + buf.getvalue(), + field_mapping={'doc_no': '单据编号', 'material_code': '料号', 'quantity': '数量', 'movement_date': '异动日期'}, + sheet_name='S', + header_row_index=1, + ) + assert rows[0]['doc_no'] == 'MOV-9' + assert rows[0]['quantity'] == 120 + assert 'movement_date' not in rows[0] diff --git a/backend/tests/services/in_transit_transfer/test_movement_parser.py b/backend/tests/services/in_transit_transfer/test_movement_parser.py new file mode 100644 index 00000000..8feadf30 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_parser.py @@ -0,0 +1,94 @@ +"""通用异动表解析器测试(L0 纯单元)。 + +用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到 + 调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity, + receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。 +依赖:app.services.in_transit_transfer.movement_parser(纯函数)。 +逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_movement_rows, +) + +pytestmark = pytest.mark.pure_unit + +VALID_MOVEMENT_ROW = { + "sheet": "Movement", + "row_no": 7, + "doc_no": "MOV-001", + "line_no": 1, + "in_out_flag": "I", + "material_code": "MAT-001", + "material_name": "连接器组件", + "warehouse_code": "DBS-TRANSIT", + "storage_code": "A-01", + "lot_no": "LOT-9", + "quantity": "500", + "movement_date": "2026-08-05", + "source_code": "DBS-AWSBI", +} + + +def _rows(**overrides) -> list[dict]: + base = dict(VALID_MOVEMENT_ROW) + base.update(overrides) + return [base] + + +def test_valid_movement_row_maps_to_parsed_rows(): + """通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。""" + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows()) + assert len(parsed) == 1 + row = parsed[0] + assert isinstance(row, ParsedReceiptRow) + assert row.invoice_no == "MOV-001" + assert row.material_no == "MAT-001" + assert row.material_name == "连接器组件" + assert row.receipt_date == date(2026, 8, 5) + assert row.receipt_quantity == Decimal("500") + assert row.sheet == "Movement" + assert row.row_no == 7 + + +def test_missing_doc_no_rejected(): + """单号缺失阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="")) + + +def test_invalid_quantity_rejected(): + """非数字数量阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc")) + + +def test_invalid_movement_date_rejected(): + """非法异动日期阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99")) + + +def test_source_identity_mismatch_rejected(): + """来源身份漂移阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) + + +def test_optional_fields_default_empty(): + """品名/规格/仓库/储位/批号可缺省为空展示。""" + parsed = parse_movement_rows( + source_code="DBS-AWSBI", + rows=_rows(material_name="", warehouse_code="", storage_code="", lot_no=""), + ) + row = parsed[0] + assert row.material_name == "" diff --git a/backend/tests/services/in_transit_transfer/test_notification.py b/backend/tests/services/in_transit_transfer/test_notification.py new file mode 100644 index 00000000..74c1e7e2 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_notification.py @@ -0,0 +1,54 @@ +"""在途调拨企微汇总通知测试(Phase 3,L1)。 + +用途:验证每个非空 Run 恰好一条汇总通知、空数据不通知、 + 通知失败不改变 ERP 结果(run.status 保持)。 +依赖:transfer_db、execution_service、notification、fakes.FakeWeCom。 +逻辑:通知状态独立于 ERP 业务状态;失败记录 notification_failed。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.notification import notify_run_summary +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.fakes import FakeWeCom +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executed_run(dbs_ready_file): + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + return outcome.run_no + + +def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file): + """非空 Run → 恰好一条汇总通知;重复调用幂等。""" + run_no = _executed_run(dbs_ready_file) + wecom = FakeWeCom() + first = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1", "u-2"]) + assert first["notification_status"] == "success" + second = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"]) + assert second["delivered"] is False # 已投递,幂等跳过 + assert len(wecom.deliveries) == 1 + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + assert run.notification_status == "success" + assert run.status == "success" # ERP 结果不受影响 + + +def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file): + """通知失败 → notification_status=failed,run.status 保持 success。""" + run_no = _executed_run(dbs_ready_file) + wecom = FakeWeCom() + wecom.attach_fail = True + result = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"], excel_path="x.xlsx") + assert result["notification_status"] == "failed" + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + assert run.notification_status == "failed" + assert run.status == "success" # 关键:通知失败不改变 ERP 业务结果 diff --git a/backend/tests/services/in_transit_transfer/test_orchestrator.py b/backend/tests/services/in_transit_transfer/test_orchestrator.py new file mode 100644 index 00000000..e8403c79 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_orchestrator.py @@ -0,0 +1,69 @@ +"""在途调拨 Run 编排测试(Phase 2,L1)。 + +用途:验证执行 Run 创建(执行中状态、关联预检与明细)、终态收尾与 + 重复创建防护。 +依赖:transfer_db、precheck_service、orchestrator、repo_fakes。 +逻辑:编排层复用 execution_service 落库流程,本文件聚焦 Run 生命周期辅助函数。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ConflictError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.status import TransferRunStatus +from tests.services.in_transit_transfer.fakes import FakeERP +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(dbs_ready_file): + """创建已预检 precheck 并返回 (deps, summary)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp) + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, summary + + +def test_create_execution_run_links_items_and_sets_executing(transfer_db, dbs_ready_file): + """create_execution_run 创建 executing Run 并关联可执行明细。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + + run = create_execution_run(precheck, deps=deps, actor_id=None) + assert run.status == TransferRunStatus.EXECUTING.value + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + assert len(items) == 2 + assert all(item.status == "executing" for item in items) + + +def test_finalize_run_sets_terminal_status(transfer_db, dbs_ready_file): + """finalize_run 按明细终态汇总 Run 状态。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + run = create_execution_run(precheck, deps=deps, actor_id=None) + + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + for item in items: + item.status = "success" + finalize_run(run, items) + assert run.status == TransferRunStatus.SUCCESS.value + + for item in items: + item.status = "blocked_recoverable" + finalize_run(run, items) + assert run.status == TransferRunStatus.PARTIAL_FAILED.value + + +def test_create_execution_run_rejects_duplicate(transfer_db, dbs_ready_file): + """已确认的 precheck 不允许重复创建执行 Run。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + create_execution_run(precheck, deps=deps, actor_id=None) + with pytest.raises(ConflictError): + create_execution_run(precheck, deps=deps, actor_id=None) diff --git a/backend/tests/services/in_transit_transfer/test_precheck_service.py b/backend/tests/services/in_transit_transfer/test_precheck_service.py new file mode 100644 index 00000000..fa0f66d6 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_precheck_service.py @@ -0,0 +1,164 @@ +"""在途调拨预检服务测试(L1,SQLite 内存库)。 + +用途:验证 D+1 过滤(当天收料 ERP 调用=0)、严格数量匹配、来源隔离、 + 预检快照 Hash 稳定、缺文件等待与进度恢复。 +依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。 +逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck), + 外部依赖注入 Fake 替身。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.erp_adapter import ErpAdapter +from app.services.in_transit_transfer.precheck_service import ( + TransferDeps, + create_precheck, + restore_precheck, + run_precheck, +) +from tests.services.in_transit_transfer.assertions import assert_erp_calls +from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA +from tests.services.in_transit_transfer.repo_fakes import FakeRouteResolver, make_ready_repo, make_transfer_deps + + +def _deps(*files: dict, erp: FakeERP | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeERP, FakeRPA]: + """构造注入 Fake 依赖的 TransferDeps。""" + return make_transfer_deps(*files, erp=erp, rpa=rpa) + + +def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file): + """两个来源全部严格匹配 → executable_count 正确,无阻断。""" + deps, erp, _ = _deps(dbs_ready_file, crane_ready_file) + for invoice, qty in [("INV-001", "1200"), ("INV-002", "1200"), ("INV-008", "600")]: + erp.seed_inventory(invoice, qty) + + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + summary = result.summary + assert summary.counts.executable_count == 3 + assert summary.counts.not_matured_count == 0 + assert summary.counts.blocked_count == 0 + assert summary.status == "ready_to_execute" + assert summary.precheck_hash.startswith("sha256:") + assert summary.estimated_erp_write_count == 3 + # 明细 DTO 决策 6/7:拨出/拨入仓库与数量对 + items = {item.invoice_no: item for item in result.items} + assert items["INV-001"].from_warehouse == "DBS-TRANSIT" + assert items["INV-001"].to_warehouse == "HUB-CN01" + assert items["INV-001"].from_quantity == items["INV-001"].to_quantity == 1200 + assert len(items["INV-001"].raw_lines) == 2 # 多行汇总保留原始行 + + +def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file): + """当天收料 → not_matured,ERP 调用次数为 0。""" + deps, erp, _ = _deps(same_day_receipt_file) + result = run_precheck( + source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, + ) + assert result.summary.counts.not_matured_count == 1 + assert result.summary.counts.executable_count == 0 + assert result.summary.estimated_erp_write_count == 0 + assert_erp_calls(erp, 0) + + +def test_quantity_mismatch_blocked_no_write(dbs_ready_file): + """收料 1200 vs ERP 1000 → blocked_recoverable;无任何写调用。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") + erp.seed_inventory("INV-002", "1200") + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + items = {item.invoice_no: item for item in result.items} + assert items["INV-001"].result == "blocked_quantity_mismatch" + assert items["INV-002"].result == "executable" + assert result.summary.counts.blocked_count == 1 + assert erp.write_calls() == [] + + +def test_erp_inventory_not_found_blocked(dbs_ready_file): + """ERP 无库存 → blocked_inventory_not_found。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") # INV-002 无库存 + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + items = {item.invoice_no: item for item in result.items} + assert items["INV-002"].result == "blocked_inventory_not_found" + + +def test_missing_file_waits_without_erp(): + """缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。""" + deps, erp, _ = _deps() + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result.sources[0].stage == "waiting_rpa_callback" + assert result.summary.status == "file_pending" + assert_erp_calls(erp, 0) + + +def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file): + """DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。""" + deps, erp, rpa = _deps(crane_ready_file) + rpa.fail_on.add("DBS-AWSBI") + erp.seed_inventory("INV-008", "600") + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + by_source = {stage.source_code: stage for stage in result.sources} + assert by_source["DBS-AWSBI"].stage == "failed" + assert by_source["CRANE-SZ"].stage == "file_ready" + items = {item.invoice_no: item for item in result.items} + assert items["INV-008"].result == "executable" + + +def test_snapshot_hash_is_stable(dbs_ready_file): + """相同输入两次预检 → 预检 Hash 一致(可审计复算)。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + assert first.summary.precheck_hash == second.summary.precheck_hash + + +def test_create_and_restore_precheck(transfer_db, dbs_ready_file): + """create_precheck 落库后 restore_precheck 可完整恢复进度与明细。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert summary.precheck_id.startswith("TPC-") + restored = restore_precheck(summary.precheck_id) + assert restored["summary"].precheck_hash == summary.precheck_hash + assert restored["summary"].status == summary.status + restored_items = {item.invoice_no: item for item in restored["items"]} + assert set(restored_items) == {"INV-001", "INV-002"} + assert restored_items["INV-001"].result == "executable" + # 落库数量与 DTO 一致(Decimal 文本持久化) + assert str(restored_items["INV-001"].to_quantity) == "1200" + + +def test_route_not_resolved_marks_source_failed(dbs_ready_file): + """来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。""" + erp = FakeERP() + rpa = FakeRPA() + deps = TransferDeps( + file_repository=make_ready_repo(dbs_ready_file), + rpa_trigger=rpa, + route_resolver=FakeRouteResolver(routes={}), + erp=ErpAdapter(transport=erp, default_org="HX-CN01"), + ) + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + by_source = {stage.source_code: stage for stage in result.sources} + assert by_source["DBS-AWSBI"].stage == "failed" + assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断 diff --git a/backend/tests/services/in_transit_transfer/test_quantity_match.py b/backend/tests/services/in_transit_transfer/test_quantity_match.py new file mode 100644 index 00000000..7a72de3d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_quantity_match.py @@ -0,0 +1,76 @@ +"""在途调拨严格数量门禁测试(L0 纯单元)。 + +用途:验证"收料数量 == ERP 账面库存 才可执行",大于/小于/缺失均阻断, + 且不允许 0、负数、非数字与隐式截断。 +依赖:app.services.in_transit_transfer.quantity。 +逻辑:数量比较全部基于 Decimal 精确语义,杜绝浮点误差。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.quantity import ( + QuantityValidationError, + classify_quantity_match, + strict_quantities_equal, + validate_receipt_quantity, +) + +pytestmark = pytest.mark.pure_unit + + +def test_equal_quantities_are_executable(): + """收料数量等于账面库存 → executable。""" + assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable" + + +def test_erp_greater_than_receipt_is_blocked(): + """ERP 库存大于收料数量 → 阻断(不允许部分调拨)。""" + assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch" + + +def test_erp_less_than_receipt_is_blocked(): + """ERP 库存小于收料数量 → 阻断。""" + assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch" + + +def test_erp_missing_is_blocked(): + """ERP 无库存(None)→ 阻断,与数量不一致分开归类。""" + assert classify_quantity_match(Decimal("1200"), None) == "blocked_inventory_not_found" + + +def test_decimal_scale_equality_is_exact(): + """1.0 与 1.00 数量相等(Decimal 精确语义)。""" + assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00")) + + +def test_zero_receipt_quantity_rejected(): + """收料数量为 0 非法。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity(Decimal("0")) + + +def test_negative_receipt_quantity_rejected(): + """收料数量为负数非法。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity(Decimal("-5")) + + +def test_non_numeric_quantity_rejected(): + """非数字数量非法(解析层不得静默截断)。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity("abc") + + +def test_string_numeric_quantity_normalized(): + """字符串数字归一化为 Decimal 后参与严格比较。""" + assert validate_receipt_quantity("1200") == Decimal("1200") + assert strict_quantities_equal("1200", Decimal("1200")) + + +def test_fractional_partial_quantity_rejected_by_policy(): + """策略层不允许部分数量:1.5 与 1 不相等即阻断。""" + assert classify_quantity_match(Decimal("1.5"), Decimal("1")) == "blocked_quantity_mismatch" diff --git a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py new file mode 100644 index 00000000..3f8a05c2 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py @@ -0,0 +1,96 @@ +"""tests/services/in_transit_transfer/test_query_inventory_gateway.py + +用途:验证调拨 query_inventory 经 CapabilityGateway 接线(首个消费者)—— + 网关被调用、成熟过滤(当天收料不查)、fail-closed(无绑定来源失败但不阻断)。 +依赖:run_precheck、CapabilityErpAdapter、repo_fakes.make_transfer_deps、transports.base。 +逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。 +""" + +from __future__ import annotations + +from dataclasses import replace +from decimal import Decimal + +from app.core.errors import AppError +from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter +from app.services.in_transit_transfer.precheck_service import run_precheck +from app.services.integration_connector.errors import BindingNotFoundError +from app.services.integration_connector.transports.base import IntegrationCallResult +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +class FakeGateway: + """按 Invoice 返回库存结果的替代网关,并记录调用。""" + + def __init__(self, inventory: dict[str, str] | None = None, *, fail: bool = False) -> None: + self.inventory = inventory or {} + self.fail = fail + self.calls: list[tuple[str, dict, dict]] = [] + + def call(self, *, capability, context, params, operation_id, idempotency_key=None, environment=None, transports=None): + self.calls.append((capability, context, params)) + if self.fail: + raise BindingNotFoundError(capability=capability) + invoice_no = params["invoice_no"] + qty = self.inventory.get(invoice_no) + if qty is None: + return IntegrationCallResult(status="success", data={"found": False}) + return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal(qty)}) + + +def _cap_deps(file, gw): + deps, _, _ = make_transfer_deps(file) + return replace(deps, erp=CapabilityErpAdapter(gateway=gw)) + + +def test_query_inventory_routed_through_gateway(app, dbs_ready_file): + """成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。""" + gw = FakeGateway(inventory={"INV-001": "1200", "INV-002": "1200"}) + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", + deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T", + ) + # 网关被调用,且携带 query_inventory 能力名 + assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls) + # INV-001 汇总 1200 == ERP 1200 → executable + item = next(i for i in result.items if i.invoice_no == "INV-001") + assert item.result == "executable" + assert item.from_quantity == Decimal("1200") + + +def test_not_matured_not_queried(app, same_day_receipt_file): + """当天收料(not_matured)不查 ERP——网关零调用。""" + gw = FakeGateway(inventory={}) + result = run_precheck( + source_codes=["DBS-AWSSG"], business_date="2026-08-06", + deps=_cap_deps(same_day_receipt_file, gw), run_no="RUN-T", + ) + assert gw.calls == [] + assert result.items[0].result == "not_matured" + + +def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file): + """无绑定的来源(网关抛错)标记来源失败,不阻断整个预检。""" + class _SplitGateway: + """按 Invoice 区分失败来源:DBS(INV-001/002)失败,CRANE(INV-008)成功。""" + + def __init__(self): + self.calls = [] + + def call(self, **kwargs): + self.calls.append(kwargs) + invoice = kwargs["params"]["invoice_no"] + if invoice in {"INV-001", "INV-002"}: + raise BindingNotFoundError(capability="in_transit_transfer.query_inventory") + return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal("600")}) + + deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file) + deps = replace(deps, erp=CapabilityErpAdapter(gateway=_SplitGateway())) + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", + deps=deps, run_no="RUN-T", + ) + dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI") + assert dbs_source.stage == "failed" + # CRANE 正常执行 → 出可执行项 + assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py new file mode 100644 index 00000000..a09636fa --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py @@ -0,0 +1,123 @@ +"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。 + +用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与 + 来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。 +依赖:app.services.in_transit_transfer.file_parser(纯函数)。 +逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_receipt_rows, +) + +pytestmark = pytest.mark.pure_unit + +VALID_ROW = { + "sheet": "Receipt", + "row_no": 10, + "invoice_no": "INV-001", + "material_no": "MAT-001", + "material_name": "连接器组件", + "specification": "A 型 / 24PIN", + "receipt_date": "2026-08-05", + "receipt_quantity": "500", + "source_code": "DBS-AWSBI", +} + + +def _rows(**overrides) -> list[dict]: + """以 VALID_ROW 为基底覆盖字段构造测试行。""" + base = dict(VALID_ROW) + base.update(overrides) + return [base] + + +def test_valid_rows_parse(): + """合法行解析出全部字段(数量 Decimal、日期 date)。""" + parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows()) + assert len(parsed) == 1 + row = parsed[0] + assert isinstance(row, ParsedReceiptRow) + assert row.invoice_no == "INV-001" + assert row.material_no == "MAT-001" + assert row.material_name == "连接器组件" + assert row.specification == "A 型 / 24PIN" + assert row.receipt_date == date(2026, 8, 5) + assert row.receipt_quantity == Decimal("500") + assert row.sheet == "Receipt" + assert row.row_no == 10 + + +def test_missing_invoice_no_rejected(): + """Invoice No 缺失必须整行阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_no="")) + + +def test_missing_material_no_rejected(): + """料号缺失必须整行阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no="")) + + +def test_invalid_quantity_rejected(): + """非数字数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc")) + + +def test_zero_quantity_rejected(): + """0 数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0")) + + +def test_negative_quantity_rejected(): + """负数数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5")) + + +def test_invalid_date_rejected(): + """非法日期必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99")) + + +def test_source_identity_mismatch_rejected(): + """行内来源与任务来源不一致(Callback 身份漂移)必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) + + +def test_missing_sheet_or_row_no_rejected(): + """Sheet/原始行号缺失无法追溯,必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0)) + + +def test_material_name_and_specification_optional(): + """品名/规格允许为空(后续由明细 DTO 展示空值)。""" + parsed = parse_receipt_rows( + source_code="DBS-AWSBI", + rows=_rows(material_name="", specification=""), + ) + assert parsed[0].material_name == "" + assert parsed[0].specification == "" + + +def test_error_carries_row_details(): + """错误细节必须携带行号与原因,供页面定位。""" + with pytest.raises(ReceiptFileSchemaError) as excinfo: + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc")) + details = excinfo.value.details + assert any(str(item.get("row_no")) == "77" for item in details.get("rows", [])) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py new file mode 100644 index 00000000..7b7e4fbc --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -0,0 +1,72 @@ +"""真实收料 RPA 触发服务测试。 + +用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者; + 配置/来源/触发目录缺失时 fail-closed(ok=False)。 +依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、 + 既有测试种子(ShippingRpaProfile/ShippingInventorySource)。 +逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。 +""" + +from __future__ import annotations + +import pytest + +from app.models import ShippingInventorySource, ShippingReceiptReportConfig +from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa + + +@pytest.fixture +def receipt_source(): + """复用种子来源并为其创建收料配置。""" + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + assert source is not None + config = ShippingReceiptReportConfig( + inventory_source_id=source.id, enabled=True, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], warehouse_ids_json=[], + ) + from app import db + + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): + """来源有效 → 写入 trigger 并返回 callback_id / trigger_path。""" + calls = {} + + def fake_writer(run_no, units, payload=None): + calls['run_no'] = run_no + calls['units'] = units + calls['payload'] = payload or {} + return f'/tmp/trigger/{run_no}.json' + + result = trigger_receipt_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + reason='transfer_retry_receipt', writer=fake_writer, + ) + assert result['ok'] is True + assert result['callback_id'] + assert result['trigger_path'].endswith('.json') + assert calls['units'][0]['source_code'] == 'DSV360_AWSDU' + assert calls['units'][0]['credential_envelope'] + assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1' + + +def test_trigger_receipt_rpa_disabled_source_fails_closed(app): + """来源停用 → ok=False,不写 trigger。""" + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source.enabled = False + from app import db + + db.session.commit() + result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING' + + +def test_trigger_receipt_rpa_missing_config_fails_closed(app): + """来源启用但无收料配置 → ok=False。""" + result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False diff --git a/backend/tests/services/in_transit_transfer/test_recovery_service.py b/backend/tests/services/in_transit_transfer/test_recovery_service.py new file mode 100644 index 00000000..b76df3c4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_recovery_service.py @@ -0,0 +1,76 @@ +"""在途调拨每日恢复(待处理池自动复核)测试(Phase 3,L1)。 + +用途:验证历史可恢复项下一排程重新预检并创建新 Attempt; + result_unknown / manually_closed / success 不自动写入。 +依赖:transfer_db、precheck_service、recovery_service、repo_fakes。 +逻辑:恢复 = 重新预检(仅查询/匹配),不写 ERP;每次恢复新 Attempt。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.recovery_service import run_daily_recovery +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _mixed_precheck(dbs_ready_file): + """构造 1 个数量不一致 + 1 个可执行的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # mismatch → blocked + erp.seed_inventory("INV-002", "1200") # executable + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, erp, summary + + +def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file): + """ERP 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + assert item.status == "blocked_recoverable" + old_attempt_no = item.attempt_no + + erp.seed_inventory("INV-001", "1200") + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.recovered_count == 1 + assert outcome.attempts_created == 1 + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "ready_to_execute" + assert refreshed.attempt_no == old_attempt_no + 1 + attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all() + assert len(attempts) == 1 and attempts[0].kind == "erp_query" + # 恢复仅预检,不写 ERP + assert erp.write_calls() == [] + + +def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file): + """result_unknown 不自动恢复,也不产生 ERP 调用。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.status = "result_unknown" + db.session.commit() + + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.skipped_result_unknown == 1 + assert outcome.recovered_count == 0 + assert erp.write_calls() == [] + + +def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file): + """manually_closed / success 永久排除,不生成 Attempt。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + blocked.status = "manually_closed" + blocked.manually_closed_reason = "线下处理" + success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-002").first() + success.status = "success" + db.session.commit() + + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.skipped_manually_closed == 1 + assert outcome.recovered_count == 0 + assert outcome.attempts_created == 0 diff --git a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py new file mode 100644 index 00000000..8b93f2ac --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py @@ -0,0 +1,117 @@ +"""在途调拨人工重试与人工关闭测试(Phase 3,L1)。 + +用途:验证人工重试只创建新 Attempt(重新查询 ERP,不重新抓 RPA、不写 ERP), + result_unknown 拒绝重试;人工关闭原因必填且永久排除。 +依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。 +逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.manual_close_service import manual_close_item +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.retry_service import retry_item +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _mismatch_precheck(dbs_ready_file): + """构造 INV-001 数量不一致的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, erp, summary + + +def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem: + return db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first() + + +def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file): + """ERP 修正后重试 → 新 Attempt,状态进入 ready_to_execute。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + assert item.status == "blocked_recoverable" + old_attempt_count = item.attempt_no + + erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存 + result = retry_item(item_id=item.id, deps=deps) + assert result["status"] == "ready_to_execute" + assert result["attempt_no"] == old_attempt_count + 1 + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "ready_to_execute" + assert refreshed.attempt_no == old_attempt_count + 1 + attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all() + assert len(attempts) == 1 + assert attempts[0].kind == "erp_query" + # 重试不写 ERP + assert erp.write_calls() == [] + + +def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file): + """重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + old = item.attempt_no + result = retry_item(item_id=item.id, deps=deps) + assert result["status"] == "blocked_recoverable" + assert result["attempt_no"] == old + 1 + + +def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file): + """result_unknown 只读:拒绝重试(禁止猜测性二次写入)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + item.status = "result_unknown" + item.result_code = "result_unknown" + db.session.commit() + with pytest.raises(ValidationError): + retry_item(item_id=item.id, deps=deps) + assert erp.write_calls() == [] + + +def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file): + """Run 创建后禁止重新抓取 RPA(文件冻结)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + with pytest.raises(ValidationError): + retry_item(item_id=item.id, deps=deps, kind="rpa_refetch") + + +def test_manual_close_requires_reason(transfer_db, dbs_ready_file): + """人工关闭原因必填。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + with pytest.raises(ValidationError): + manual_close_item(item_id=item.id, reason="") + + +def test_manual_close_marks_terminal(transfer_db, dbs_ready_file): + """人工关闭 → manually_closed(永久排除,后续排程不再处理)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + result = manual_close_item(item_id=item.id, reason="货代确认无需调拨") + assert result["status"] == "manually_closed" + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "manually_closed" + assert refreshed.manually_closed_reason == "货代确认无需调拨" + # 关闭后不再进入可恢复池(自动排程不再处理) + from app.services.in_transit_transfer.backlog_service import backlog_summary + + assert backlog_summary().recoverable_count == 0 + + +def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file): + """result_unknown 只读:禁止人工关闭(需按 SOP 核实)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + item.status = "result_unknown" + db.session.commit() + with pytest.raises(ValidationError): + manual_close_item(item_id=item.id, reason="尝试关闭未知项") diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py new file mode 100644 index 00000000..fa4df666 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -0,0 +1,46 @@ +"""在途调拨排程注册与执行测试(Phase 3)。 + +用途:验证 08:00 收料文件 / 09:00 自动调拨 platform job 已注册(含参数契约), + handler 返回标准 ScheduleExecuteResult(7 元组)。 +依赖:schedule.job_registry、schedule 两个 in_transit job 模块。 +逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。 +""" + +from __future__ import annotations + +import pytest + +from app.services.schedule.job_registry import get_platform_job, list_platform_jobs + + +def test_receipt_file_job_registered_with_schedule_defaults(): + """08:00 收料文件 job 注册且含 source_codes 参数契约。""" + job = get_platform_job("in-transit-receipt-file") + assert job is not None + assert job.enabled + keys = {field.get("key") for field in job.params_schema} + assert "source_codes" in keys + + +def test_transfer_job_registered_with_schedule_defaults(): + """09:00 自动调拨 job 注册且含并发/恢复参数契约。""" + job = get_platform_job("in-transit-transfer") + assert job is not None + assert job.enabled + keys = {field.get("key") for field in job.params_schema} + assert {"source_codes", "recover_history"} <= keys + + +def test_schedule_handlers_return_seven_tuple(): + """两个排程 handler 返回标准 ScheduleExecuteResult(7 元组)。""" + from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule + from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule + + for handler in (run_in_transit_receipt_file_schedule, run_in_transit_transfer_schedule): + assert callable(handler) + + +def test_jobs_visible_in_platform_list(): + """platform job 列表包含两个调拨排程。""" + keys = {job.key for job in list_platform_jobs()} + assert {"in-transit-receipt-file", "in-transit-transfer"} <= keys diff --git a/backend/tests/services/in_transit_transfer/test_source_file_status.py b/backend/tests/services/in_transit_transfer/test_source_file_status.py new file mode 100644 index 00000000..b319fa7b --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_source_file_status.py @@ -0,0 +1,88 @@ +"""来源收料文件状态投影服务测试。 + +用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile), + 按来源投影 ready/fetching/failed/none。调拨不维护独立抓取状态表。 +依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 +逻辑:有文件→ready;有进行中单元→fetching;最新单元失败终态→failed;否则→none。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + +SOURCE_CODE = 'DSV360_AWSDU' + + +@pytest.fixture +def receipt_unit_run(): + """构造一条收料执行单元(含排程/来源上下文)。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + + source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one() + task = ScheduleTask( + schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job', + owner_user_id=1, cron_expr='0 8 * * *', job_params={}, + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback') + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001', + status='awaiting_rpa', config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + return unit + + +def test_no_file_and_no_unit_is_none(app): + """无文件且无执行单元 → none(待触发)。""" + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'none' + assert status['has_ready_file'] is False + + +def test_running_unit_is_fetching(app, receipt_unit_run): + """有进行中执行单元 → fetching。""" + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'fetching' + assert status['has_ready_file'] is False + + +def test_failed_latest_unit_is_failed(app, receipt_unit_run): + """最新单元为失败终态且无文件 → failed。""" + from app import db + from app.models import ShippingReceiptRpaUnitRun + + receipt_unit_run.status = 'failed' + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'failed' + + +def test_report_file_is_ready(app, receipt_unit_run): + """有收料归档文件 → ready,且带 file_no/sha256。""" + from app import db + from app.models import ShippingReceiptReportFile + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'receipt workbook').hexdigest() + db.session.add(ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx', + file_size=16, sha256=digest, + )) + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'ready' + assert status['has_ready_file'] is True + assert status['file_no'] == 'receipt.xlsx' + assert status['file_sha256'] == digest diff --git a/backend/tests/services/in_transit_transfer/test_source_job_service.py b/backend/tests/services/in_transit_transfer/test_source_job_service.py new file mode 100644 index 00000000..833adcbd --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_source_job_service.py @@ -0,0 +1,88 @@ +"""来源级状态服务测试。 + +用途:验证 create_source_job / advance_source_job / source_jobs_for_run 的职责—— + 一次 run 内每来源一条 job((run, source) 唯一),状态推进统一集中在此服务。 +依赖:app(SQLite)、models(TransferRun/TransferSourceJob)、source_job_service。 +逻辑:同 run 同来源复用(不重复建);终态自动写 finished_at。 +""" + +from __future__ import annotations + +import pytest + +from app.models import TransferRun, TransferSourceJob +from app.services.in_transit_transfer.source_job_service import ( + advance_source_job, + create_source_job, + source_jobs_for_run, +) + + +def _run() -> TransferRun: + from app import db + + run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='prechecking') + db.session.add(run) + db.session.flush() + return run + + +def test_create_source_job_per_run_source_unique(app): + """一次 run 内同来源只建一条 job。""" + run = _run() + job_a = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + job_b = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + from app import db + + db.session.commit() + assert job_a.id == job_b.id + + +def test_source_jobs_for_run_returns_ordered_sources(app): + """source_jobs_for_run 按来源排序。""" + run = _run() + create_source_job(run_id=run.id, source_code='CRANE-SZ') + create_source_job(run_id=run.id, source_code='DBS-AWSBI') + from app import db + + db.session.commit() + jobs = source_jobs_for_run(run.id) + assert [j.source_code for j in jobs] == ['CRANE-SZ', 'DBS-AWSBI'] + + +def test_advance_source_job_writes_status_and_fields(app): + """推进 job 写入状态与来源字段。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='waiting_rpa_callback', file_no='REC-1', file_sha256='hash') + from app import db + + db.session.commit() + assert job.status == 'waiting_rpa_callback' + assert job.file_no == 'REC-1' + assert job.file_sha256 == 'hash' + + +def test_terminal_status_sets_finished_at(app): + """到达终态自动写 finished_at。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='failed', error_code='ERR', error_message='boom') + from app import db + + db.session.commit() + assert job.status == 'failed' + assert job.finished_at is not None + assert job.error_code == 'ERR' + + +def test_file_ready_is_valid_source_job_status(app): + """file_ready 是合法来源 job 状态(来源准备流程阶段与 job 状态集对齐)。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='file_ready', file_no='REC-1') + from app import db + + db.session.commit() + assert job.status == 'file_ready' + assert job.file_no == 'REC-1' diff --git a/backend/tests/services/in_transit_transfer/test_status_machine.py b/backend/tests/services/in_transit_transfer/test_status_machine.py new file mode 100644 index 00000000..deeddb51 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_status_machine.py @@ -0,0 +1,123 @@ +"""在途调拨状态机与转换门禁测试(L0 纯单元)。 + +用途:验证提示词冻结的 13 个状态全部存在、非法迁移被服务端拒绝、 + result_unknown / manually_closed / success 无出边、通知失败不改变 ERP 结果。 +依赖:app.services.in_transit_transfer.status。 +逻辑:所有转换必须显式声明于转换表;未声明迁移一律抛 TransferStateError。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.status import ( + ITEM_TRANSITIONS, + RUN_TRANSITIONS, + TERMINAL_TRANSFER_STATUSES, + TransferNotificationStatus, + TransferRunStatus, + TransferStateError, + TransferStatus, + apply_notification_failure, + assert_transition_allowed, +) + +pytestmark = pytest.mark.pure_unit + +PROMPT_STATUSES = { + "file_pending", "file_ready", "prechecking", "ready_to_execute", "executing", + "success", "duplicate_success", "blocked_recoverable", "not_matured", + "result_unknown", "manually_closed", "cancelled", "notification_failed", +} + + +def test_all_prompt_statuses_covered(): + """提示词要求的 13 个状态必须全部存在。""" + actual = {status.value for status in TransferStatus} + assert PROMPT_STATUSES <= actual + + +def test_success_and_duplicate_success_are_terminal(): + """成功/重复成功为终态(幂等跳过)。""" + assert TransferStatus.SUCCESS in TERMINAL_TRANSFER_STATUSES + assert TransferStatus.DUPLICATE_SUCCESS in TERMINAL_TRANSFER_STATUSES + + +def test_result_unknown_is_terminal_without_outgoing_edges(): + """result_unknown 无出边:禁止自动重试、禁止手工猜测性操作。""" + assert TransferStatus.RESULT_UNKNOWN in TERMINAL_TRANSFER_STATUSES + assert ITEM_TRANSITIONS[TransferStatus.RESULT_UNKNOWN.value] == frozenset() + + +def test_manually_closed_is_terminal_without_outgoing_edges(): + """manually_closed 永久排除:不得再进入待处理池。""" + assert TransferStatus.MANUALLY_CLOSED in TERMINAL_TRANSFER_STATUSES + assert ITEM_TRANSITIONS[TransferStatus.MANUALLY_CLOSED.value] == frozenset() + + +def test_illegal_transition_rejected(): + """file_ready 直接跳 executing 必须抛领域错误。""" + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.EXECUTING.value) + + +def test_legal_transition_accepted(): + """file_ready → prechecking 是合法迁移。""" + assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.PRECHECKING.value) + + +def test_executing_to_success_accepted(): + """executing → success 合法。""" + assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.SUCCESS.value) + + +def test_executing_to_result_unknown_accepted_but_no_auto_retry(): + """executing → result_unknown 合法(超时落位),但之后无任何出边。""" + assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.RESULT_UNKNOWN.value) + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.EXECUTING.value) + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.MANUALLY_CLOSED.value) + + +def test_blocked_recoverable_to_manual_close_and_recheck(): + """blocked_recoverable 可人工关闭或重新预检(新 Attempt)。""" + assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MANUALLY_CLOSED.value) + assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.PRECHECKING.value) + + +def test_unknown_status_rejected(): + """未知状态字符串不得被门禁接受。""" + with pytest.raises(TransferStateError): + assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value) + + +def test_not_matured_has_no_outgoing_edges(): + """not_matured 无出边:当天不得查询 ERP、不得生成调拨单。""" + assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset() + + +def test_run_transition_queued_to_executing_path(): + """Run 生命周期:queued → preparing_files → prechecking → ready_to_execute → executing。""" + assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.PRECHECKING.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.PRECHECKING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.READY_TO_EXECUTE.value, TransferRunStatus.EXECUTING.value, transitions=RUN_TRANSITIONS) + + +def test_notification_failed_does_not_change_erp_result(): + """通知失败不改变 ERP 结果:apply_notification_failure 返回原 ERP 终态。""" + assert apply_notification_failure(TransferRunStatus.SUCCESS.value) == TransferRunStatus.SUCCESS.value + assert apply_notification_failure(TransferRunStatus.PARTIAL_FAILED.value) == TransferRunStatus.PARTIAL_FAILED.value + + +def test_notification_failed_rejected_on_non_terminal_run(): + """非终态 Run 不允许记录通知失败(必须先结束 ERP 阶段)。""" + with pytest.raises(TransferStateError): + apply_notification_failure(TransferRunStatus.EXECUTING.value) + + +def test_notification_status_enum(): + """通知状态枚举包含 pending/success/failed(failed 即 notification_failed 语义)。""" + assert TransferNotificationStatus.FAILED.value == "failed" + assert TransferNotificationStatus.SUCCESS.value == "success" diff --git a/backend/tests/services/in_transit_transfer/test_strategy_policy.py b/backend/tests/services/in_transit_transfer/test_strategy_policy.py new file mode 100644 index 00000000..2117734c --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_strategy_policy.py @@ -0,0 +1,63 @@ +"""在途调拨策略硬门禁测试(L0 纯单元)。 + +用途:验证一期策略禁止部分数量调拨、数量容差与 ERP 自动重试, + 并强制默认确认有效期(10 分钟)。 +依赖:app.services.in_transit_transfer.strategy。 +逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.strategy import ( + TransferStrategyPolicy, + StrategyViolationError, + default_strategy, + validate_strategy, +) + +pytestmark = pytest.mark.pure_unit + + +def test_default_strategy_is_valid(): + """默认策略(无部分调拨/无容差/无自动重试/10 分钟确认)合法。""" + strategy = default_strategy() + validate_strategy(strategy) + assert strategy.confirm_ttl_seconds == 600 + + +def test_partial_transfer_rejected(): + """开启部分数量调拨必须被发布门禁拒绝。""" + strategy = TransferStrategyPolicy(allow_partial=True) + with pytest.raises(StrategyViolationError) as excinfo: + validate_strategy(strategy) + assert "partial" in str(excinfo.value) + + +def test_quantity_tolerance_rejected(): + """任何非零数量容差必须被拒绝。""" + strategy = TransferStrategyPolicy(quantity_tolerance=Decimal("0.01")) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_erp_auto_retry_rejected(): + """开启 ERP 自动重试必须被拒绝(result_unknown 严禁自动重试)。""" + strategy = TransferStrategyPolicy(allow_erp_auto_retry=True) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_combined_violations_still_rejected(): + """多项禁令同时开启仍拒绝。""" + strategy = TransferStrategyPolicy(allow_partial=True, allow_erp_auto_retry=True) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_custom_ttl_allowed_but_default_ten_minutes(): + """确认有效期可配置,但默认必须是 600 秒(10 分钟)。""" + assert TransferStrategyPolicy().confirm_ttl_seconds == 600 diff --git a/backend/tests/services/in_transit_transfer/test_worker_recovery.py b/backend/tests/services/in_transit_transfer/test_worker_recovery.py new file mode 100644 index 00000000..9a02d13e --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_worker_recovery.py @@ -0,0 +1,84 @@ +"""在途调拨 Worker 崩溃/陈旧执行恢复测试(Phase 4,L1)。 + +用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、 + 停滞 Run 可终态收尾、result_unknown 不被自动重试。 +依赖:transfer_db、precheck/execution/recovery、repo_fakes。 +逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 ERP 返回 duplicate_success。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.recovery import ( + finalize_stale_runs, + recover_stale_execution_items, +) +from app.services.in_transit_transfer.status import TransferStatus +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executing_precheck(dbs_ready_file): + """构造已预检 precheck(不执行),并手动把明细置为 executing。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + for item in db.session.query(TransferInvoiceItem).all(): + item.status = "executing" + item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期 + db.session.commit() + return deps, erp + + +def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_file): + """租约过期的 executing 项恢复后完成写入(幂等,无重复建单)。""" + deps, erp = _executing_precheck(dbs_ready_file) + result = recover_stale_execution_items(deps=deps) + assert result["recovered"] == 2 + items = db.session.query(TransferInvoiceItem).all() + assert all(item.status == "success" for item in items) + assert all(item.erp_document_no for item in items) + # 每 Invoice 恰 1 次写(恢复只写一次,不重复建单) + assert len(erp.write_calls()) == 2 + + +def test_recover_skips_result_unknown(transfer_db, dbs_ready_file): + """result_unknown 不自动重试(不触碰、不写 ERP)。""" + deps, erp = _executing_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).first() + item.status = "result_unknown" + db.session.commit() + result = recover_stale_execution_items(deps=deps) + assert result["recovered"] == 1 # 仅另一个 executing 项恢复 + db.session.refresh(item) + assert item.status == "result_unknown" # 未知项保持只读 + assert len(erp.write_calls()) == 1 # 未知项 0 写入 + + +def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file): + """停滞 Run(全部明细已终态但 Run 仍 executing)→ 收尾为 success。""" + from app.models import TransferPrecheck + from app.services.in_transit_transfer.orchestrator import create_execution_run + + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first() + run = create_execution_run(precheck, deps=deps, actor_id=None) + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): + item.status = "success" + item.erp_document_no = "TRF-DONE" + db.session.commit() + + run_ids = finalize_stale_runs() + assert run.id in run_ids + db.session.refresh(run) + assert run.status == "success" \ No newline at end of file diff --git a/backend/tests/services/integration_connector/test_binding.py b/backend/tests/services/integration_connector/test_binding.py new file mode 100644 index 00000000..245b1ff8 --- /dev/null +++ b/backend/tests/services/integration_connector/test_binding.py @@ -0,0 +1,122 @@ +"""tests/services/integration_connector/test_binding.py + +用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。 +依赖:IntegrationBinding 等模型、binding.py、errors.py。 +逻辑:只匹配 published + environment + 生效区间 + context_selector 子集; + 无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.binding import BindingSnapshot, resolve_binding + + +def _client(code="CLI-A", **overrides): + values = {"name": f"client {code}", "connector_type": "soap", "environment": "prod", + "config_json": {"endpoint": "https://erp.invalid"}} + values.update(overrides) + return IntegrationClientInstance(code=code, **values) + + +def _interface(code="IFACE-Q", **overrides): + values = {"name": "查询库存", "client_instance_code": "CLI-A", "connector_type": "soap", + "request_spec_json": {"method": "GET", "path": "/stock"}, + "input_schema_json": {}, "response_mapping_json": {"qty": {"expr": "quantity", "transform": "decimal"}}, + "output_schema_json": {"type": "object", "properties": {"qty": {"type": "number"}}}, + "version": 3, "status": "published"} + values.update(overrides) + return IntegrationInterfaceDefinition(code=code, **values) + + +def _binding(capability="in_transit_transfer.query_inventory", **overrides): + values = {"capability": capability, "context_selector_json": {}, + "client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q", + "mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"} + values.update(overrides) + return IntegrationBinding(**values) + + +def _seed_default(app): + db.session.add_all([_client(), _interface(), _binding()]) + db.session.commit() + + +def test_default_binding_matches_any_context(app): + """空 context_selector 的默认绑定命中(context 含额外键也可命中)。""" + _seed_default(app) + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod") + assert snap.client_code == "CLI-A" + assert snap.interface_code == "IFACE-Q" + assert snap.mapping_version == 2 + + +def test_context_specific_overrides_default(app): + """context_selector 匹配的来源专属绑定(更高优先级)覆盖默认绑定。""" + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(), + _binding(context_selector_json={"source_code": "CRANE-SZ"}, priority=10), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "CRANE-SZ"}, "prod") + assert snap.context_selector == {"source_code": "CRANE-SZ"} + + +def test_higher_priority_wins_among_matching(app): + """同一 context 下、不同 context_selector 均命中时,priority 高者优先。""" + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(context_selector_json={"source_code": "X", "region": "cn"}, priority=1), + _binding(context_selector_json={"source_code": "X"}, priority=5), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X", "region": "cn"}, "prod") + assert snap.context_selector == {"source_code": "X"} # priority 5 绑定胜出 + + +def test_expired_effective_window_not_matched(app): + """effective_to 已过期的绑定不命中,回落到默认。""" + past = datetime.now(timezone.utc) - timedelta(days=1) + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(context_selector_json={"source_code": "X"}, effective_from=past, effective_to=past), + _binding(), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod") + assert snap.context_selector == {} + + +def test_draft_status_not_matched(app): + """status=draft 的绑定不命中;无默认时抛 BindingNotFoundError。""" + db.session.add_all([_client(), _interface(), _binding(status="draft")]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_no_match_raises(app): + """无任何可命中绑定抛 BindingNotFoundError(fail-closed)。""" + db.session.add_all([_client(), _interface(), _binding(capability="other.cap")]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_freeze_versions_in_snapshot(app): + """快照冻结 interface 版本与调用期配置(非活表)。""" + _seed_default(app) + snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert snap.interface_version == 3 + assert snap.credential_ref_code is None + assert snap.request_spec.get("path") == "/stock" + assert snap.config.get("endpoint") == "https://erp.invalid" diff --git a/backend/tests/services/integration_connector/test_capability.py b/backend/tests/services/integration_connector/test_capability.py new file mode 100644 index 00000000..8b0c3c8b --- /dev/null +++ b/backend/tests/services/integration_connector/test_capability.py @@ -0,0 +1,59 @@ +"""tests/services/integration_connector/test_capability.py + +用途:验证 Capability 强类型契约注册表:注册/查询/清单/重复/未注册。 +依赖:服务层 capability.py(纯代码,不依赖 DB);errors.py。 +逻辑:领域只能调用已注册的强类型能力;未注册 fail-closed 抛 INTEGRATION.CAPABILITY_NOT_FOUND。 +""" + +from __future__ import annotations + +import pytest + +from app.services.integration_connector.capability import ( + CapabilitySpec, + ensure_capabilities_loaded, + get_capability, + list_capabilities, + register_capability, + reset_capability_registry_for_tests, +) +from app.core.errors import AppError, ValidationError + + +@pytest.fixture(autouse=True) +def _fresh_registry(): + reset_capability_registry_for_tests() + yield + reset_capability_registry_for_tests() + + +def test_register_then_get_returns_same_spec(): + """注册后按名查询返回同一对象。""" + spec = CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False) + register_capability(spec) + assert get_capability("demo.echo") is spec + + +def test_duplicate_register_raises_validation(): + """同名能力重复注册抛 ValidationError。""" + register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)) + with pytest.raises(ValidationError): + register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)) + + +def test_get_unregistered_raises_not_found(): + """未注册能力抛 INTEGRATION.CAPABILITY_NOT_FOUND(fail-closed)。""" + with pytest.raises(AppError) as exc: + get_capability("in_transit_transfer.none") + assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND" + assert exc.value.http_status == 404 + + +def test_ensure_loaded_registers_three_transfer_capabilities(): + """ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。""" + ensure_capabilities_loaded() + names = {spec.name for spec in list_capabilities()} + assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) + assert get_capability("in_transit_transfer.create_transfer").write is True + assert get_capability("in_transit_transfer.query_inventory").write is False + assert get_capability("in_transit_transfer.verify_duplicate").write is False diff --git a/backend/tests/services/integration_connector/test_engine.py b/backend/tests/services/integration_connector/test_engine.py new file mode 100644 index 00000000..8cb22785 --- /dev/null +++ b/backend/tests/services/integration_connector/test_engine.py @@ -0,0 +1,162 @@ +"""tests/services/integration_connector/test_engine.py + +用途:验证 CapabilityGateway 调用引擎管线——resolve→validate→call→map→classify→落 IntegrationCall。 +依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 +逻辑:读能力走 success(映射校验通过);写能力按原始 status 分类;超时→timeout; + 入参非法/无绑定/映射失败/result_unknown 均 fail-closed,且 result_unknown 不自动重试。 +""" + +from __future__ import annotations + +from datetime import datetime +from decimal import Decimal + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.capability import ensure_capabilities_loaded +from app.services.integration_connector.engine import CapabilityGateway + + +class FakeTransport: + """可注入响应或异常的传输替身。""" + + connector_type = "rest" + + def __init__(self, response): + self._response = response + + def call(self, *, client, interface, request): + if isinstance(self._response, Exception): + raise self._response + return self._response + + +def _seed(capability, *, connector_type="rest", response_mapping=None, output_schema=None): + resp_map = response_mapping or {"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}} + out_schema = output_schema or {"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}} + client = IntegrationClientInstance( + code="CLI-A", name="client", connector_type=connector_type, environment="prod", + config_json={"endpoint": "https://erp.invalid"}, + ) + iface = IntegrationInterfaceDefinition( + code="IFACE-Q", name="iface", client_instance_code="CLI-A", connector_type=connector_type, + request_spec_json={"method": "GET", "path": "/stock/{invoice_no}"}, + input_schema_json={}, response_mapping_json=resp_map, output_schema_json=out_schema, + version=3, status="published", + ) + db.session.add_all([client, iface]) + db.session.flush() + binding = IntegrationBinding( + capability=capability, context_selector_json={}, client_instance_code="CLI-A", + interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod", + status="published", + ) + db.session.add(binding) + db.session.commit() + return connector_type + + +def _params(**overrides): + values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} + values.update(overrides) + return values + + +def test_call_success_records_integration_call(app): + """读能力成功:status=success、data 含映射结果、落 IntegrationCall。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + fake = FakeTransport({"found": True, "quantity": "100"}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-1", environment="prod", + ) + assert result.status == "success" + assert result.data["quantity"] == Decimal("100") + call_row = IntegrationCall.query.filter_by(operation_id="OP-1").first() + assert call_row is not None + assert call_row.status == "success" + + +def test_call_input_invalid_raises(app): + """入参不合输入 Schema → INTEGRATION.INPUT_INVALID。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( + capability="in_transit_transfer.query_inventory", context={}, + params={}, operation_id="OP-2", environment="prod", + ) + assert exc.value.code == "INTEGRATION.INPUT_INVALID" + + +def test_call_no_binding_raises(app): + """无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。""" + ensure_capabilities_loaded() + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-3", environment="prod", + ) + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_call_write_business_failed(app): + """写能力按原始 status 分类 → business_failed。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.create_transfer") + fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_params(), operation_id="OP-4", environment="prod", + ) + assert result.status == "business_failed" + assert result.error_code == "E1" + + +def test_call_transport_timeout_returns_timeout(app): + """传输超时 → status=timeout。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-5", environment="prod", + ) + assert result.status == "timeout" + + +def test_call_mapping_invalid_raises(app): + """输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory", + output_schema={"type": "object", "required": ["found", "quantity"], + "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}) + fake = FakeTransport({"found": True}) # 缺 quantity + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-6", environment="prod", + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_call_result_unknown_no_auto_retry(app): + """result_unknown 不自动重试:transport 仅被调用一次。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.create_transfer") + calls = [] + + class _OneShot(FakeTransport): + def call(self, **kw): + calls.append(1) + return {"status": "result_unknown"} + + result = CapabilityGateway(transports={"rest": _OneShot(None)}).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_params(), operation_id="OP-7", environment="prod", + ) + assert result.status == "result_unknown" + assert len(calls) == 1 diff --git a/backend/tests/services/integration_connector/test_mapping.py b/backend/tests/services/integration_connector/test_mapping.py new file mode 100644 index 00000000..e6548a2a --- /dev/null +++ b/backend/tests/services/integration_connector/test_mapping.py @@ -0,0 +1,96 @@ +"""tests/services/integration_connector/test_mapping.py + +用途:验证声明式映射引擎——点路径/数组下标提取、白名单转换函数、最小 Schema 校验。 +依赖:mapping.py(纯函数);errors.py。 +逻辑:缺字段且不可满足→MappingInvalidError;非法类型/枚举→MappingInvalidError; + 表达式超深/超长→MappingInvalidError(fail-closed)。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.core.errors import AppError +from app.services.integration_connector.mapping import MISSING, extract_path, map_response + + +def test_extract_path_dot(): + assert extract_path({"a": {"b": 1}}, "a.b") == 1 + + +def test_extract_path_array_index(): + assert extract_path({"a": [10, 20]}, "a[1]") == 20 + + +def test_extract_path_missing_returns_sentinel(): + assert extract_path({"a": 1}, "a.b") is MISSING + assert extract_path({"a": [1]}, "a[9]") is MISSING + + +def test_extract_path_depth_limit(): + deep = {"a": {"b": {"c": {"d": {"e": {"f": {"g": {"h": {"i": 1}}}}}}}}} + with pytest.raises(AppError) as exc: + extract_path(deep, "a.b.c.d.e.f.g.h.i") + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_extract_path_length_limit(): + with pytest.raises(AppError) as exc: + extract_path({"a": 1}, "a." + "b" * 300) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_extract_and_decimal_transform(): + mapped = map_response( + {"qty": {"expr": "rows[0].qty", "transform": "decimal"}}, + {"rows": [{"qty": "100.5"}]}, + {"type": "object", "required": ["qty"], "properties": {"qty": {"type": "number"}}}, + ) + assert mapped["qty"] == Decimal("100.5") + + +def test_map_response_default_and_fallback(): + mapped = map_response( + { + "a": {"expr": "missing", "transform": "default", "args": {"default": 7}}, + "b": {"expr": "missing", "transform": "fallback", "args": {"fallback": "X"}}, + }, + {}, + {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "string"}}}, + ) + assert mapped == {"a": 7, "b": "X"} + + +def test_map_response_missing_required_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"a": {"expr": "missing"}}, + {}, + {"type": "object", "required": ["a"], "properties": {"a": {"type": "string"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_wrong_type_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"a": {"expr": "x"}}, + {"x": "not-a-number"}, + {"type": "object", "required": ["a"], "properties": {"a": {"type": "number"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_enum_violation_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"status": {"expr": "s"}}, + {"s": "banana"}, + { + "type": "object", "required": ["status"], + "properties": {"status": {"type": "string", "enum": ["ok", "bad"]}}, + }, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" diff --git a/backend/tests/services/integration_connector/test_migration.py b/backend/tests/services/integration_connector/test_migration.py new file mode 100644 index 00000000..4d00b979 --- /dev/null +++ b/backend/tests/services/integration_connector/test_migration.py @@ -0,0 +1,86 @@ +"""tests/services/integration_connector/test_migration.py + +用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。 +依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f / ix1a2b3c4d5e 迁移。 +逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +import pytest + + +EXPECTED_TABLES = { + 'integration_credential_references', + 'integration_client_instances', + 'integration_interface_definitions', + 'integration_bindings', + 'integration_calls', +} + +VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions' + + +def _load_migration(name: str, filename: str): + """加载指定迁移模块。""" + path = VERSIONS_DIR / filename + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_migration_chains_after_head(): + """建表迁移必须挂接在既有链 head it1a2b3c4d5e 之后。""" + migration = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py') + assert migration.revision == 'ic1a2b3c4d5f' + assert migration.down_revision == 'it1a2b3c4d5e' + + +def test_integration_connector_migration_round_trip(): + """空库升级后 5 表存在;回滚后全部删除。""" + engine = sa.create_engine('sqlite:///:memory:') + base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py') + split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py') + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + base.op = operations + split.op = operations + + base.upgrade() + split.upgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert EXPECTED_TABLES.issubset(tables) + + inspector = sa.inspect(connection) + client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')} + assert 'credential_ref_code' in client_cols + assert 'endpoint' in client_cols + assert 'timeout_seconds' in client_cols + iface_cols = {item['name'] for item in inspector.get_columns('integration_interface_definitions')} + assert 'http_method' in iface_cols + assert 'request_path' in iface_cols + binding_cols = {item['name'] for item in inspector.get_columns('integration_bindings')} + assert 'context_source_code' in binding_cols + binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')} + assert 'ix_integration_bindings_cap_env_status' in binding_indexes + + split.downgrade() + base.downgrade() + assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names())) + + +def test_split_migration_chains_after_create(): + """拆列迁移必须挂接在 ic1a2b3c4d5e 之后(down_revision=iy1a2b3c4d5e)。""" + split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py') + assert split.revision == 'ix1a2b3c4d5e' + assert split.down_revision == 'iy1a2b3c4d5e' diff --git a/backend/tests/services/integration_connector/test_models.py b/backend/tests/services/integration_connector/test_models.py new file mode 100644 index 00000000..25c4fedf --- /dev/null +++ b/backend/tests/services/integration_connector/test_models.py @@ -0,0 +1,119 @@ +"""tests/services/integration_connector/test_models.py + +用途:验证 Integration Connector 领域模型的可建表、唯一约束与状态/连接器类型约束。 +依赖:根 conftest 的 app fixture(SQLite 内存 + db.create_all())。 +逻辑:create_all 后各表可查询为空;code 唯一冲突抛 IntegrityError;非法 + connector_type / status 被 CheckConstraint 拒绝。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy.exc import IntegrityError + +from app import db +from app.models import ( + IntegrationBinding, + IntegrationCall, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) + +CONNECTOR_MODELS = ( + IntegrationCredentialReference, + IntegrationClientInstance, + IntegrationInterfaceDefinition, + IntegrationBinding, + IntegrationCall, +) + + +def _client(**overrides): + values = { + "code": "ERP-T100", + "name": "T100 ERP", + "connector_type": "soap", + "environment": "prod", + "config_json": {"endpoint": "https://t100.invalid/ws", "timeout_seconds": 60}, + } + values.update(overrides) + return IntegrationClientInstance(**values) + + +def test_all_connector_tables_created_and_empty(app): + """create_all 已随 app fixture 执行,5 张连接器表均可插入且初始为空。""" + for model in CONNECTOR_MODELS: + assert model.query.count() == 0 + + +def test_client_instance_code_unique_conflict(app): + """同一 code 的第二条记录触发唯一约束。""" + db.session.add(_client()) + db.session.flush() + db.session.add(_client()) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_client_instance_connector_type_check(app): + """connector_type 不在白名单(rest/soap)时被 CheckConstraint 拒绝。""" + db.session.add(_client(connector_type="ftp")) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_interface_definition_status_check(app): + """InterfaceDefinition.status 非法值被 CheckConstraint 拒绝。""" + client = _client() + db.session.add(client) + db.session.flush() + iface = IntegrationInterfaceDefinition( + code="ERP-QUERY-STOCK", + name="查询库存", + client_instance_code=client.code, + connector_type="soap", + request_spec_json={"template": "{{invoice_no}}"}, + input_schema_json={}, + response_mapping_json={}, + output_schema_json={}, + version=1, + status="banana", + ) + db.session.add(iface) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_credential_reference_status_check(app): + """CredentialReference.status 非法值被 CheckConstraint 拒绝。""" + db.session.add(IntegrationCredentialReference( + code="ERP-CRED-01", + secret_ref="ERP_PASSWORD", + secret_provider="env", + credential_type="password", + version=1, + status="expired", + )) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_credential_reference_secret_ref_not_returned_in_summary_column(app): + """模型列本身不存明文;secret_ref 是引用键而非真实凭据。""" + cred = IntegrationCredentialReference( + code="ERP-CRED-01", + secret_ref="ERP_PASSWORD", + secret_provider="env", + credential_type="password", + version=1, + status="active", + ) + db.session.add(cred) + db.session.flush() + assert cred.secret_ref == "ERP_PASSWORD" + assert "password" not in cred.secret_ref.lower() or cred.secret_ref != "P@ssw0rd!" diff --git a/backend/tests/services/integration_connector/test_security.py b/backend/tests/services/integration_connector/test_security.py new file mode 100644 index 00000000..7f53ab69 --- /dev/null +++ b/backend/tests/services/integration_connector/test_security.py @@ -0,0 +1,73 @@ +"""tests/services/integration_connector/test_security.py + +用途:验证凭据引用解析(fail-closed)与敏感字段脱敏。 +依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 +逻辑:secret_ref 指向缺失配置键→CredentialUnresolvedError;sanitize 脱敏敏感键; + credential_summary 只含元数据,绝不含明文。 +""" + +from __future__ import annotations + +import json + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationCredentialReference +from app.services.integration_connector.security import credential_summary, resolve_credential, sanitize + + +def _add_credential(code="ERP-CRED-01", secret_ref="ERP_TEST_CRED", **overrides): + cred = IntegrationCredentialReference( + code=code, secret_ref=secret_ref, secret_provider="env", + credential_type="password", version=1, status="active", **overrides, + ) + db.session.add(cred) + db.session.flush() + return cred + + +def test_resolve_credential_returns_secrets(app): + """secret_ref 指向存在的配置键时返回该字典。""" + app.config["ERP_TEST_CRED"] = {"username": "u", "password": "p", "endpoint": "https://erp.invalid"} + _add_credential() + creds = resolve_credential("ERP-CRED-01") + assert creds == {"username": "u", "password": "p", "endpoint": "https://erp.invalid"} + + +def test_resolve_credential_missing_secret_fail_closed(app): + """secret_ref 指向缺失/空配置键时抛 CredentialUnresolvedError。""" + _add_credential(secret_ref="MISSING_KEY") + with pytest.raises(AppError) as exc: + resolve_credential("ERP-CRED-01") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" + + +def test_resolve_credential_unknown_ref_fail_closed(app): + """凭据引用不存在时抛 CredentialUnresolvedError。""" + with pytest.raises(AppError) as exc: + resolve_credential("NOPE") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" + + +def test_sanitize_redacts_sensitive_keys(): + """sanitize 递归把 password/token/secret 等键替换为 ***。""" + data = {"outer": {"password": "s3cret", "keep": "ok"}, "token": "abc", "list": [{"secret": "x"}]} + out = sanitize(data) + assert out["outer"]["password"] == "***" + assert out["outer"]["keep"] == "ok" + assert out["token"] == "***" + assert out["list"][0]["secret"] == "***" + assert "s3cret" not in json.dumps(out) + + +def test_credential_summary_has_no_plaintext(app): + """credential_summary 只含元数据,不含解析出的明文。""" + app.config["ERP_TEST_CRED"] = {"username": "svc_user_erp", "password": "s3cretLY"} + cred = _add_credential() + resolve_credential("ERP-CRED-01") # 确保能解析 + summary = credential_summary(cred) + assert "s3cretLY" not in json.dumps(summary) + assert "svc_user_erp" not in json.dumps(summary) + assert summary["version"] == 1 diff --git a/backend/tests/services/integration_connector/test_transports.py b/backend/tests/services/integration_connector/test_transports.py new file mode 100644 index 00000000..bd3cfc80 --- /dev/null +++ b/backend/tests/services/integration_connector/test_transports.py @@ -0,0 +1,104 @@ +"""tests/services/integration_connector/test_transports.py + +用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed; + 以及结果分类(classify_transport_response)的六态语义。 +依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。 +逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。 +""" + +from __future__ import annotations + +import pytest + +from app.services.integration_connector.errors import TransportNotFrozenError +from app.services.integration_connector.transports.base import IntegrationCallResult, classify_transport_response +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + + +def _resp(status_code, payload=None, text=""): + class _Response: + def __init__(self): + self.status_code = status_code + self.text = text + self._payload = payload + + def json(self): + return self._payload + + return _Response() + + +def _client(**overrides): + cfg = {"endpoint": "https://erp.invalid", "timeout_seconds": 30} + cfg.update(overrides) + return {"config_json": cfg, "credential": {}} + + +def test_rest_builds_url_and_sends_request(): + """REST Transport 拼接 endpoint+path,按 method/params 发请求并返回 JSON。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(method=method, url=url, params=kw.get("params"), json=kw.get("json")) + return _resp(200, {"found": True, "quantity": "100"}) + + transport = RestTransport(http_request=fake_http) + result = transport.call( + client=_client(), + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={"params": {"invoice_no": "INV-001"}}, + ) + assert captured["url"] == "https://erp.invalid/stock" + assert captured["method"] == "GET" + assert captured["params"] == {"invoice_no": "INV-001"} + assert result == {"found": True, "quantity": "100"} + + +def test_rest_business_error_maps_to_dict(): + """4xx 映射为 business_failed dict,供上层透传分类。""" + + def fake_http(method, url, **kw): + return _resp(404, text="not found") + + transport = RestTransport(http_request=fake_http) + result = transport.call( + client=_client(), + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={}, + ) + assert result["status"] == "business_failed" + assert result["code"] == "HTTP_404" + assert "not found" in result["message"] + + +def test_rest_fail_closed_without_endpoint(): + """endpoint 未冻结时 fail-closed 抛 TransportNotFrozenError。""" + transport = RestTransport(http_request=lambda *a, **k: None) + with pytest.raises(TransportNotFrozenError): + transport.call( + client={"config_json": {}}, + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={}, + ) + + +def test_soap_fail_closed_without_wsdl(): + """SOAP 无 wsdl 时 fail-closed 抛 TransportNotFrozenError(SOAP 只需 wsdl,不需 endpoint)。""" + transport = SoapTransport() + with pytest.raises(TransportNotFrozenError): + transport.call( + client={"config_json": {}}, + interface={"request_spec_json": {"soap_action": "queryInventory"}}, + request={}, + ) + + +def test_classify_transport_response_states(): + """结果分类覆盖 success/duplicate_success/business_failed/technical_failed。""" + assert classify_transport_response({"status": "success", "document_no": "DOC-1"}).status == "success" + assert classify_transport_response({"status": "business_failed", "code": "E1", "message": "reject"}).status == "business_failed" + dup = classify_transport_response({"status": "duplicate_success", "verified_posted": True, "document_no": "DOC-9"}) + assert dup.status == "duplicate_success" + unknown = classify_transport_response({}) + assert unknown.status == "technical_failed" diff --git a/backend/tests/services/shipping_notice/test_customer_resolution_service.py b/backend/tests/services/shipping_notice/test_customer_resolution_service.py new file mode 100644 index 00000000..0161d3b2 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_customer_resolution_service.py @@ -0,0 +1,84 @@ +""" +用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。 +依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。 +逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + User, +) +from app.services.shipping_notice.customer_resolution_service import ( + confirm_customer_resolution, + customer_resolution_facts, +) + + +def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]: + """构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。""" + user = User(username='resolution-user', email='resolution@example.com', role='user') + customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active') + db.session.add_all([user, customer]) + db.session.flush() + intake = ShippingOrderIntake( + intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1, + candidate_key='resolution-test', candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id) + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=intake.id, + resolution_version='shadow-v2', + status=status, + evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, + identity_rule_set_checksum='a' * 64, + top_customer_id=customer.id, + top_score=100, + ) + db.session.add_all([task, resolution]) + db.session.commit() + return task, resolution, customer + + +def test_non_bill_to_evidence_can_confirm_customer(app): + """关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。""" + with app.app_context(): + task, resolution, customer = _task_with_resolution() + + confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual') + db.session.commit() + facts = customer_resolution_facts(task) + + assert facts['status'] == 'confirmed' + assert facts['customer_id'] == customer.id + assert resolution.confirmed_customer_id == customer.id + # 关键断言:确认不篡改规则证据及其 checksum。 + assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}] + assert resolution.identity_rule_set_checksum == 'a' * 64 + + +def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app): + """关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。""" + with app.app_context(): + task, _resolution, _customer = _task_with_resolution(status='unique_candidate') + + facts = customer_resolution_facts(task) + + assert facts['status'] == 'unique_candidate' + assert facts['customer_id'] is None diff --git a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py index 47da3c5c..f63675e6 100644 --- a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py +++ b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py @@ -13,7 +13,9 @@ from app.models import ( ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, - ShippingNotice, + ShippingOrderTask, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, ShippingNoticeLineInventoryMatch, ShippingInventoryFile, ) @@ -23,17 +25,18 @@ from app.services.shipping_notice.inventory_candidate_projection import ( from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines -def _task(task_no: str) -> ShippingNotice: - task = ShippingNotice( +def _task(task_no: str) -> ShippingOrderTask: + task = ShippingOrderTask( task_no=task_no, - source_type='manual', + source_type='direct_pdf', + user_id=1, ) db.session.add(task) db.session.flush() return task -def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet: +def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet: row = ShippingInventoryCandidateSet( task_id=int(task.id), set_version=version, @@ -120,9 +123,19 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): ) db.session.add(new_line) db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=int(task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, source_manifest_json={}, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) + db.session.add(snapshot_line) + db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=int(task.id), - line_key='line-1', + snapshot_line_id=int(snapshot_line.id), + line_no=1, line_index=0, candidate_set_id=int(old_set.id), candidate_set_version=1, @@ -152,16 +165,26 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'], )) db.session.flush() - snapshot = ShippingInventoryFile( + inventory_file = ShippingInventoryFile( inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64, ) + db.session.add(inventory_file) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=int(task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, source_manifest_json={}, header_values_json={}, + ) db.session.add(snapshot) db.session.flush() + snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) + db.session.add(snapshot_line) + db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( - task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id), - candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched', - inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no, + task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1, + candidate_set_id=int(candidate_set.id), + candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched', + inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no, matched_row_index=9, is_current=True, detail_json={}, )) db.session.commit() diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 68695869..1ca8a885 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s ('failed', False, 'failed', '业务阻断失败 → failed'), ('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'), ('failed', True, 'retryable', '技术失败 retryable → retryable'), - ('idle', False, 'idle', 'Idle → idle(默认)'), + ('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'), ], ids=lambda t: t[3] if isinstance(t, tuple) else '', ) -def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label): - """[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。""" +def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label): + """[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。""" from app.services.shipping_notice.reconciliation_projector import project_case_user_status case = _fake_case(status='draft') @@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch): """正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。""" from app.services.shipping_notice import reconciliation_projector - case = _fake_case(status='draft', candidate_id=None) + # 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。 + case = _fake_case(status='confirmed', candidate_id=None) monkeypatch.setattr( reconciliation_projector, '_project_case_formal_gate_summary', 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 5af4a963..65c90ccd 100644 --- a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py +++ b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py @@ -25,9 +25,11 @@ from app.models import ( ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, - ShippingOrderCustomerMatch, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, + ShippingOrderIntake, ShippingCustomer, - ShippingNotice, + ShippingOrderTask, User, ) from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness @@ -43,7 +45,7 @@ from app.services.shipping_notice.order_freeze_service import ( def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'): """创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。""" user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x') - task = ShippingNotice(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7) + task = ShippingOrderTask(task_no=f'OT-SNAPSHOT-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7) schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order') db.session.add_all([user, task, schema]) db.session.flush() @@ -82,7 +84,7 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() values = { @@ -119,13 +121,26 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: customer = ShippingCustomer(standard_name='Snapshot Customer', short_code='CUS') db.session.add(customer) db.session.flush() - db.session.add(ShippingOrderCustomerMatch( - extraction_id=extraction.id, role='bill_to', raw_name='Snapshot Customer', - normalized_name='SNAPSHOT CUSTOMER', status='confirmed', customer_id=customer.id, - customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, - identity_fingerprint='f' * 64, identity_rule_version='order-customer-fingerprint.v1', - identity_components_json={'role': 'bill_to'}, resolution_method='manual', - confirmation_reason='测试确认', confirmed_by_id=user.id, confirmed_at=datetime.utcnow(), + intake = ShippingOrderIntake( + intake_no=f'INT-SNAPSHOT-{suffix}', asset_id=1, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-SNAPSHOT-{suffix}', intake_id=intake.id, primary_document_id=1, + candidate_key=f'snapshot-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task.candidate_id = candidate.id + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'f' * 64}}, + identity_rule_set_checksum='f' * 64, top_customer_id=customer.id, top_score=100, + confirmed_customer_id=customer.id, confirmation_method='manual', confirmed_by_id=user.id, + confirmed_at=datetime.utcnow(), )) db.session.commit() return task, user @@ -141,7 +156,7 @@ def test_freeze_creates_strong_snapshot_and_preserves_identifiers(app): assert task.order_snapshot_id == snapshot.id assert snapshot.customer_short_code_snapshot == 'CUS' assert snapshot.customer_id is not None - assert snapshot.rule_versions_json['ordering_customer']['identity_rule_version'] == 'order-customer-fingerprint.v1' + assert snapshot.rule_versions_json['ordering_customer']['identity_rule_set_checksum'] == 'f' * 64 assert snapshot.lines[0].part_number == '000123' assert snapshot.lines[0].reservation_id == '0012345678' assert snapshot.lines[0].qty == Decimal('12.50000000') @@ -225,10 +240,9 @@ def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app): """冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。""" with app.app_context(): task, user = _build_accepted_order() - match = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=task.current_order_extraction_id, role='bill_to', - ).one() - match.status = 'unique_candidate' + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + resolution.status = 'unique_candidate' + resolution.confirmed_customer_id = None with pytest.raises(ValidationError) as error: freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) assert error.value.code == 'SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED' diff --git a/backend/tests/test_admin_create_user_casdoor.py b/backend/tests/test_admin_create_user_casdoor.py index a4c1282e..d2188fa7 100644 --- a/backend/tests/test_admin_create_user_casdoor.py +++ b/backend/tests/test_admin_create_user_casdoor.py @@ -247,6 +247,35 @@ def test_admin_update_user_rolls_back_when_casdoor_password_fails(client, admin_ assert user.check_password('old-password') +def test_admin_update_user_rejects_unchanged_password(client, admin_headers, monkeypatch): + """管理员提交与当前相同的密码应 400 AUTH.PASSWORD_UNCHANGED,且不调用 Casdoor。""" + user = _create_local_user('same_pw_user', 'same_pw_user@example.com') + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + casdoor_calls = {'set_password': 0} + + def fake_set_password(_owner, _name, _old, _new): + casdoor_calls['set_password'] += 1 + + monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password) + + res = client.put( + f'/api/admin/users/{user.id}', + json={'password': 'old-password'}, + headers=admin_headers, + ) + # 断言:相同密码按业务校验失败,不刷新 token / 不清会话。 + assert res.status_code == 400 + payload = res.get_json() or {} + error = payload.get('error') or {} + assert error.get('code') == 'AUTH.PASSWORD_UNCHANGED' + assert casdoor_calls['set_password'] == 0 + db.session.refresh(user) + assert user.check_password('old-password') + + def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, admin_headers, monkeypatch): """ IdP 无账号且管理员改密时,应 set-password 失败后 fallback 至 add-user,不调用 update-user。 diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index d0ff6695..df30caa8 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -22,6 +22,11 @@ from app.models import ( ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingOrderTask, + ShippingOrderExtraction, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingNoticeLineInventoryMatch, ShippingNotice, User, ) @@ -65,6 +70,98 @@ def _headers(username: str, role: str) -> dict[str, str]: return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} +def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | None = None) -> ShippingNotice: + """创建由已确认客户识别结果支撑的正式 Notice,避免回写 bill_to 或旧匹配表。""" + _identity_field() + user = User.query.filter_by(username='shipping-admin').one() + version = ShippingOrderSchemaVersion.query.filter_by(status='published').order_by( + ShippingOrderSchemaVersion.id.desc(), + ).first() + asset = FileAsset( + asset_no=f'FA-{task_no}', owner_user_id=user.id, original_filename='notice.pdf', + storage_provider='minio', storage_bucket='test', storage_key=f'{task_no}.pdf', + content_hash=f'{task_no:0<64}'[:64], file_size=1, upload_status='uploaded', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingOrderIntake( + intake_no=f'INTAKE-{task_no}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed', + ) + db.session.add(intake) + db.session.flush() + document = ShippingOrderDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file', + filename='notice.pdf', classification='order_notice', parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CANDIDATE-{task_no}', intake_id=intake.id, primary_document_id=document.id, + candidate_key='document:1', validation_status='ready', selected=True, + ) + db.session.add(candidate) + db.session.flush() + task = ShippingOrderTask( + task_no=task_no, user_id=user.id, intake_id=intake.id, candidate_id=candidate.id, + status='ready', current_step='customer_review', + ) + db.session.add(task) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, + schema_version_id=version.id, + input_snapshot_hash=('a' * 64), + status='accepted', + ) + db.session.add(extraction) + db.session.flush() + task.current_order_extraction_id = extraction.id + candidate.order_extraction_id = extraction.id + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=intake.id, + resolution_version='test-v1', + status='confirmed', + evidence_json=[], + candidate_matches_json=[], + confirmed_customer_id=customer_id, + confirmation_method='manual', + )) + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=extraction.id, + schema_version_id=version.id, + order_data_version=1, + header_values_json={}, + source_manifest_json={}, + rule_versions_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + part_number='TEST-PART', + qty=1, + ) + db.session.add(snapshot_line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line.id, + line_no=1, + match_result='matched', + inventory_status='ready', + is_current=True, + )) + notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id) + db.session.add(notice) + db.session.flush() + return notice + + def test_shipping_customer_admin_crud_uses_standard_contract(app, client): """管理员可创建和查询客户,校验失败返回标准错误 envelope。""" app.config['AUTH_JWT_REQUIRED'] = False @@ -327,7 +424,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers( customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active') db.session.add(customer) db.session.flush() - db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id)) + _notice_with_customer(task_no='SN-DELETE-API', customer_id=customer.id) db.session.commit() customer_id = customer.id @@ -346,7 +443,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers( assert blocked.status_code == 409 error = parse_api_error(blocked.get_json()) assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' - assert error['details']['blockers']['business_cases'] == 1 + assert error['details']['blockers']['shipping_notices'] == 1 def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client): @@ -363,7 +460,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias', normalized_value='SOURCEALIAS', status='approved', source='manual', ), - ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'), + _notice_with_customer(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'), ]) db.session.commit() source_id = source.id @@ -382,7 +479,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( headers=admin_headers, ) assert preview.status_code == 200 - assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1 + assert parse_api_data(preview.get_json())['historical_references']['shipping_notices'] == 1 response = client.post( f'/api/admin/shipping-customers/{source_id}/merge', @@ -396,7 +493,10 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( with app.app_context(): assert db.session.get(ShippingCustomer, source_id).status == 'merged' assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1 - assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id + notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one() + task = db.session.get(ShippingOrderTask, notice.order_task_id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert resolution.confirmed_customer_id == source_id def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client): @@ -507,47 +607,3 @@ def test_shipping_customer_shadow_report_and_label_api(app, client): headers=_headers('shipping-user', 'user'), ) assert forbidden.status_code == 403 - - -def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client): - """管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。""" - app.config['AUTH_JWT_REQUIRED'] = False - with app.app_context(): - _create_users() - wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active') - correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active') - db.session.add_all([wrong, correct]) - db.session.flush() - task = ShippingNotice( - task_no='SN-CORRECTION-API', - source_type='manual', customer_resolution_status='pending', - ) - db.session.add(task) - db.session.commit() - from app.services.shipping_notice.customer_identity_gate import confirm_task_customer - - confirm_task_customer(task, customer_id=wrong.id, actor_id=None) - old_business_no = task.business_no - correct_id = correct.id - - forbidden = client.post( - '/api/admin/shipping-customers/numbered-task-correction', - json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'}, - headers=_headers('shipping-user', 'user'), - ) - assert forbidden.status_code == 403 - - response = client.post( - '/api/admin/shipping-customers/numbered-task-correction', - json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'}, - headers=_headers('shipping-admin', 'admin'), - ) - assert response.status_code == 200 - payload = parse_api_data(response.get_json()) - assert payload['old_business_no'] == old_business_no - assert payload['new_business_no'].startswith('NEW') - with app.app_context(): - old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one() - replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one() - assert old_notice.lifecycle_status == 'voided' - assert replacement.business_no == payload['new_business_no'] diff --git a/backend/tests/test_agent_registry_catalog.py b/backend/tests/test_agent_registry_catalog.py index 7d40baab..e1091da7 100644 --- a/backend/tests/test_agent_registry_catalog.py +++ b/backend/tests/test_agent_registry_catalog.py @@ -16,18 +16,22 @@ from app.services.agent_registry.catalog import ( def test_agent_type_catalog_contains_three_seed_types(): - """首批 Catalog 应包含 generic、shipping_notice、file_check 三类。""" - assert set(AGENT_TYPE_CATALOG.keys()) == {'generic', 'shipping_notice', 'file_check'} + """Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。""" + assert { + 'generic', 'shipping_notice', 'file_check', + 'procurement_contract_review', 'in_transit_transfer', + } <= set(AGENT_TYPE_CATALOG.keys()) def test_list_type_catalog_includes_agent_code_and_label(): """Admin 下拉列表每条须含 agent_code 与人类可读 label。""" catalog = list_type_catalog() - assert len(catalog) == 3 + assert len(catalog) >= 5 codes = {entry['agent_code'] for entry in catalog} - assert codes == {'generic', 'shipping_notice', 'file_check'} + assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes labels = {entry['label'] for entry in catalog} assert '通用问答 / 知识库' in labels + assert '在途仓自动调拨' in labels assert '货代发货通知' in labels assert '文件检核' in labels diff --git a/backend/tests/test_agent_registry_in_transit_transfer.py b/backend/tests/test_agent_registry_in_transit_transfer.py new file mode 100644 index 00000000..a6530647 --- /dev/null +++ b/backend/tests/test_agent_registry_in_transit_transfer.py @@ -0,0 +1,69 @@ +"""在途仓自动调拨 Agent 应用类型注册测试。 + +用途:验证 in_transit_transfer 已注册为 Agent 应用类型(catalog manifest + handler 绑定 + + HANDLER_REGISTRY),与既有 shipping_notice 注册链路一致。 +依赖:catalog_loader / catalog_bindings / handlers.bootstrap / resolver / catalog_validation。 +逻辑:只读断言注册契约;不创建 Flask 应用(避免对既有 catalog 单测造成影响)。 +""" + +from __future__ import annotations + +import pytest + +from app.services.agent_registry import catalog_bindings +from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry +from app.services.agent_registry.catalog_validation import ( + apply_catalog_capabilities, + normalize_handler_config, + validate_required_fields, +) +from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests +from app.services.agent_registry.handlers.base import AgentHandler +from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY + + +def test_in_transit_transfer_type_in_catalog(): + """catalog 必须包含 in_transit_transfer 应用类型及关键声明。""" + entry = get_catalog_entry('in_transit_transfer') + assert entry is not None + assert entry.get('label') == '在途仓自动调拨' + assert entry.get('runtime_provider_default') == 'hybrid' + progress = entry.get('progress_contract') or {} + assert progress.get('enabled') is True + assert progress.get('data_source', {}).get('domain') == 'in_transit_transfer' + + +def test_in_transit_transfer_bound_to_runtime_handler(): + """catalog_bindings 必须把 in_transit_transfer 绑定到同名 HANDLER_REGISTRY key。""" + assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['in_transit_transfer'] == 'in_transit_transfer' + + +def test_in_transit_transfer_handler_registered(): + """bootstrap 加载后 HANDLER_REGISTRY 包含 InTransitTransferHandler 实例。""" + reset_handlers_for_tests() + load_handlers() + handler = HANDLER_REGISTRY.get('in_transit_transfer') + assert handler is not None + assert isinstance(handler, AgentHandler) + assert handler.handler_key == 'in_transit_transfer' + reset_handlers_for_tests() + + +def test_in_transit_transfer_validation_compatible(): + """catalog_validation 对 in_transit_transfer 的强制能力/配置归一化/必填校验可执行。""" + from app.core.errors import ValidationError + + capabilities = apply_catalog_capabilities('in_transit_transfer', {'streaming': True}) + assert capabilities.get('human_confirm') is True + # 空 handler_config_schema:null 允许、任意字段拒绝(与既有类型一致)。 + assert normalize_handler_config('in_transit_transfer', None) is None + with pytest.raises(ValidationError): + normalize_handler_config('in_transit_transfer', {'poll_interval_seconds': '5'}) + validate_required_fields('in_transit_transfer', bound_schedule_task_id=None) + + +def test_in_transit_transfer_present_in_full_catalog(): + """完整 catalog 构建包含新类型(与既有类型共存)。""" + catalog = build_agent_type_catalog() + assert 'in_transit_transfer' in catalog + assert 'shipping_notice' in catalog diff --git a/backend/tests/test_casdoor_errors.py b/backend/tests/test_casdoor_errors.py index d24951ed..c95c5c70 100644 --- a/backend/tests/test_casdoor_errors.py +++ b/backend/tests/test_casdoor_errors.py @@ -1,3 +1,10 @@ +""" +tests/test_casdoor_errors.py + +用途:校验 Casdoor 登录/改密错误文本到稳定 AppError 的映射。 +依赖:app.api.user 兼容入口中的 _raise_casdoor_* 辅助函数。 +逻辑:覆盖 OAuth 错误、set-password 策略/缺失用户/相同密码/原密码错误。 +""" import pytest from app.api import user as user_api @@ -34,6 +41,26 @@ def test_raise_casdoor_set_password_error_maps_policy(app): assert exc.value.code == 'CASDOOR_PASSWORD_POLICY' +def test_raise_casdoor_set_password_error_maps_same_password(app): + """Casdoor “新密码不能与旧密码相同”不得映射为 401,以免前端清会话。""" + with app.app_context(): + with pytest.raises(user_api.AppError) as exc: + user_api._raise_casdoor_set_password_error( + {'status': 'error', 'msg': 'The new password cannot be the same as the old password'} + ) + assert exc.value.code == 'AUTH.PASSWORD_UNCHANGED' + assert exc.value.http_status == 400 + + +def test_raise_casdoor_set_password_error_maps_incorrect_current_as_business(app): + """原密码错误走业务码 400,禁止 CASDOOR_INVALID_CREDENTIALS 401。""" + with app.app_context(): + with pytest.raises(user_api.AppError) as exc: + user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': 'incorrect current password'}) + assert exc.value.code == 'AUTH.INCORRECT_CURRENT_PASSWORD' + assert exc.value.http_status == 400 + + def test_raise_casdoor_add_user_error_maps_policy(app): with app.app_context(): with pytest.raises(user_api.AppError) as exc: diff --git a/backend/tests/test_change_password.py b/backend/tests/test_change_password.py index 1fbc9b92..25540f74 100644 --- a/backend/tests/test_change_password.py +++ b/backend/tests/test_change_password.py @@ -92,6 +92,34 @@ def test_change_password_local_mode(client): +def test_change_password_rejects_unchanged_password(client): + + """新密码与原密码相同时应 400,且不改哈希。""" + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'old-password', 'new_password': 'old-password'}, + + ) + + assert res.status_code == 400 + + assert (res.get_json() or {}).get('error', {}).get('code') == 'AUTH.PASSWORD_UNCHANGED' + + user = db.session.query(User).filter_by(username='testuser').first() + + assert user.check_password('old-password') + + + + + def test_change_password_local_mode_syncs_casdoor(client, monkeypatch): client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index c46bdf6e..48fc4e51 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -80,7 +80,7 @@ def test_chat_turn_rejects_legacy_fulfillment_action(app, client): "input": { "type": "action", "display_text": "确认", - "action_type": "shipping.submit_decision", + "action_type": "shipping.match_inventory", "payload": {"task_no": task_no, "decision": "confirm"}, }, }, @@ -128,7 +128,7 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client): "input": { "type": "action", "display_text": "确认", - "action_type": "shipping.submit_decision", + "action_type": "shipping.match_inventory", "payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"}, }, }, diff --git a/backend/tests/test_crane_navigation.py b/backend/tests/test_crane_navigation.py index 7c8f7fc6..82523458 100644 --- a/backend/tests/test_crane_navigation.py +++ b/backend/tests/test_crane_navigation.py @@ -10,7 +10,7 @@ import pytest def _load_navigation(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py" spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index b52a4819..4daaa733 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -10,7 +10,7 @@ import pytest def _load_export(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py" spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) @@ -106,13 +106,14 @@ def test_export_scheduled_report_flow(monkeypatch): def _download(*args, **kwargs): calls.append("download") captured["download_description"] = kwargs.get("description", "") + captured["download_dir"] = kwargs.get("download_dir", "") return "download-object" monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download) result = module.export_crane_inventory_report( page, - {"parameters": [], "source_code": "CRANE_TZR2"}, + {"parameters": [], "source_code": "CRANE_TZR2", "__download_dir": "D:/tmp/crane-drop"}, trigger={"task_no": "SN-1001"}, env=lambda name, default="": default, browser_timeout_ms=5_000, @@ -124,6 +125,7 @@ def test_export_scheduled_report_flow(monkeypatch): assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"] assert captured["description"] == "HXOPS-CRANE_TZR2-TEST" assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST" + assert captured["download_dir"] == "D:/tmp/crane-drop" def test_should_run_report_before_schedule_uses_driver_environment_only(): @@ -443,3 +445,154 @@ def test_resolve_download_mode_uses_driver_environment_only(): module = _load_export() assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report" assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download" + + +def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch): + """ + expect_download 超时后,应短窗口扫描 downloads_path 并返回目录文件适配器。 + 断言意图:主路径事件丢失时复用 DSV 同款兜底,而不是直接失败。 + """ + module = _load_export() + page = MagicMock() + locator = MagicMock() + fallback = MagicMock() + fallback.suggested_filename = "OnHandDetails.xlsx" + fallback_calls: list[dict] = [] + + class _TimeoutDownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + if exc_type is not None: + return False + raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"') + + @property + def value(self): + raise AssertionError("download event should not resolve") + + page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", locator), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True) + + def _fake_wait(*, download_dir, baseline_names, timeout_seconds): + fallback_calls.append( + { + "download_dir": str(download_dir), + "baseline_names": set(baseline_names), + "timeout_seconds": timeout_seconds, + } + ) + return fallback + + monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait) + + result = module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + expected_report_name="OnHandDetails.xlsx", + download_dir=str(tmp_path), + ) + + assert result is fallback + assert fallback_calls == [ + { + "download_dir": str(tmp_path), + "baseline_names": set(), + "timeout_seconds": module._CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS, + } + ] + + +def test_wait_and_click_scheduled_download_reraises_when_fallback_misses(tmp_path, monkeypatch): + """ + expect_download 超时且目录无新文件时,应继续抛出原超时。 + 断言意图:兜底失败不能吞掉异常。 + """ + module = _load_export() + page = MagicMock() + + class _TimeoutDownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + if exc_type is not None: + return False + raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"') + + page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", MagicMock()), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True) + monkeypatch.setattr(module, "_wait_for_new_download_file", lambda **_k: None) + + with pytest.raises(TimeoutError, match="download"): + module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + download_dir=str(tmp_path), + ) + + +def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_path, monkeypatch): + """ + Download 链接点击失败时不应进入目录兜底。 + 断言意图:避免点击失败后空等 15s。 + """ + module = _load_export() + page = MagicMock() + fallback_called = {"value": False} + + class _DownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + @property + def value(self): + raise AssertionError("should not reach download value") + + page.expect_download.side_effect = lambda timeout=None: _DownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", MagicMock()), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: False) + + def _fake_wait(**_kwargs): + fallback_called["value"] = True + return MagicMock() + + monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait) + + with pytest.raises(RuntimeError, match="Download link click failed"): + module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + download_dir=str(tmp_path), + ) + assert fallback_called["value"] is False diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py index 090f4b52..f6e3c398 100644 --- a/backend/tests/test_crane_session.py +++ b/backend/tests/test_crane_session.py @@ -8,7 +8,7 @@ from unittest.mock import MagicMock def _load_crane_session(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py" spec = importlib.util.spec_from_file_location("crane_session_test", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) @@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): def test_ensure_crane_session_skips_login_when_session_active(monkeypatch): """batch 内 session 有效时不应重复 goto + login。""" - worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py" + worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path) assert spec and spec.loader worker = importlib.util.module_from_spec(spec) diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 644d0c9e..eae5a371 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -7,7 +7,7 @@ from pathlib import Path def _load_module(): - path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "dsv_report_parameters.py" + path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py" spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index 2dca8f2a..538c05c2 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -430,3 +430,248 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers(): html_tables=['''
PO#MPNReservation ID
4518838154B3-AR1000270A14000111701
'''], ) assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']} + + +def test_email_supplement_inventec_po_date_two_digit_year_keeps_source_location(): + """Inventec 分配表 PO Date=12-Jun-26 时仍须保留 Source Location / 预约号。 + + 回归:order_date 别名命中 PO date 后,两位年英文月曾整行 fail-closed, + 导致 inventory_source_hint 与 External reservation ID 同时落空。 + """ + schema = { + 'fields': [ + { + 'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', + 'aliases': ['PO number', 'PO Number'], + }, + { + 'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', + 'value_type': 'date', 'aliases': ['PO Date', 'Order Date'], + }, + { + 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', + 'aliases': ['MPN'], + }, + { + 'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', + 'aliases': ['External reservation ID'], + }, + { + 'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', + 'aliases': ['Source Type', 'Source Location'], + }, + ], + } + html = ''' + + + + + +
External reservation IDSource typeSource LocationMPNPO datePO number
3000099143DBS SINVMI-SIND4-AR1200163A112-Jun-264518814838
''' + + supplement = parse_email_allocation_tables( + content_hash='i' * 64, html_tables=[html], schema_definition=schema, + ) + + # 关键断言:补充行必须产出;库存源按别名优先级取 Source Type;预约号与 PO 日期均保留。 + assert supplement['rows'], supplement + row = supplement['rows'][0] + assert row['customer_po_number'] == '4518814838' + assert row['reservation_id'] == '3000099143' + assert row['inventory_source_hint'] == 'DBS SIN' + assert row['order_date'].isoformat() == '2026-06-12' + assert 'email_supplement_field_invalid' not in supplement['issues'] + + +def test_email_supplement_skips_invalid_optional_field_without_dropping_row(): + """可选列非法时只跳过该列,不得丢弃同行走的库存源线索。""" + schema = { + 'fields': [ + { + 'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', + 'aliases': ['PO Number'], + }, + { + 'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', + 'value_type': 'date', 'aliases': ['PO Date'], + }, + { + 'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', + 'aliases': ['Source Location'], + }, + ], + } + html = ''' +
PO NumberPO DateSource Location
4518814838not-a-dateVMI-SIN
''' + + supplement = parse_email_allocation_tables( + content_hash='j' * 64, html_tables=[html], schema_definition=schema, + ) + + # 关键断言:日期列记 invalid,但行仍保留 PO 与库存源线索。 + assert supplement['issues'] == ['email_supplement_field_invalid'] + assert len(supplement['rows']) == 1 + assert supplement['rows'][0]['customer_po_number'] == '4518814838' + assert supplement['rows'][0]['inventory_source_hint'] == 'VMI-SIN' + assert 'order_date' not in supplement['rows'][0] + + +def test_email_supplement_uses_only_first_valid_allocation_table(): + """同行身份键以靠前新表为准,旧表同键单价不得制造冲突。 + + 回归:Inventec 修订邮件顶部表 U/P=563.79,引用区旧表 U/P=450.8300; + 同 reservation 只保留新价。 + """ + schema = { + 'fields': [ + { + 'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', + 'aliases': ['PO number', 'PO Number'], + }, + { + 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', + 'aliases': ['MPN'], + }, + { + 'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', + 'value_type': 'decimal', 'aliases': ['U/P', 'Unit Price'], + }, + { + 'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', + 'aliases': ['External reservation ID'], + }, + ], + } + latest = ''' +
External reservation IDMPNPO numberU/P
3000099143D4-AR1200163A14518814838563.79
''' + quoted = ''' +
External reservation IDMPNPO numberU/P
3000099143D4-AR1200163A14518814838450.8300
''' + + supplement = parse_email_allocation_tables( + content_hash='k' * 64, + html_tables=[latest, quoted, '
'], + schema_definition=schema, + ) + + # 关键断言:同 reservation 只留新表行;旧表被 supersede。 + assert len(supplement['rows']) == 1 + assert supplement['rows'][0]['table_index'] == 0 + assert str(supplement['rows'][0]['unit_price']) == '563.79' + assert 'email_supplement_older_row_superseded' in supplement['issues'] + + order = { + '_hxops_intake_id': 1, + 'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518814838'}]}], + 'lines': [{'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-AR1200163A1'}]}, + {'field_id': 'price', 'observations': [{'value': '563.79'}]}, + ]}], + 'conflicts': [], + } + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: {**supplement, 'document_id': 44}}, + schema_definition=schema, + )[0] + assert not any(item.get('field') == 'unit_price' for item in merged.get('conflicts') or []) + assert _value(merged['lines'][0]['fields'], 'price') == '563.79' + + +def test_email_supplement_partial_revision_keeps_unrevised_old_rows(): + """新表只修正一行时,旧表中未覆盖的其它行仍须保留。""" + schema = { + 'fields': [ + { + 'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', + 'aliases': ['PO Number'], + }, + { + 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', + 'aliases': ['MPN'], + }, + { + 'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', + 'value_type': 'decimal', 'aliases': ['U/P'], + }, + { + 'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', + 'aliases': ['External reservation ID'], + }, + ], + } + revised = ''' +
External reservation IDMPNPO NumberU/P
3000099143D4-AR1200163A14518814838563.79
''' + older = ''' + +
External reservation IDMPNPO NumberU/P
3000099143D4-AR1200163A14518814838450.8300
3000099999D4-OTHER00001451881483810.00
''' + + supplement = parse_email_allocation_tables( + content_hash='l' * 64, html_tables=[revised, older], schema_definition=schema, + ) + + # 关键断言:修订行用新价;旧表另一 reservation 行仍在。 + assert len(supplement['rows']) == 2 + by_reservation = {str(row['reservation_id']): row for row in supplement['rows']} + assert str(by_reservation['3000099143']['unit_price']) == '563.79' + assert by_reservation['3000099143']['table_index'] == 0 + assert str(by_reservation['3000099999']['unit_price']) == '10.00' + assert by_reservation['3000099999']['table_index'] == 1 + assert 'email_supplement_older_row_superseded' in supplement['issues'] + + +def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict(): + """邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。 + + 回归:ZNE 邮件正文 PO 表把客户件号(504-006043-001)放进 PN 列并映射到 + `part_number`,而 PDF 同一行的 `part_number` 是内部件号(D4-A08AR12000001)、 + `customer_part_number` 是 504-006043-001。邮件值命中 PDF 的客户件号即同一料号, + 不得判成 `part_number` 的 `supplement_field_conflict`。 + """ + order = _order() # header PO 4518738152;line part D4-A08AR12000002 + order['lines'][0]['fields'].append({ + 'field_id': 'customer-part', 'observations': [{'value': '504-006043-001'}], + }) + supplement = { + 'document_id': 44, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': '504-006043-001', # 邮件 PN 列,实为客户件号(MPN) + 'evidence': {}, + }], + } + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA, + )[0] + # PDF 内部件号保持不变,且不再误判 part_number 冲突 + assert _value(merged['lines'][0]['fields'], 'part') == 'D4-A08AR12000002' + assert not any(item.get('field') == 'part_number' for item in merged['conflicts']) + + +def test_supplement_field_conflict_pdf_string_evidence_ref_does_not_crash(): + """坐标 PDF observation 的 evidence_ref 是字符串时不得崩溃(dict.update length1 回归)。 + + 回归:`_supplement_field_conflict` 曾用 `dict(pdf.get('evidence_ref') or {})` 直接构造证据, + 而坐标 PDF observation 的 `evidence_ref` 是字符串(如 `layout:...:row-7:qty`), + `dict(<字符串>)` 会按字符拆成长度 1 序列 → `dictionary update sequence element #0 has length 1; 2 is required`。 + 修复后改用 observation 的证据 dict(`layout_evidence`,或 `evidence_ref` 为 dict 时用其本身)。 + """ + from app.services.shipping_notice.order_supplement_merge import _supplement_field_conflict + + conflict = _supplement_field_conflict( + field_code='qty', config={'field_id': 'qty', 'field_code': 'qty'}, line_index=0, + pdf_observations=[{ + 'value': '30', 'document_id': 305, + 'evidence_ref': 'layout:305:p1:t1:row-1:qty', # 字符串(坐标 evidence_ref,触发旧崩溃) + 'layout_evidence': {'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty'}, + }], + email_value='99', email_evidence={'table_index': 0, 'row_index': 1}, + email_document_id=44, schema_version='v1', + ) + + assert conflict['conflict_key'] == '0:qty' + # evidence_ref 保持 dict 契约,并取 observation 的证据 dict(layout_evidence) + assert conflict['sources'][0]['evidence_ref'] == { + 'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty', + } + assert conflict['sources'][1]['evidence_ref'] == {'table_index': 0, 'row_index': 1} diff --git a/backend/tests/test_faq_cache.py b/backend/tests/test_faq_cache.py new file mode 100644 index 00000000..50e7713d --- /dev/null +++ b/backend/tests/test_faq_cache.py @@ -0,0 +1,60 @@ +""" +backend/tests/test_faq_cache.py + +用途:FAQ 缓存在线匹配规则。 +逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。 +""" +from app import db +from app.models import Agent, QuickQuestion +from app.services.faq_cache import FaqCacheService + + +def _create_agent() -> Agent: + """写入测试 Agent,供 FAQ 条目关联。""" + agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache') + db.session.add(agent) + db.session.commit() + return agent + + +def _create_faq(agent_id: int, **overrides) -> QuickQuestion: + """写入一条全局 FAQ,默认启用缓存且有标准答案。""" + payload = { + 'user_id': None, + 'agent_id': agent_id, + 'title': '公司的企业文化', + 'question': '公司的企业文化', + 'answer': '客户满意、员工乐意、经营得意', + 'aliases': ['企业文化'], + 'cache_enabled': True, + 'is_enabled': True, + } + payload.update(overrides) + faq = QuickQuestion(**payload) + db.session.add(faq) + db.session.commit() + return faq + + +def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app): + """关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。""" + with app.app_context(): + agent = _create_agent() + _create_faq(agent.id, is_enabled=False) + + hit = FaqCacheService.try_match('公司的企业文化', agent.id) + alias_hit = FaqCacheService.try_match('企业文化', agent.id) + + assert hit is not None + assert hit.answer == '客户满意、员工乐意、经营得意' + assert alias_hit is not None + assert alias_hit.id == hit.id + + +def test_try_match_skips_when_cache_disabled(app): + """仅在首页展示、未启用缓存时,提问仍应回退 Dify。""" + with app.app_context(): + agent = _create_agent() + _create_faq(agent.id, cache_enabled=False, is_enabled=True) + + assert FaqCacheService.try_match('公司的企业文化', agent.id) is None diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 4f241c86..8f87b1bc 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -7,7 +7,7 @@ from pathlib import Path def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract(): """收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text assert 'shipping_receipt_rpa.v1' in text @@ -19,8 +19,8 @@ def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract def test_receipt_crane_driver_forces_inbound_details_match_name(): """收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' - receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8') - crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8') + receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8') + crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8') assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver @@ -28,7 +28,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name(): def test_receipt_crane_driver_forces_inbound_details_entry_route(): """复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' - module_path = root / 'freight_receipt_crane_export.py' + module_path = root / 'receipt' / 'receipt_crane_export.py' sys.path.insert(0, str(root)) spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path) assert spec and spec.loader diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 6acea67e..6004c911 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -13,7 +13,7 @@ def _load_freight_rpa_heartbeat_module(): rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa" if str(rpa_dir) not in sys.path: sys.path.insert(0, str(rpa_dir)) - module_path = rpa_dir / "freight_rpa_heartbeat.py" + module_path = rpa_dir / "common" / "rpa_heartbeat.py" spec = importlib.util.spec_from_file_location("freight_rpa_heartbeat_test", module_path) module = importlib.util.module_from_spec(spec) assert spec.loader is not None diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index c32e2e8a..eda5a638 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -14,6 +14,7 @@ import json import os import re import sys +import time from pathlib import Path import pytest @@ -26,8 +27,8 @@ def _repo_root() -> Path: def _load_freight_rpa_worker(): - module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_under_test", module_path) + module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path) assert spec is not None assert spec.loader is not None module = importlib.util.module_from_spec(spec) @@ -622,6 +623,155 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp assert not log_path.exists() +def _load_worker_disk_cleanup(): + """加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。""" + module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py" + spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + # dataclass 在装饰阶段会查 sys.modules;动态加载须先登记。 + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypatch, tmp_path): + """ + 超过保留期的归档应删除;进行中的 trigger、会话 Profile、cleanup_queue 必须保留。 + + 断言意图:验证磁盘清理只碰“归档/临时物”,不误删业务进行中文件。 + """ + cleanup = _load_worker_disk_cleanup() + now = time.time() + old = now - (10 * 86400) + recent = now - 3600 + + inv_trigger = tmp_path / "inventory_triggers" + upload_trigger = tmp_path / "upload_triggers" + drop = tmp_path / "inventory_drop" + queue = tmp_path / "upload_queue" + profiles = tmp_path / "browser_profile" + logs = tmp_path / "logs" + for path in ( + inv_trigger / "processed", + inv_trigger / "failed", + upload_trigger / "processed", + drop / "processed", + drop / ".hxops_quarantine", + drop / ".cleanup_queue", + drop / ".cleanup_failed", + queue, + profiles, + logs, + ): + path.mkdir(parents=True) + + active_trigger = inv_trigger / "inventory_export_SN-ACTIVE.json" + active_trigger.write_text("{}", encoding="utf-8") + os.utime(active_trigger, (old, old)) + + stale_processed = inv_trigger / "processed" / "inventory_export_SN-OLD.json" + stale_processed.write_text("{}", encoding="utf-8") + os.utime(stale_processed, (old, old)) + + fresh_processed = inv_trigger / "processed" / "inventory_export_SN-NEW.json" + fresh_processed.write_text("{}", encoding="utf-8") + os.utime(fresh_processed, (recent, recent)) + + stale_drop = drop / "processed" / "inventory_OLD.xlsx" + stale_drop.write_bytes(b"xlsx") + os.utime(stale_drop, (old, old)) + + stale_root_drop = drop / "inventory_STALE.xlsx" + stale_root_drop.write_bytes(b"xlsx") + os.utime(stale_root_drop, (old, old)) + + cleanup_job = drop / ".cleanup_queue" / "move_abc.json" + cleanup_job.write_text("{}", encoding="utf-8") + os.utime(cleanup_job, (old, old)) + + stale_queue = queue / "upload_OLD.xlsx" + stale_queue.write_bytes(b"xlsx") + os.utime(stale_queue, (old, old)) + + log_path = logs / "worker.log" + log_path.write_text("current", encoding="utf-8") + stale_backup = Path(f"{log_path}.1") + stale_backup.write_text("old-backup", encoding="utf-8") + os.utime(stale_backup, (old, old)) + + session_profile = profiles / "dsv360__DEFAULT_session" + session_profile.mkdir() + (session_profile / "Cookies").write_text("keep", encoding="utf-8") + os.utime(session_profile, (old, old)) + + orphan_run = profiles / "run_orphan" + orphan_run.mkdir() + (orphan_run / "Cookies").write_text("drop", encoding="utf-8") + os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + + stats = cleanup.run_worker_disk_cleanup( + inventory_trigger_dir=inv_trigger, + upload_trigger_dir=upload_trigger, + drop_dir=drop, + upload_queue_dir=queue, + browser_profile_dir=profiles, + log_file=log_path, + now_unix=now, + ) + + assert not stale_processed.exists() + assert fresh_processed.exists() + assert active_trigger.exists() + assert not stale_drop.exists() + assert not stale_root_drop.exists() + assert cleanup_job.exists() + assert not stale_queue.exists() + assert log_path.exists() + assert not stale_backup.exists() + assert session_profile.exists() + assert not orphan_run.exists() + assert stats.deleted_files >= 4 + assert stats.deleted_dirs >= 1 + + +def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path): + """DISK_RETENTION_DAYS<=0 时不删归档;孤儿 Profile 仍可按独立配置清理。""" + cleanup = _load_worker_disk_cleanup() + now = time.time() + old = now - (10 * 86400) + + inv_trigger = tmp_path / "inventory_triggers" + processed = inv_trigger / "processed" + profiles = tmp_path / "browser_profile" + processed.mkdir(parents=True) + profiles.mkdir(parents=True) + + stale_processed = processed / "old.json" + stale_processed.write_text("{}", encoding="utf-8") + os.utime(stale_processed, (old, old)) + + orphan_run = profiles / "run_orphan" + orphan_run.mkdir() + os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + + cleanup.run_worker_disk_cleanup( + inventory_trigger_dir=inv_trigger, + browser_profile_dir=profiles, + now_unix=now, + ) + + assert stale_processed.exists() + assert not orphan_run.exists() + + def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): """未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。""" worker = _load_freight_rpa_worker() @@ -648,9 +798,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): return _FakePlaywright() monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true") monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False) monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) temp_roots: list[Path] = [] @@ -932,8 +1084,8 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path): worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}}) -def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path): - """DSV 上传须复用登录态打开入口、设置文件,并以 History 绿色回执作为证据返回。""" +def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path): + """DSV 上传须点击 Process File,并以结果页三项判定的证据回传。""" worker = _load_freight_rpa_worker() workbook = tmp_path / "shipment.xlsx" workbook.write_bytes(b"test") @@ -986,10 +1138,10 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path): monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile)) - def fake_history(_page, filename): - return {"reference": "FREIGHT-REF-001", "success_evidence": {"kind": "dsv_history_green_dom", "selector": "em.fa.fa-circle.success-color.status-icon", "filename": filename, "reference": "FREIGHT-REF-001", "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "", "dom_sha256": "abc"}} + def fake_result(_page, filename): + return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "
", "dom_sha256": "abc"}} - monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", fake_history) + monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", fake_result) result = worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={ "connector_type": "dbs", @@ -1001,11 +1153,12 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path): "result_mode": "page_notice", "result_selector": None, "success_texts": [], "timeout_seconds": 120, }, }) - assert result['reference'] == 'FREIGHT-REF-001' - assert result['success_evidence']['kind'] == 'dsv_history_green_dom' + assert result['reference'] == '' + assert result['success_evidence']['kind'] == 'dsv_upload_success_dom' assert events[0] == ("session", "https://s360.dbschenker.com/") assert ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") in events assert ("file", str(workbook)) in events + assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path): @@ -1053,7 +1206,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path): runtime_profile.mkdir() monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile)) - monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}") + monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}}) assert worker._upload_shipment_with_browser( workbook, connector_type="dbs", upload_source={ @@ -1068,12 +1221,52 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path): "success_texts": [], "timeout_seconds": 120, }, } - ) == "REF-shipment.xlsx" + ) == {"reference": "", "success_evidence": {}} assert events[0] == ("session", "https://s360.dbschenker.com/") assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") assert ("file", "#file2") in events - assert ("click", 'button.upload-button:has-text("Process File")') in events + assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events + + +def test_dsv_upload_always_confirms_process_file_after_selecting_file(monkeypatch, tmp_path): + """DSV 选中文件后必须点击 Process File,不能仅凭 set_input_files 视为已上传。""" + worker = _load_freight_rpa_worker() + workbook = tmp_path / "shipment.xlsx" + workbook.write_bytes(b"test") + events: list[tuple[str, object]] = [] + + class _Locator: + def __init__(self, selector: str): + self.selector = selector + self.first = self + + def set_input_files(self, value: str, **_kwargs) -> None: + events.append(("file", value)) + + def click(self, **_kwargs) -> None: + events.append(("click", self.selector)) + + class _Page: + def goto(self, _url: str, **_kwargs) -> None: + return None + + def locator(self, selector: str) -> _Locator: + return _Locator(selector) + + monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: None) + monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda *_args: {"reference": "", "success_evidence": {}}) + worker.DsvUploadAdapter( + file_path=workbook, + upload_config={ + "entry_url": "https://s360.dbschenker.com/upload", + "file_input_selector": "#file2", + "submit_mode": "auto_after_file", + "timeout_seconds": 1, + }, + ).run(_Page(), login_url="https://s360.dbschenker.com/") + + assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch): @@ -1154,6 +1347,48 @@ def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeyp assert evidence["page_url"] +def test_crane_upload_result_requires_processing_and_shipping_order_allocated(): + """Crane 上传成功必须同时满足单号行状态与状态描述。""" + worker = _load_freight_rpa_worker() + + assert worker._crane_upload_result_is_success({ + "found": True, + "order_status": "Processing", + "order_status_description": "Shipping Order Allocated", + }) is True + assert worker._crane_upload_result_is_success({ + "found": True, + "order_status": "Completed", + "order_status_description": "Shipping Order Allocated", + }) is False + assert worker._crane_upload_result_is_success({ + "found": True, + "order_status": "Processing", + "order_status_description": "Allocating the Shipping Order", + }) is False + + +def test_dsv_upload_result_requires_success_button_and_empty_errors(): + """DSV 只有成功按钮且两类错误均为空时才算上传成功。""" + worker = _load_freight_rpa_worker() + + assert worker._dsv_upload_result_is_success({ + "button": "Upload Successful", + "upload_file_errors": "", + "wms_errors": "", + }) is True + assert worker._dsv_upload_result_is_success({ + "button": "Upload Unsuccessful", + "upload_file_errors": "", + "wms_errors": "", + }) is False + assert worker._dsv_upload_result_is_success({ + "button": "Upload Successful", + "upload_file_errors": "Missing column", + "wms_errors": "", + }) is False + + def test_dsv_upload_falls_back_to_apps_menu(monkeypatch): """首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。""" worker = _load_freight_rpa_worker() @@ -1263,7 +1498,7 @@ def test_summarize_inventory_batch_results_all_skipped_is_success(): assert summary["has_success"] is False assert summary["status"] not in {"failed", "partial_failed"} def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path): - """真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。""" + """关闭会话复用时,每次都应在配置目录下生成新的 run_* 临时 profile。""" worker = _load_freight_rpa_worker() observed: dict[str, object] = {} @@ -1288,9 +1523,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat return _FakePlaywright() monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads") @@ -1309,8 +1546,8 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat } -def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path): - """DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。""" +def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monkeypatch, tmp_path): + """会话复用开启时按 connector+rpa_profile 固定目录,且不得当作临时目录清理。""" worker = _load_freight_rpa_worker() observed: dict[str, object] = {} @@ -1334,18 +1571,91 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo return _FakePlaywright() monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, profile_dir = worker._open_browser( - tmp_path / "downloads", reuse_dsv_session=True + tmp_path / "downloads", + reuse_session=True, + connector_type="crane_footprint", + profile_code="CRANE-MAIN", ) assert context is not None assert page is not None - assert profile_dir == tmp_path / "profile" / "dsv360_session" + assert profile_dir == tmp_path / "profile" / "crane_footprint__CRANE-MAIN_session" assert observed["profile"] == str(profile_dir) assert worker._should_cleanup_browser_profile(profile_dir) is False + assert (profile_dir / ".hxops_rpa_session_meta.json").is_file() + + +def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path): + """兼容旧参数 reuse_dsv_session:开启复用时落到 dsv360__* 持久目录。""" + worker = _load_freight_rpa_worker() + observed: dict[str, object] = {} + + class _FakePage: + def set_default_timeout(self, value: int) -> None: + observed["timeout"] = value + + class _FakeContext: + pages = [_FakePage()] + + class _FakeChromium: + def launch_persistent_context(self, profile: str, **kwargs): + observed["profile"] = profile + return _FakeContext() + + class _FakePlaywright: + chromium = _FakeChromium() + + class _FakeStarter: + def start(self): + return _FakePlaywright() + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") + monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) + + _playwright, context, page, profile_dir = worker._open_browser( + tmp_path / "downloads", + reuse_dsv_session=True, + connector_type="dsv360", + profile_code="DSV-A", + ) + + assert context is not None + assert page is not None + assert profile_dir == tmp_path / "profile" / "dsv360__DSV-A_session" + assert observed["profile"] == str(profile_dir) + assert worker._should_cleanup_browser_profile(profile_dir) is False + + +def test_prepare_reusable_session_profile_keeps_existing_dir(tmp_path): + """持久 Profile 不按本地时间清空;已有内容应保留供站点会话继续复用。""" + worker = _load_freight_rpa_worker() + profile_dir = tmp_path / "dsv360__OLD_session" + profile_dir.mkdir(parents=True) + stale_marker = profile_dir / "stale.txt" + stale_marker.write_text("keep-me", encoding="utf-8") + created = time.time() - (25 * 3600) + (profile_dir / ".hxops_rpa_session_meta.json").write_text( + json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}), + encoding="utf-8", + ) + + prepared = worker._prepare_reusable_session_profile( + profile_dir, + connector_type="dsv360", + profile_code="OLD", + ) + + assert prepared == profile_dir + assert stale_marker.exists() + meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8")) + assert float(meta["created_at_unix"]) == created + assert "ttl_hours" not in meta def test_is_dsv_username_page_ignores_login_method_page_text(): @@ -1627,7 +1937,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch): def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch): """登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。""" - module_path = _repo_root() / "scripts" / "rpa" / "dsv_report_export.py" + module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py" spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path) assert spec is not None and spec.loader is not None dsv_report_export = importlib.util.module_from_spec(spec) diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index 7f138151..cc65faaf 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -20,8 +20,21 @@ def _load_dsv_auth_login_flow(): return _load_rpa_module("dsv_auth_login_flow") +_RPA_MODULE_PATHS = { + "freight_rpa_worker": "inventory/inventory_rpa_worker.py", + "inventory_rpa_worker": "inventory/inventory_rpa_worker.py", + "dsv_report_export": "connectors/dsv/dsv_report_export.py", + "dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py", + "dsv_navigation": "connectors/dsv/dsv_navigation.py", + "dsv_auth": "connectors/dsv/dsv_auth.py", + "dsv_session": "connectors/dsv/dsv_session.py", + "dsv_debug": "connectors/dsv/dsv_debug.py", +} + + def _load_rpa_module(module_name: str): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py" + rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py") + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel scripts_dir = str(module_path.parent) if scripts_dir not in sys.path: sys.path.insert(0, scripts_dir) diff --git a/backend/tests/test_gate_derivation.py b/backend/tests/test_gate_derivation.py new file mode 100644 index 00000000..e5c9a034 --- /dev/null +++ b/backend/tests/test_gate_derivation.py @@ -0,0 +1,414 @@ +""" +backend/tests/test_gate_derivation.py + +用途:验收 Gate 推导的粗分类 / 位置 / 待办分类,替代旧 checkpoint_kind。 +依赖:process_gate_contract.derive_*、query_service._todo_category_from_gate、 + ui_state._derived_*、user_facing_status、pytest。 +逻辑:Task1–6 契约纯函数与消费点迁移断言;SQL CASE 双读过渡不在此覆盖。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, +) + + +def test_user_mode_complete_when_rejected(): + assert derive_user_mode( + user_status='completed', + gate_code=None, + review_status='rejected', + lifecycle_stage=None, + ) == 'complete' + + +def test_user_mode_wait_upload_handoff(): + assert derive_user_mode( + user_status='waiting_human', + gate_code='manual_upload_handoff', + review_status=None, + lifecycle_stage='freight_upload', + ) == 'wait_manual_upload' + + +def test_user_mode_must_human(): + assert derive_user_mode( + user_status='waiting_human', + gate_code='inventory_matching', + review_status=None, + lifecycle_stage='fulfillment_prep', + ) == 'must_human' + + +def test_user_mode_auto(): + assert derive_user_mode( + user_status='running', + gate_code='inventory_preparation', + review_status=None, + lifecycle_stage='fulfillment_prep', + ) == 'auto_continue' + + +def test_position_review_dispositions(): + assert derive_position(gate_code=None, review_status='rejected') == 'rejected' + assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue' + assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req' + + +def test_position_fulfillment(): + assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending' + assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready' + + +def test_todo_category(): + assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review' + assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception' + assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload' + assert derive_todo_category(user_mode='complete') == 'done' + assert derive_todo_category(user_mode='auto_continue') == 'in_progress' + + +def test_fetch_gate_positions_empty(): + from app.services.shipping_notice.query_service import fetch_gate_positions + + assert fetch_gate_positions([]) == {} + + +def test_fetch_gate_positions_batched(app): + """关键断言:一次查询按 task_id 返回 current_gate_code / status。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import fetch_gate_positions + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='GATE-POS') + ot_a = ShippingOrderTask( + task_no='OT-GATE-POS-A', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='step5_match_inventory', + progress_version=1, + ) + ot_b = ShippingOrderTask( + task_no='OT-GATE-POS-B', + user_id=user.id, + conversation_id=session.session_id, + status='processing', + stage='inventory_fetching', + progress_version=1, + ) + db.session.add_all([ot_a, ot_b]) + db.session.flush() + db.session.add_all([ + ShippingProcessExecution( + execution_no='SPE-GATE-POS-A', + task_id=int(ot_a.id), + status='blocked', + current_gate_code='inventory_sufficiency', + ), + ShippingProcessExecution( + execution_no='SPE-GATE-POS-B', + task_id=int(ot_b.id), + status='active', + current_gate_code='inventory_preparation', + ), + ]) + db.session.commit() + + result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999]) + assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency' + assert result[int(ot_a.id)]['status'] == 'blocked' + assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation' + assert 999999 not in result + + +def test_early_stop_uses_derive_user_mode(monkeypatch): + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'SN-1' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_gate': { + 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_shortage_review_required', + 'gate_code': 'inventory_sufficiency', + }, + 'responsible_party': 'owner', + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_sufficiency', + 'status': 'blocked', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'must_human' + + +def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch): + """ + 回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为 + blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停, + 否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。 + """ + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'OT-INV-EMPTY' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_file_empty', + 'gate_code': 'inventory_preparation', + }, + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_file_empty', + 'gate_code': 'inventory_preparation', + }, + 'responsible_party': 'worker', + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_preparation', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_file_empty', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'auto_continue' + + +def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch): + """RPA 耗尽属 needs_human,入口仍须早停,不能自动空转重试。""" + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'OT-INV-EXHAUSTED' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_rpa_exhausted', + 'gate_code': 'inventory_preparation', + }, + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_preparation', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_rpa_exhausted', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'must_human' + + +def test_position_inventory_sufficiency(): + assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review' + + +def test_todo_category_from_gate_positions(): + from app.services.shipping_notice.query_service import _todo_category_from_gate + + assert ( + _todo_category_from_gate( + {'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'}, + None, + ) + == 'review' + ) + assert ( + _todo_category_from_gate( + {'current_gate_code': 'inventory_preparation', 'status': 'active'}, + None, + ) + == 'in_progress' + ) + assert ( + _todo_category_from_gate( + {'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'}, + None, + ) + == 'exception' + ) + + +def test_user_facing_stage_uses_position(monkeypatch): + from app.services.shipping_notice import user_facing_status as ufs + + class FakeTask: + step_payload_json = {} + pending_human_reason = None + lifecycle_status = 'active' + review_status = None + order_task_id = None + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + lambda t: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: {'current_gate_code': 'inventory_preparation'}, + ) + assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存' + + +def test_derived_entry_surface_review(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + + assert ( + _derived_entry_surface( + gate_code='order_field_extraction', + review_status='parse_review', + user_mode='must_human', + ) + == 'review_workbench' + ) + + +def test_derived_entry_surface_task(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + + assert ( + _derived_entry_surface( + gate_code='artifact_generation', + review_status=None, + user_mode='wait_manual_upload', + ) + == 'task_workbench' + ) + + +def test_summary_prefers_gate_shortage_over_freeze(monkeypatch): + """关键断言:Gate 短缺时摘要不再沿用 OT 默认 order_freeze 文案。""" + from app.services.shipping_notice import ui_state as us + + class FakeTask: + task_no = 'OT-SHORT' + review_status = None + order_task_id = None + updated_at = None + error_message = None + step_payload_json = {} + + monkeypatch.setattr(us, '_build_stp_facts', lambda t: None) + monkeypatch.setattr(us, '_collect_parse_stage_issues', lambda *a, **k: []) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + lambda t: 'inventory_shortage_review_required', + ) + monkeypatch.setattr(us, 'user_facing_task_stage', lambda t: '库存不足,无法发货') + monkeypatch.setattr( + 'app.services.shipping_notice.stp_progress_contract.project_task_progress_nodes', + lambda t: [], + ) + summary = us._build_task_summary( + FakeTask(), + 'shortage_review', + user_mode='must_human', + gate_code='inventory_sufficiency', + ) + assert '缺口' in summary['message'] or '库存' in summary['message'] + assert summary['user_mode'] == 'must_human' + assert summary['entry_surface'] == 'task_workbench' + assert summary['next_auto_step'] is None + + +def test_rejected_maps_to_review_disposition(): + assert derive_position(gate_code=None, review_status='rejected') == 'rejected' + + +def test_notice_text_failure_maps_to_quality_issue(): + assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue' + + +def test_sql_todo_category_prefers_gate_inventory_sufficiency(app): + """关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE') + ot = ShippingOrderTask( + task_no='OT-SQL-GATE-SHORT', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='step5_match_inventory', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-GATE-SHORT', + task_id=int(ot.id), + status='blocked', + current_gate_code='inventory_sufficiency', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'exception' + + +def test_sql_todo_category_prefers_gate_manual_upload(app): + """关键断言:manual_upload_handoff → manual_upload。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE-MU') + ot = ShippingOrderTask( + task_no='OT-SQL-GATE-MU', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_upload', + stage='freight_upload', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-GATE-MU', + task_id=int(ot.id), + status='blocked', + current_gate_code='manual_upload_handoff', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'manual_upload' + + +def test_user_mode_review_status_must_human(): + """复核处置 review_status 在默认 auto 之前映射为 must_human。""" + for rs in ('parse_review', 'rsv_req', 'quality_issue', 'customer_review', 'shortage_review'): + assert derive_user_mode( + user_status='running', + gate_code=None, + review_status=rs, + lifecycle_stage=None, + ) == 'must_human' diff --git a/backend/tests/test_integration_connector_columns_migration.py b/backend/tests/test_integration_connector_columns_migration.py new file mode 100644 index 00000000..f629302b --- /dev/null +++ b/backend/tests/test_integration_connector_columns_migration.py @@ -0,0 +1,48 @@ +""" +backend/tests/test_integration_connector_columns_migration.py + +用途:验证集成连接器"关键字段拆列"迁移的版本链与新增/回滚列清单。 +依赖:新增迁移模块、pytest monkeypatch。 +逻辑:拦截 add_column/drop_column,确认三个表各加/删目标列;确认 down_revision 承接当前 head。 +""" + +from __future__ import annotations + +from typing import Any + +MIGRATION_REV = "ix1a2b3c4d5e_split_integration_connector_columns" + +COLUMN_TARGETS: list[tuple[str, str]] = [ + ("integration_client_instances", "endpoint"), + ("integration_client_instances", "timeout_seconds"), + ("integration_interface_definitions", "http_method"), + ("integration_interface_definitions", "request_path"), + ("integration_bindings", "context_source_code"), +] + + +def test_integration_connector_column_migration_adds_columns(monkeypatch): + """迁移应承接 head iy1a2b3c4d5e,并对三张表加关键字段列。""" + import importlib + + module = importlib.import_module(f"migrations.versions.{MIGRATION_REV}") + add_calls: list[tuple[str, str]] = [] + drop_calls: list[tuple[str, str]] = [] + + def capture_add(table_name: str, column: Any, **_: Any) -> None: + add_calls.append((table_name, getattr(column, "name", column))) + + def capture_drop(table_name: str, column_name: Any, **_: Any) -> None: + drop_calls.append((table_name, getattr(column_name, "name", column_name))) + + monkeypatch.setattr(module.op, "add_column", capture_add) + monkeypatch.setattr(module.op, "drop_column", capture_drop) + + module.upgrade() + assert module.down_revision == "iy1a2b3c4d5e" + for target in COLUMN_TARGETS: + assert target in add_calls + + module.downgrade() + for target in COLUMN_TARGETS: + assert target in drop_calls diff --git a/backend/tests/test_inventory_poll_failure_semantics.py b/backend/tests/test_inventory_poll_failure_semantics.py new file mode 100644 index 00000000..9156e02c --- /dev/null +++ b/backend/tests/test_inventory_poll_failure_semantics.py @@ -0,0 +1,203 @@ +"""inventory 只读轮询失败语义(P1)单测。 + +锁定契约:poll_inventory_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed +Attempt)时—— +1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable), + 而非 needs_human 伪装的人工阻断; +2. Gate 收口为 blocked_retryable,next_action 保留用户显式重试入口; +3. 全链路不新建任何 RPA Attempt(轮询零写入)。 + +迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源 +ShippingTaskInventoryRpaAttempt;任务加载与冻结候选源均按 OT 口径构造。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ( + ShippingOrderTask, + ShippingProcessGateAttempt, + ShippingTaskInventoryRpaAttempt, + User, +) +from app.services.shipping_notice import per_source_rpa_service +from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa +from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through +from app.services.shipping_notice.process_gate_executor import execute_queued_attempt +from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + queue_gate_attempt, +) +from tests.test_shipping_process_gate_service import _seed_workflow_version + + +def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') -> None: + """写入一条已被超时扫描收口的逐源 RPA Attempt(模拟 Worker 离线场景)。""" + db.session.add(ShippingTaskInventoryRpaAttempt( + task_no=task_no, + source_code=source_code, + attempt_no=1, + source_run_no=f'RUN-{task_no}-1', + status='failed', + error_code='rpa_timeout', + error_message='Attempt 已排队 941s,但 Trigger 文件不存在,Worker 未领取', + lease_token='lease-p1', + execution_phase='timeout_failed', + extra_json={'trigger_mode': 'auto'}, + )) + db.session.commit() + + +def _rpa_attempt_count(task_no: str) -> int: + return ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task_no).count() + + +@pytest.fixture() +def poll_ready_task(app): + """真实 ShippingOrderTask:库存源已冻结(单源 DSV360_AWSDU),用于 via_rpa 层真实链路。""" + with app.app_context(): + db.session.add(User( + username='poll-fail-owner', + email='poll-fail-owner@example.com', + password_hash='x', + )) + db.session.flush() + user_id = db.session.query(User.id).filter_by(username='poll-fail-owner').scalar() + task = ShippingOrderTask( + task_no='OT-POLL-FAIL-SEMANTICS', + user_id=int(user_id), + source_type='direct_pdf', + ) + db.session.add(task) + db.session.commit() + yield task + + +def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch, poll_ready_task): + """[断言] allow_auto_retry=False(poll 查询路径)遇 failed Attempt:返回 status='failed' + 而非 needs_human,且不新建 RPA Attempt;默认路径(显式重试/首次投递)保持 needs_human。""" + with app.app_context(): + task = db.session.get(ShippingOrderTask, int(poll_ready_task.id)) + _seed_failed_rpa_attempt(task.task_no) + + # 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。 + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.task_execution_block_reason', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.customer_gate_tool_response', + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.field_conflict_gate_response', + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.task_reservation_gate_issues', + lambda _task: [], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.assert_inventory_source_gate', + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.task_rpa_inventory_source', + lambda _task: {'source_code': 'DSV360_AWSDU'}, + ) + # 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。 + monkeypatch.setattr( + per_source_rpa_service, + 'task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU'], + ) + # 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失 + # 快照/订单字段时被投影逻辑干扰。 + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.serialize_task_for_tool', + lambda _task: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.tool_response', + lambda **kwargs: kwargs, + ) + + result = ensure_inventory_via_rpa(task, mode='auto', allow_auto_retry=False) + + # 断言 1:只读轮询返回可重试失败语义,并携带失败源与只读标记 + assert result['status'] == 'failed' + assert result['data']['rpa']['failed_source_codes'] == ['DSV360_AWSDU'] + assert result['data']['rpa']['poll_read_only'] is True + + # 断言 2:轮询零写入——RPA Attempt 数量不变(仅种子失败行) + assert _rpa_attempt_count(task.task_no) == 1 + + # 断言 3:自动路径仍收口为失败,且不会为 failed Attempt 创建下一次 RPA。 + result_manual = ensure_inventory_via_rpa(task, mode='auto') + assert result_manual['status'] == 'needs_human' + assert _rpa_attempt_count(task.task_no) == 1 + + +def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch): + """[断言] Gate poll 透传只读开关,并把 failed RPA 结果收口为 blocked_retryable。 + + 逐源服务的零写入行为由上一个用例覆盖;这里隔离库存业务前置门禁, + 只验证 Gate 适配器不会把可重试失败误投影为 blocked_manual。 + """ + _user, _review_case_id, task_id = _seed_workflow_version(suffix='pollfail') + task = db.session.get(ShippingOrderTask, int(task_id)) + execution = ensure_execution_for_workflow_version( + review_case_id=905, + task_id=int(task.id), + ) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_source_routing', + reason='test_poll_failure_semantics', + ) + _seed_failed_rpa_attempt(task.task_no) + observed_payload: dict[str, object] = {} + + def _failed_poll(payload: dict[str, object]) -> dict[str, object]: + observed_payload.update(payload) + return { + 'status': 'failed', + 'message': '库存 RPA 未能为全部库存源生成结果。', + 'data': {'rpa': {'failed_source_codes': ['DSV360_AWSDU']}}, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + _failed_poll, + ) + + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + trigger_type='system_requeue', + actor_type='system', + actor_id='poll-p1', + idempotency_key='poll-fail-semantics-1', + input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}}, + ) + db.session.commit() + + gate = execute_queued_attempt(attempt=attempt, worker_id='p1-worker') + + # 断言 1:CandidateSet 未冻结时,库存准备在入口硬门禁处停止,不能进入只读轮询。 + # 这比把 routing 缺失伪装成库存 RPA 失败更准确,也确保不会旁路创建/消费 Attempt。 + assert 'allow_auto_retry' not in observed_payload + assert gate.status == 'blocked_retryable' + assert gate.next_action_code == 'retry_inventory_preparation' + assert gate.blocking_reason_code == 'inventory_source_routing_required' + + # 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族) + db.session.expire_all() + attempt_final = db.session.get(ShippingProcessGateAttempt, int(attempt.id)) + assert attempt_final is not None + assert attempt_final.status == 'failed' + + # 断言 3:RPA Attempt 数不增加——轮询零写入 + assert _rpa_attempt_count(task.task_no) == 1 diff --git a/backend/tests/test_inventory_poll_read_only.py b/backend/tests/test_inventory_poll_read_only.py new file mode 100644 index 00000000..c7666828 --- /dev/null +++ b/backend/tests/test_inventory_poll_read_only.py @@ -0,0 +1,166 @@ +"""inventory 只读轮询(A1)单测。 + +覆盖 ensure_all_required_sources_prepared 的 allow_auto_retry 开关: +1. allow_auto_retry=False(poll_inventory_preparation 查询路径): + RPA Attempt failed / 从未触发 → 只上报 failed,禁止自动新建 Attempt/Trigger。 +2. allow_auto_retry=False + queued → 仍视为 pending(轮询语义保持)。 +3. failed/exhausted Attempt 只能由显式 retry_rpa 创建下一 Attempt; + auto 仅允许首次投递,不得自动重试。 +""" + +from types import SimpleNamespace + +import pytest + +from app import db +from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt +from app.services.shipping_notice import per_source_rpa_service + + +def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> ShippingTaskInventoryRpaAttempt: + """在测试库写入一条真实逐源 Attempt,供 _latest_attempt / FOR UPDATE 复检读取。""" + att = ShippingTaskInventoryRpaAttempt( + task_no=task_no, + source_code='SRC_A', + attempt_no=attempt_no, + source_run_no=f'RUN-{task_no}-{attempt_no}', + status=status, + triggered_at=db.session.query(db.func.now()).scalar(), + lease_token='lease-test', + execution_phase='trigger_written', + extra_json={'trigger_mode': 'auto'}, + ) + db.session.add(att) + db.session.commit() + return att + + +@pytest.fixture() +def poll_task(app): + """构造一个极简 ShippingNotice 行,task_no 仅供 Attempt 归属查询使用。""" + with app.app_context(): + task = ShippingNotice(task_no='SN-POLL-READ-ONLY') + db.session.add(task) + db.session.commit() + yield task + + +def _patch_common(monkeypatch, *, snapshot_ready=False): + """统一 monkeypatch:单候选源 + 快照未就绪;Attempt 走真实表。""" + monkeypatch.setattr( + per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A'] + ) + monkeypatch.setattr( + per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: snapshot_ready + ) + + +def test_poll_read_only_reports_failed_without_new_attempt(monkeypatch, app, poll_task): + """[断言] 只读轮询遇 failed Attempt:源进入 failed 列表、不新建 Attempt、不写 trigger。""" + _patch_common(monkeypatch) + _seed_attempt(poll_task.task_no, status='failed') + + def _forbidden_batch_writer(*args, **kwargs): + raise AssertionError('只读轮询不得写入 RPA trigger 文件') + + monkeypatch.setattr( + per_source_rpa_service, 'write_inventory_export_batch_trigger', _forbidden_batch_writer + ) + + result = per_source_rpa_service.ensure_all_required_sources_prepared( + poll_task, mode='auto', allow_auto_retry=False + ) + + # 断言:failed 事实被上报,且没有任何新 Attempt 落库 + assert result.failed_source_codes == ['SRC_A'] + assert result.pending_source_codes == [] + assert result.prepared_source_codes == [] + assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1 + + +def test_poll_read_only_keeps_pending_for_active_attempt(monkeypatch, app, poll_task): + """[断言] 只读轮询遇 queued Attempt:维持 pending 轮询语义,不新建 Attempt。""" + _patch_common(monkeypatch) + _seed_attempt(poll_task.task_no, status='queued') + monkeypatch.setattr( + per_source_rpa_service, 'write_inventory_export_batch_trigger', + lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')), + ) + + result = per_source_rpa_service.ensure_all_required_sources_prepared( + poll_task, mode='auto', allow_auto_retry=False + ) + + assert result.pending_source_codes == ['SRC_A'] + assert result.failed_source_codes == [] + assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1 + + +def test_poll_read_only_reports_failed_when_never_attempted(monkeypatch, app, poll_task): + """[断言] 只读轮询遇从未触发的源:不代为首次触发,按 failed 上报交由用户决策。""" + _patch_common(monkeypatch) + monkeypatch.setattr( + per_source_rpa_service, 'write_inventory_export_batch_trigger', + lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')), + ) + + result = per_source_rpa_service.ensure_all_required_sources_prepared( + poll_task, mode='auto', allow_auto_retry=False + ) + + assert result.failed_source_codes == ['SRC_A'] + assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0 + + +@pytest.mark.parametrize('status', ['failed', 'exhausted']) +def test_auto_does_not_retry_terminal_attempt(monkeypatch, app, poll_task, status): + """[断言] auto 遇 failed/exhausted Attempt 只上报失败,绝不写入下一次 Attempt/Trigger。""" + _patch_common(monkeypatch) + _seed_attempt(poll_task.task_no, status=status) + monkeypatch.setattr( + per_source_rpa_service, 'write_inventory_export_batch_trigger', + lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('auto 不得重试 RPA')), + ) + + result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='auto') + + assert result.failed_source_codes == ['SRC_A'] + assert result.pending_source_codes == [] + assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1 + + +def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task): + """[断言] 只有用户显式 retry_rpa 能把 failed Attempt 投递为下一次 queued Attempt。 + + 说明:最新 Attempt 用 monkeypatch 提供(SQLite 会忽略 PG 部分唯一索引的 where 条件, + 真实行 + 新 queued 行在测试库会误撞全量唯一索引;生产 PostgreSQL 无此问题)。""" + monkeypatch.setattr( + per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A'] + ) + monkeypatch.setattr( + per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False + ) + monkeypatch.setattr( + per_source_rpa_service, + '_latest_attempt', + lambda *args, **kwargs: SimpleNamespace( + id=1, status='failed', attempt_no=1, run_no='RUN-FAILED-1', + error_code=None, error_message=None, + ), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda task: {'source_code': 'SRC_A'}, + ) + monkeypatch.setattr( + per_source_rpa_service, 'write_inventory_export_batch_trigger', + lambda run_no, sources, payload=None: 'trigger/batch.json', + ) + + result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='retry_rpa') + + assert result.pending_source_codes == ['SRC_A'] + attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).all() + assert len(attempts) == 1 + assert attempts[0].status == 'queued' + assert attempts[0].attempt_no == 1 diff --git a/backend/tests/test_order_document_profile_creation_service.py b/backend/tests/test_order_document_profile_creation_service.py index fe09beeb..1dc2b477 100644 --- a/backend/tests/test_order_document_profile_creation_service.py +++ b/backend/tests/test_order_document_profile_creation_service.py @@ -14,6 +14,8 @@ import pytest from app.extensions import db from app.models import ( + FileAsset, + ShippingOrderDocument, ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, ShippingOrderDocumentProfileDraftRevision, @@ -59,6 +61,9 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi assert created['definition']['main_table_id'] == 'sample-table' assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1 assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1 + asset = db.session.get(FileAsset, db.session.get(ShippingOrderDocument, sample.document_id).asset_id) + assert asset.lifecycle_status == 'referenced' + assert int(asset.reference_count or 0) >= 1 assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1 assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1 assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1 diff --git a/backend/tests/test_order_document_profile_overlap_summary.py b/backend/tests/test_order_document_profile_overlap_summary.py index 0e94d082..788a0ba2 100644 --- a/backend/tests/test_order_document_profile_overlap_summary.py +++ b/backend/tests/test_order_document_profile_overlap_summary.py @@ -7,8 +7,13 @@ tests/test_order_document_profile_overlap_summary.py """ from __future__ import annotations -from app.services.shipping_notice.order_document_profile_validation_service import build_cross_template_overlap_summary -from app.services.shipping_notice.order_document_profile_validation_service import _evaluate_self_sample_match +from types import SimpleNamespace + +from app.services.shipping_notice.order_document_profile_validation_service import ( + build_cross_template_overlap_summary, + published_rival_snapshots_for_overlap, + _evaluate_self_sample_match, +) from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchCandidate, ProfileMatchResult, @@ -75,3 +80,24 @@ def test_overlap_ignores_ineligible_candidate_when_unique_match_has_no_eligible_ assert outcome['self_unique'] is True assert outcome['margin'] == 1.0 assert outcome['margin_ok'] is True + + +def test_published_rival_snapshots_exclude_same_profile_code(monkeypatch): + """同模板族旧 published 版不得进入跨模板冲突候选池。""" + from app.services.shipping_notice import order_document_profile_service as profile_service + + monkeypatch.setattr( + profile_service, + 'published_snapshots_for_schema', + lambda _schema_id: [ + {'profile_code': 'ODP-SELF', 'version': 1}, + {'profile_code': 'ODP-SELF', 'version': 2}, + {'profile_code': 'ODP-OTHER', 'version': 1}, + ], + ) + profile = SimpleNamespace(profile_code='ODP-SELF', schema_version_id=1, version=3) + + rivals = published_rival_snapshots_for_overlap(profile) + + assert [item['profile_code'] for item in rivals] == ['ODP-OTHER'] + assert all(item['profile_code'] != 'ODP-SELF' for item in rivals) diff --git a/backend/tests/test_order_document_profile_preview_service.py b/backend/tests/test_order_document_profile_preview_service.py index ba19c61b..be6f1402 100644 --- a/backend/tests/test_order_document_profile_preview_service.py +++ b/backend/tests/test_order_document_profile_preview_service.py @@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_preview_service.py from __future__ import annotations +import gzip +import json from types import SimpleNamespace import numpy as np @@ -15,7 +17,13 @@ import pytest from app import db from app.core.auth.jwt import issue_local_access_token -from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User +from app.models import ( + FileAsset, + ShippingDocumentLayoutVersion, + ShippingOrderDocumentProfileSample, + ShippingOrderDocument, + User, +) from app.services.shipping_notice import document_profile_quality_service as quality_service from app.services.shipping_notice import order_document_profile_preview_service as preview_service from app.services.shipping_notice import order_document_profile_service as profile_service @@ -120,6 +128,62 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND' +def test_frozen_sample_preview_recovers_legacy_table_page_count_when_frozen_evidence_has_all_pages( + app, monkeypatch, admin_headers_factory, +): + """历史快照把页数误记为表格页数时,仅可由同一冻结证据中的完整物理页数修复预览。""" + with app.app_context(): + monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None) + schema = _schema_version() + draft = profile_service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample( + draft['id'], + sample_role='annotation', + physical_page_count=2, + include_top_level_pages=False, + ) + published = profile_service.publish( + draft['id'], actor_id=None, expected_lock_version=draft['lock_version'], + ) + profile_id = int(published['id']) + sample_id = int(sample.id) + # 模拟修复上线前已发布的历史记录:页数被退化为仅第一页业务表。 + sample.page_count_snapshot = 1 + layout_version = db.session.get(ShippingDocumentLayoutVersion, sample.layout_version_id) + evidence_ref = (layout_version.payload_json or {}).get('coordinate_evidence_ref') + assert isinstance(evidence_ref, dict) + evidence_asset_no = str(evidence_ref['asset_no']) + db.session.commit() + + preview_store = _PreviewStore() + monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store) + coordinate_evidence_bytes = gzip.compress(json.dumps({ + 'pages': {'1': {'width': 200, 'height': 100}, '2': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]}, + 'tables': {'sample-table': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]}, + }).encode('utf-8')) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', + lambda asset: coordinate_evidence_bytes if asset.asset_no == evidence_asset_no else b'%PDF-frozen-preview', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content, render_scale: [ + SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8)), + SimpleNamespace(page_no=2, image=np.full((12, 12, 3), 255, dtype=np.uint8)), + ], + ) + + client = app.test_client() + response = client.post( + f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages', + headers=admin_headers_factory('frozen-preview-legacy-page-count'), + ) + + assert response.status_code == 200 + assert parse_api_data(response.get_json())['page_count'] == 2 + + def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch): """发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。""" profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch) diff --git a/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py b/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py index 056beb8d..042571c9 100644 --- a/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py +++ b/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py @@ -336,6 +336,9 @@ def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_ 'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by( profile_id=draft['id'], sample_role='annotation', ).first().document_id, + # 本变更将 bind-po-001 改名为 bind-po-002(字段/值源未变), + # 正式 XFA 按 binding_id 身份识别删除,故显式确认该身份变更。 + 'allow_formal_binding_deletions': ['bind-po-001'], }, actor_id=user.id, profile_id=draft['id'], browser_session_id='xfa-p4-tab', lease_token=lease['lease_token'], diff --git a/backend/tests/test_order_extraction_merge.py b/backend/tests/test_order_extraction_merge.py index 765e306e..42e42301 100644 --- a/backend/tests/test_order_extraction_merge.py +++ b/backend/tests/test_order_extraction_merge.py @@ -175,12 +175,12 @@ def test_same_po_conflicting_reservations_do_not_merge_lines(): def test_same_po_conflicting_line_no_does_not_merge_same_part_number(): - """料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。""" + """料号一致但双方都有不同客户项次(customer_po_line_no)时,不能忽略项次而错误补入 Reservation。""" pdf_line = _partial_line(1, part='PN-1', qty=30) pdf_line['fields'].append(_field('line-id', '00010', 1)) email_line = _partial_line(2, part='PN-1', reservation='1000123456') email_line['fields'].append(_field('line-id', '00020', 2)) - definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]} + definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'customer_po_line_no'}]} merged = merge_unit_orders( orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])], diff --git a/backend/tests/test_parsing_profile_purpose.py b/backend/tests/test_parsing_profile_purpose.py new file mode 100644 index 00000000..5f3a3c84 --- /dev/null +++ b/backend/tests/test_parsing_profile_purpose.py @@ -0,0 +1,69 @@ +"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。 + +用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支—— + movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、 + 不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。 + 并用 app fixture 校验模型 purpose 列默认 'inventory'。 +依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。 +逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ValidationError +from app.services.shipping_notice.inventory_parsing_profile import _validate_definition + +pytestmark = pytest.mark.pure_unit + + +def _movement_definition() -> dict: + return { + 'sheet_name': 'Movement', + 'header_row_index': 1, + 'field_mapping': { + 'doc_no': '单据编号', + 'line_no': '项次', + 'in_out_flag': '进出库别', + 'material_code': '料号', + 'material_name': '品名', + 'warehouse_code': '仓库', + 'storage_code': '储位', + 'lot_no': '批号', + 'quantity': '数量', + 'movement_date': '异动日期', + }, + } + + +def test_movement_definition_validates_fixed_fields(): + """movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。""" + definition = _validate_definition(_movement_definition(), purpose='movement') + assert definition['field_mapping']['doc_no'] == '单据编号' + assert definition['field_mapping']['quantity'] == '数量' + assert definition['match_keys'] == [] + + +def test_movement_definition_missing_fixed_field_rejected(): + """movement 缺 movement_date → 阻断。""" + raw = dict(_movement_definition()) + raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'} + with pytest.raises(ValidationError): + _validate_definition(raw, purpose='movement') + + +def test_movement_definition_rejects_unknown_field(): + """movement 引用非定死领域字段 → 阻断。""" + raw = dict(_movement_definition()) + raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'} + with pytest.raises(ValidationError): + _validate_definition(raw, purpose='movement') + + +def test_model_purpose_column_defaults_to_inventory(app): + """模型 purpose 列默认 'inventory'(既有行不回填)。""" + from app.models import ShippingInventoryParsingProfile + + existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first() + assert existing is not None and existing.purpose == 'inventory' diff --git a/backend/tests/test_schedule_run_executor_error.py b/backend/tests/test_schedule_run_executor_error.py new file mode 100644 index 00000000..d5da36e1 --- /dev/null +++ b/backend/tests/test_schedule_run_executor_error.py @@ -0,0 +1,43 @@ +""" +backend/tests/test_schedule_run_executor_error.py + +用途:排程 handler 抛错时 ScheduleRun 必须记 failed,不能因 failed_count=0 标成 success。 +依赖:scheduler_service.run_task_now、ScheduleTask/ScheduleRun。 +逻辑:monkeypatch executor 抛出配置错误,断言 status=failed 且 error_message 保留原文。 +""" + +from __future__ import annotations + +from app import db +from app.models import ScheduleRun, ScheduleTask, User +from app.services.schedule.scheduler_service import run_task_now + + +def test_run_task_now_marks_executor_exception_as_failed(app, monkeypatch): + """handler 抛 RuntimeError 时,批次状态应为 failed 且 failed_count=1。""" + def _boom(_task: ScheduleTask, _run: ScheduleRun): + raise RuntimeError("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME") + + monkeypatch.setattr( + "app.services.schedule.scheduler_service.resolve_schedule_executor", + lambda _task: _boom, + ) + with app.app_context(): + user = User(username="sched-exec-err", email="sched-exec-err@example.com") + db.session.add(user) + db.session.flush() + task = ScheduleTask( + schedule_no="SCH-TEST-EXECUTOR-ERROR", + name="executor error fixture", + schedule_type="platform_job", + platform_api_path="accounting-voucher-check", + owner_user_id=user.id, + cron_expr="0 6 * * 2", + enabled=True, + ) + db.session.add(task) + db.session.commit() + result = run_task_now(task, trigger_type="manual", triggered_by_user_id=user.id) + assert result.status == "failed" + assert result.failed_count == 1 + assert "VOUCHER_CHECK_ERP" in (result.error_message or "") diff --git a/backend/tests/test_shipping_attachment_selection.py b/backend/tests/test_shipping_attachment_selection.py index e3afa735..18d931da 100644 --- a/backend/tests/test_shipping_attachment_selection.py +++ b/backend/tests/test_shipping_attachment_selection.py @@ -238,8 +238,10 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa phase='queued', schema_version_id=1, attempt_count=0, - reparse_source=None, - superseding_run=None, + reparse_source=None, + reparse_of_run_id=None, + superseded_by_run_id=None, + superseding_run=None, reparse_reason=None, superseded_at=None, result_json=None, diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index caef0a9b..bd7495a6 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -80,6 +80,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): run_id=10, run=run, owner_user_id=1, + stream_id=100, current_draft=SimpleNamespace( draft_version=1, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, @@ -103,6 +104,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): return_value={'status': 'queued', 'job_id': 1201, 'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'}, ) as ensure_mock: + RC_Mock.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=1)] RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ SimpleNamespace(id=1), ] @@ -136,6 +138,7 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app) run_id=20, run=SimpleNamespace(id=20, run_no='SNER-20'), owner_user_id=1, + stream_id=200, current_draft=SimpleNamespace( draft_version=3, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, @@ -172,6 +175,7 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app): id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None, document_id=300, candidate_id=30, run_id=30, run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1, + stream_id=300, current_draft=SimpleNamespace( draft_version=2, validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'}, @@ -232,34 +236,26 @@ def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(a case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31) candidate = SimpleNamespace(id=31) shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555) - extraction = SimpleNamespace(id=101) shadow_model = SimpleNamespace( query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)), ) - match_model = SimpleNamespace( - query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))), - ) with patch.object(coord.db.session, 'get', return_value=candidate), patch.object( coord, 'ShippingCustomerShadowResolution', shadow_model, ), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object( coord, - '_resolve_extraction_for_case', - return_value=extraction, - ), patch.object( - coord, - 'ShippingOrderCustomerMatch', - match_model, - ), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object( + 'confirm_customer_resolution', + autospec=True, + ) as confirm_mock, patch.object( coord, 'record_fulfillment_audit', ): status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated') assert status == 'auto_confirmed' - assert metadata == {'customer_id': 5555, 'extraction_id': 101} - assert confirm_mock.call_args.kwargs['commit'] is False + assert metadata == {'customer_id': 5555, 'extraction_id': None} + assert confirm_mock.call_args.kwargs['method'] == 'auto_rule' def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): @@ -313,6 +309,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app): run_id=42, run=run, owner_user_id=1, + stream_id=420, current_draft=SimpleNamespace( draft_version=8, header_values_json={}, @@ -331,6 +328,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app): 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', return_value={'status': 'waiting_manual_validation'}, ): + review_case.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=42)] review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ SimpleNamespace(id=42), ] @@ -465,6 +463,26 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app): ) is True +def test_contract_06_legacy_unexpected_stp_failure_allows_general_retry(app): + """修复前落库的技术异常不能继续阻止普通 STP 重试。""" + from app.services.shipping_notice import reconciliation_service as rs + + case = SimpleNamespace( + case_no='SORC-P1-06-TECH', status='ready', confirmed_task_id=None, + document_id=601, run=SimpleNamespace(run_no='SNER-P1-06-TECH'), + ) + with patch.object(rs, 'Job') as Job: + Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace( + id=61, status='failed', + result_json={ + 'retryable': False, + 'blocking_reason': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED', + 'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED', + }, + ) + rs.assert_case_not_blocked_manual(case_no='SORC-P1-06-TECH', case=case) + + def test_contract_07_get_projection_is_pure_read_no_writes(app): """合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。""" from app.services.shipping_notice.order_review_customer_service import ( @@ -482,11 +500,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): ) as sess_mock, patch( 'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved', return_value=False, - ), patch( - 'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches', - ) as refresh_mock, patch( - 'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match', - ) as confirm_mock: + ): # Shadow = unique_candidate 但是 resolved=false。 with patch( 'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution', @@ -501,19 +515,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): with patch( 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate', ) as Cand, patch( - 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch', - ) as CM, patch( 'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction', ) as EX: sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) - CM.query.filter_by.return_value.first.return_value = None EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700) # 执行投影(纯读) out = project_review_case_customer_resolution(case) # 7A:GET 路径不允许 confirm / validate / commit - confirm_mock.assert_not_called() - refresh_mock.assert_not_called() sess_mock.commit.assert_not_called() # 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认) assert out.get('resolved') is False diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index 1bc54951..d5d9f22c 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -4,7 +4,8 @@ tests/test_shipping_auto_progress_p0_3.py 用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。 依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。 逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox - 仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。 + 仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链; + 显式 retry_rpa 覆盖 waiting_external 残留 poll。 """ from __future__ import annotations @@ -15,7 +16,7 @@ from app import db from app.models import ( Job, ShippingInventoryCandidateSet, - ShippingNotice, + ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, @@ -28,9 +29,9 @@ from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_t from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version -def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice: +def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask: """创建正式 Task;可选择是否补齐订单解析与冻结快照事实。""" - task = ShippingNotice(task_no='APX-P0-3-001') + task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1) db.session.add(task) db.session.flush() candidate = ShippingInventoryCandidateSet( @@ -101,7 +102,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app): formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id)) mark_gates_passed_through( execution=formal, - through_gate_code='task_creation', + through_gate_code='inventory_source_routing', reason='test_review_confirmed', ) task.active_process_execution_id = formal.id @@ -148,6 +149,121 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app): assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0 +def test_submit_does_not_redispatch_after_failed_worker_attempt(app): + """[断言] Worker 真实执行失败(failed + job_id 非空)的门禁:auto_progress 不得自动重试, + 必须等待用户在当前 Gate 显式恢复;首次投递通道(无失败 Attempt)不受影响(由 + test_formal_execution_queues_one_gate_attempt_job 锁定)。""" + import uuid as _uuid + + task = _task_with_candidate() + execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_source_routing', + reason='test_review_confirmed', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).one() + # Worker 已真实执行并失败:failed Attempt 持有非空 job_id + failed_job = Job( + domain='shipping_notice', job_type='shipping_process_gate', + status='failed', business_ref='apx-p03-failed-gate-job', + ) + db.session.add(failed_job) + db.session.flush() + db.session.add(ShippingProcessGateAttempt( + gate_id=int(gate.id), + attempt_no=1, + status='failed', + trigger_type='auto', + actor_type='system', + actor_id='external-wait-poll', + idempotency_key=f'test-failed-worker-attempt:{_uuid.uuid4().hex}', + job_id=int(failed_job.id), + )) + gate.status = 'blocked_retryable' + gate.next_action_code = 'retry_inventory_preparation' + execution.status = 'blocked' + execution.current_gate_code = 'inventory_preparation' + execution.primary_next_action_code = 'retry_inventory_preparation' + execution.responsible_party = 'worker' + task.active_process_execution_id = int(execution.id) + db.session.commit() + + # 同步事实是本用例之外的职责;固定复现“同步后仍为可重试阻断”的当前 Gate。 + with patch( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + ): + result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded') + + assert result['status'] == 'waiting_human' + assert result['gate_code'] == 'inventory_preparation' + # 没有新的 ProcessGate Job 被创建(仅存量失败 Job) + assert Job.query.filter( + Job.job_type == 'shipping_process_gate', + Job.id != int(failed_job.id), + ).count() == 0 + # Attempt 数量不变:只有种子失败行,未被自动重派 + assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1 + + +def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None: + """waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。 + + 回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa) + 后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队 + poll;poll 遇失败 Preparation 直接收口,表现为「改源已保存但 RPA 不触发」。 + """ + task = _task_with_candidate() + execution = ensure_execution_for_workflow_version(review_case_id=905, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_source_routing', + reason='test_review_confirmed', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).one() + gate.status = 'waiting_external' + gate.blocking_reason_code = 'inventory_rpa_export_failed' + gate.next_action_code = 'poll_inventory_preparation' + execution.status = 'waiting_external' + execution.current_gate_code = 'inventory_preparation' + execution.primary_next_action_code = 'poll_inventory_preparation' + execution.responsible_party = 'worker' + task.active_process_execution_id = int(execution.id) + db.session.commit() + + with patch( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + ), patch( + 'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls', + return_value=0, + ): + result = submit_auto_progress( + task=task, + trigger='manual_override_source', + resume_gate_code='inventory_preparation', + inventory_mode='retry_rpa', + commit=True, + ) + + db.session.refresh(gate) + # 关键断言:显式重抓必须入队 retry_inventory_preparation(而非残留 poll)。 + assert result['status'] == 'queued' + assert result.get('reused') is False + queued = ( + ShippingProcessGateAttempt.query + .filter_by(gate_id=int(gate.id), status='queued') + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .first() + ) + assert queued is not None + assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation' + assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa' + + def test_active_stp_job_without_retry_metadata_is_reused(app): """活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。""" from types import SimpleNamespace @@ -183,3 +299,90 @@ def test_active_stp_job_without_retry_metadata_is_reused(app): assert result['retry_of_job_id'] is None +def test_derived_fulfillment_status_uses_line_match_facts_for_order_task(): + """OT 履约状态必须从行级 Match 事实推导,不再读取已删除的 Notice JSON 投影。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_bridge import _derived_fulfillment_status + + task = SimpleNamespace(id=1) + with patch( + 'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task', + return_value=True, + ), patch( + 'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage', + return_value=False, + ), patch( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + return_value=False, + ), patch( + 'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt', + return_value=None, + ), patch( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + return_value=None, + ), patch( + 'app.services.shipping_notice.process_gate_bridge.ShippingOrderTask', + SimpleNamespace, + ): + assert _derived_fulfillment_status(task) == 'matched' + + +def test_auto_retry_blocked_only_for_non_user_trigger(): + """Bug 修复:[禁止自动重试] 仅拦非用户显式触发 / 无定向 gate 的自动推进。 + + 核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试, + 用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进 + (如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching') + 应绕过,否则点"重新匹配库存"报"无待处理 Gate"。 + """ + from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked + + assert _auto_retry_blocked('auto', True) is True + assert _auto_retry_blocked('system_requeue', True) is True + assert _auto_retry_blocked('worker_takeover', True) is True + assert _auto_retry_blocked('user_retry', True) is False + assert _auto_retry_blocked('user_manual', True) is False + assert _auto_retry_blocked('user_retry', False) is False + assert _auto_retry_blocked('auto', False) is False + # 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行 + assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True + assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False + assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False + + +def test_retry_inventory_matching_fulfillable_passes(): + """Bug 修复:已可履约订单的"重新匹配库存"应通过,不把 match_inventory 内部的 + run_task_auto_progress "无待处理 Gate"(status='completed')误判为失败。 + + 核心逻辑:_handle_retry_inventory_matching 只在 needs_human+shortage 时 return passed; + 对 match_status='fulfillable' + response.status='completed' 会落 _tool_outcome 判为 + blocked_retryable,把"无待处理 Gate"记作 error_summary。修复:fulfillable 直接 passed。 + """ + from app.services.shipping_notice import process_gate_executor as ex + from unittest.mock import MagicMock + + class _Task: + id = 1 + task_no = 'OT-X' + order_snapshot_id = 1 + + class _Execution: + task_id = 1 + + class _Gate: + gate_code = 'inventory_matching' + + class _OT: + query = MagicMock(get=MagicMock(return_value=_Task())) + + with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={ + 'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'position': None, + }), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \ + patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \ + patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \ + patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \ + patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}): + result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1}) + assert result['outcome'] == 'passed' + + diff --git a/backend/tests/test_shipping_business_numbering.py b/backend/tests/test_shipping_business_numbering.py index 56a782b7..ad26a9d6 100644 --- a/backend/tests/test_shipping_business_numbering.py +++ b/backend/tests/test_shipping_business_numbering.py @@ -12,7 +12,17 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ( + ShippingBusinessSequence, + ShippingCustomer, + ShippingNotice, + ShippingTaskEvent, + ShippingOrderTask, + ShippingOrderExtraction, + ShippingCustomerShadowResolution, + ShippingOrderSchema, + ShippingOrderSchemaVersion, +) from app.services.shipping_notice.business_numbering_service import ( assign_notice_business_number, format_business_no, @@ -22,23 +32,42 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref -def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): - """创建待客户确认的 Notice 和启用客户。""" - customer = ShippingCustomer( - standard_name=f"编号测试客户 {short_code}", - short_code=short_code, - status="active", - ) - db.session.add(customer) +def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001", customer: ShippingCustomer | None = None): + """创建带客户识别结果的待确认 Notice。""" + if customer is None: + customer = ShippingCustomer( + standard_name=f"编号测试客户 {short_code}", + short_code=short_code, + status="active", + ) + db.session.add(customer) + db.session.flush() + schema = ShippingOrderSchema(schema_code=f'SHIPPING_ORDER_{task_no}', display_name='Order') + db.session.add(schema) db.session.flush() - task = ShippingNotice( - task_no=task_no, - customer_resolution_status="pending", - source_type="manual", + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='a' * 64, ) - db.session.add(task) + db.session.add(version) + db.session.flush() + owner = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='ready', current_step='customer_review') + db.session.add(owner) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + owner.current_order_extraction_id = extraction.id + from tests.conftest import confirm_test_customer_resolution + confirm_test_customer_resolution(owner, customer=customer, extraction=extraction) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one() + resolution.status = 'unique_candidate' + resolution.confirmed_customer_id = None + notice = ShippingNotice(task_no=task_no, source_type='manual', order_task_id=owner.id) + db.session.add(notice) db.session.commit() - return task, customer + return notice, customer def test_number_format_and_shanghai_date_boundary(app): @@ -54,31 +83,31 @@ def test_confirmation_assigns_idempotent_business_number(app): """重复确认同一客户不得重复占用流水,正式编号保持不变。""" with app.app_context(): task, customer = _seed_notice() - first = confirm_task_customer(task, customer_id=customer.id, actor_id=None) - first_no = first.business_no - second = confirm_task_customer(first, customer_id=customer.id, actor_id=None) + confirm_task_customer(task, customer_id=customer.id, actor_id=None) + first_no = assign_notice_business_number(task) + confirm_task_customer(task, customer_id=customer.id, actor_id=None) + second = task assert first_no assert second.business_no == first_no assert ShippingBusinessSequence.query.one().current_value == 1 - assert second.customer_short_code_snapshot == "WYC" - assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1 + resolution = ShippingCustomerShadowResolution.query.one() + assert resolution.confirmed_customer_id == customer.id def test_each_notice_gets_a_distinct_business_number_for_same_customer(app): """同一客户 PO 的不同发货通知必须各自占用独立业务流水。""" with app.app_context(): - customer = ShippingCustomer( - standard_name='通知单波次客户', short_code='WVC', status='active', - ) + customer = ShippingCustomer(standard_name='通知单波次客户', short_code='WVC', status='active') db.session.add(customer) db.session.flush() - first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed') - second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed') - db.session.add_all([first, second]) - db.session.flush() - first.customer_id = customer.id - second.customer_id = customer.id + first, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-1', customer=customer) + second, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-2', customer=customer) + for notice in (first, second): + owner = db.session.get(ShippingOrderTask, notice.order_task_id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one() + resolution.confirmed_customer_id = customer.id + resolution.status = 'confirmed' db.session.flush() first_no = assign_notice_business_number(first) @@ -95,21 +124,17 @@ def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app): customer = ShippingCustomer( standard_name='Notice 自持客户', short_code='NHC', status='active', ) - task = ShippingNotice( - task_no='SN-NOTICE-SELF-CUSTOMER', - customer_resolution_status='pending', - source_type='manual', - ) - db.session.add_all([customer, task]) - db.session.commit() + task, _ = _seed_notice(short_code='NHC', task_no='SN-NOTICE-SELF-CUSTOMER') + customer = ShippingCustomer.query.filter_by(short_code='NHC').one() - confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7) + confirm_task_customer(task, customer_id=customer.id, actor_id=7) + assign_notice_business_number(task) + confirmed = task - assert confirmed.customer_id == customer.id - assert confirmed.customer_name_snapshot == 'Notice 自持客户' - assert confirmed.customer_short_code_snapshot == 'NHC' + owner = db.session.get(ShippingOrderTask, confirmed.order_task_id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one() + assert resolution.confirmed_customer_id == customer.id assert confirmed.business_no - assert confirmed.customer_resolution_status == 'confirmed' def test_replacement_notice_uses_next_sequence(app): @@ -117,16 +142,18 @@ def test_replacement_notice_uses_next_sequence(app): with app.app_context(): task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) + assign_notice_business_number(task) revision = ShippingNotice( task_no="SN-NUMBER-REV", supersedes_task_id=task.id, - customer_resolution_status="pending", + order_task_id=task.order_task_id, source_type="manual", ) db.session.add(revision) db.session.commit() confirm_task_customer(revision, customer_id=customer.id, actor_id=None) + assign_notice_business_number(revision) assert revision.business_no[:-2] == task.business_no[:-2] assert task.business_no.endswith("01") assert revision.business_no.endswith("02") @@ -144,8 +171,7 @@ def test_daily_sequence_blocks_one_hundredth_case(app): current_value=99, )) db.session.commit() - task.customer_id = customer.id - + confirm_task_customer(task, customer_id=customer.id, actor_id=None) with pytest.raises(ConflictError) as exc_info: assign_notice_business_number(task) assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED" @@ -165,14 +191,17 @@ def test_numbering_failure_rolls_back_customer_confirmation(app): )) db.session.commit() + confirm_task_customer(task, customer_id=customer.id, actor_id=None) with pytest.raises(ConflictError): - confirm_task_customer(task, customer_id=customer.id, actor_id=None) + assign_notice_business_number(task) db.session.rollback() db.session.expire_all() persisted_task = db.session.get(ShippingNotice, task.id) - assert persisted_task.customer_id is None + owner = db.session.get(ShippingOrderTask, persisted_task.order_task_id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one() + assert resolution.confirmed_customer_id == customer.id + assert resolution.status == 'confirmed' assert persisted_task.business_no is None - assert persisted_task.customer_resolution_status == "pending" def test_business_number_query_returns_exact_notice(app): @@ -180,11 +209,12 @@ def test_business_number_query_returns_exact_notice(app): with app.app_context(): task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) + assign_notice_business_number(task) revision = ShippingNotice( task_no="SN-NUMBER-QUERY-REV", supersedes_task_id=task.id, document_version=2, - customer_resolution_status="pending", + order_task_id=task.order_task_id, source_type="manual", ) db.session.add(revision) @@ -199,7 +229,7 @@ def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app) """客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。""" with app.app_context(): task, customer = _seed_notice() - task.customer_id = customer.id + confirm_task_customer(task, customer_id=customer.id, actor_id=None) customer.short_code = "W1" # 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。 with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info: diff --git a/backend/tests/test_shipping_candidate_qualification.py b/backend/tests/test_shipping_candidate_qualification.py index 42605672..289a8a85 100644 --- a/backend/tests/test_shipping_candidate_qualification.py +++ b/backend/tests/test_shipping_candidate_qualification.py @@ -128,6 +128,9 @@ def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monke conflicts_json=[{ 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', 'owning_gate_code': 'field_completeness', + # 派生/已解决字段的历史 evidence_missing 由写路径 _discard_resolved_worker_field_conflicts + # 在投影到 Candidate 前丢弃;资格 Gate 只按冻结字段配置判断证据缺失是否可选。 + 'field_config': {'required': False, 'auto_create_key_field': False}, }], structured_result_json={ 'customer': {'resolution_status': 'user_confirmed'}, diff --git a/backend/tests/test_shipping_chat_action_handlers.py b/backend/tests/test_shipping_chat_action_handlers.py index 81623ef3..1c03142b 100644 --- a/backend/tests/test_shipping_chat_action_handlers.py +++ b/backend/tests/test_shipping_chat_action_handlers.py @@ -23,7 +23,6 @@ def test_legacy_fulfillment_chat_actions_are_not_registered(): "shipping.retry_upload", "shipping.match_inventory", "shipping.confirm_inventory_source", - "shipping.submit_decision", "shipping.mark_manual_uploaded", }.isdisjoint(action_types) diff --git a/backend/tests/test_shipping_chat_tool_capability.py b/backend/tests/test_shipping_chat_tool_capability.py index 97852023..e0d85377 100644 --- a/backend/tests/test_shipping_chat_tool_capability.py +++ b/backend/tests/test_shipping_chat_tool_capability.py @@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ForbiddenError -from app.models import Agent, ChatSession, ShippingNotice, User +from app.models import Agent, ChatSession, ShippingOrderTask, User from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability @@ -18,10 +18,10 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app): agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True) db.session.add_all([user, agent]); db.session.flush() session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id) - own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test') - other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test') + own = ShippingOrderTask(task_no='SN-CAP-OWN', user_id=user.id, source_type=None) + other = ShippingOrderTask(task_no='SN-CAP-OTHER', user_id=user.id, source_type=None) db.session.add_all([session, own, other]); db.session.commit() - token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None) + token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no) assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id with pytest.raises(ForbiddenError): require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no) diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 648495cc..a95d6730 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -13,6 +13,7 @@ from pydantic import ValidationError from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( coordinate_profile_character_candidates, + _is_structured_part_identifier, _text_in_region, _text_in_horizontal_region, reconstruction_exclusion_regions, @@ -186,7 +187,7 @@ def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows(): ), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(), row_reconstruction_mode='adaptive_record_columns', ) - # Both layouts must yield a complete logical record despite their different visual-band counts. + # 两种视觉排版均可从明确的 ``@ + 纯数字`` 预约号段还原完整逻辑明细。 assert compact[0].fields == { 'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS', 'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48', @@ -870,6 +871,22 @@ def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign( assert rows[0].fields['reservation_id'] == '3000097059' +def test_coordinate_profile_rows_accept_reservation_with_text_suffix_truncated(): + """预约号框内含文本后缀时可截断为纯数字写入(生产行为)。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)], + [('898.72', 80), ('898.72', 165)], [('3000097059(PENROSE)', 115)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + line_layouts=_adaptive_layouts(), + row_reconstruction_mode='adaptive_record_columns', + ) + + # 允许将带文本后缀的预约号截断为纯数字(生产已实现)。 + assert rows[0].fields['reservation_id'] == '3000097059' + + def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line(): """一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。""" rows = reconstruct_coordinate_profile_rows( @@ -974,6 +991,70 @@ def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor(): }] +def test_dynamic_x_columns_clamps_a_shifted_wide_field_frame_to_the_page_top(): + """锚点上移把宽字段框推过页顶时,截断框仍须读取页面内的有效字符。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('1', 10), ('PART-A', 60)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .25, 'y1': .80}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ], + }], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields for row in rows] == [{'customer_po_line_no': '1', 'part_number': 'PART-A'}] + + +def test_dynamic_x_columns_honors_deleted_marker_exclusion_authorization(): + """dynamic 模式绕过普通排除过滤时,仍须使用配置排除区授权删除标记。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('00010', 10), ('PART-A', 65)], + [('** Item deleted **', 65)], + [('00020', 10), ('PART-B', 65)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}}, + ], + }], + exclusion_regions=[{'x0': .3, 'y0': .3, 'x1': .8, 'y1': .5}], + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields['customer_po_line_no'] for row in rows] == ['00020'] + + +def test_dynamic_x_columns_ignores_unconfigured_deleted_marker(): + """dynamic 模式没有删除标记排除授权时,不得擅自删除上一条明细。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('00010', 10), ('PART-A', 65)], + [('** Item deleted **', 65)], + [('00020', 10), ('PART-B', 65)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}}, + ], + }], + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields['customer_po_line_no'] for row in rows] == ['00010', '00020'] + + def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor(): """固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。""" rows = reconstruct_coordinate_profile_rows( @@ -1145,13 +1226,122 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B'] +def test_coordinate_profile_rows_keep_main_row_fields_and_skip_description_wrap_for_part_number(): + """主视觉行同时含日期金额时,描述折行不得占用内部料号视觉位置。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130), ('08/28/2026', 260), + ('941.76', 320), ('37670.40', 365)], + [('BUSBAR', 130)], + [('D4-A08AR12000002', 130)], + [('Revision:A0', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, + line_layouts=[{'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + {'field_code': 'requested_receipt_date', 'region': {'x0': .65, 'y0': .2, 'x1': .78, 'y1': .3}}, + {'field_code': 'unit_price', 'region': {'x0': .79, 'y0': .2, 'x1': .88, 'y1': .3}}, + {'field_code': 'line_amount_with_tax', 'region': {'x0': .88, 'y0': .2, 'x1': 1, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}], + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'requested_receipt_date', 'scope': 'line', 'value_type': 'date'}, + {'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + {'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields == { + 'customer_po_line_no': '10', 'qty': '40', 'customer_part_number': 'RK-00410-001B', + 'requested_receipt_date': '08/28/2026', 'unit_price': '941.76', + 'line_amount_with_tax': '37670.40', 'part_number': 'D4-A08AR12000002', + } + + +@pytest.mark.parametrize('row_reconstruction_mode', [ + 'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns', +]) +def test_two_subrow_layout_rescans_description_wrap_before_part_number(row_reconstruction_mode): + """真实 ZT 两子行布局中,描述折行不能占用内部料号的固定续行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130)], + [('BUSBAR', 130)], + [('D4-A08AR12000002', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + line_layouts=[ + {'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + ]}, + {'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}, + ], + row_reconstruction_mode=row_reconstruction_mode, + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields['part_number'] == 'D4-A08AR12000002' + + +@pytest.mark.parametrize('row_reconstruction_mode', [ + 'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns', +]) +def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(row_reconstruction_mode): + """真实 ZT 两子行布局中,含数字和标点的描述折行也不能占用内部料号续行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130)], + [('48U AR1.2', 130)], + [('D4-A08AR12000002', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + line_layouts=[ + {'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + ]}, + {'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}, + ], + row_reconstruction_mode=row_reconstruction_mode, + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields['part_number'] == 'D4-A08AR12000002' + + def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review(): - """额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。""" + """描述折行后出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。""" rows = reconstruct_coordinate_profile_rows( characters=_glyphs( [('00010', 10), ('CUSTOMER-A', 55)], [('PART-A', 55)], [('00020', 10), ('CUSTOMER-B', 55)], + [('WRAPPED DESC', 55)], [('ALT-1', 55)], [('ALT-2', 55)], ), @@ -1168,6 +1358,56 @@ def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review(): assert 'coordinate_profile_field_band_ambiguous:part_number' in rows[1].issues +@pytest.mark.parametrize('raw,expected', [ + ('D4-AR1200163A', True), + ('D4-AR1200163A1', True), + ('PART-A', True), + ('A EXW AWS HUB-DB', False), + ('48U AR1.2', False), + ('BUSBAR', False), + ('', False), +]) +def test_is_structured_part_identifier_rejects_whitespace(raw, expected): + """结构化料号纠偏证据不得含空格,避免贸易条款串被当成料号。""" + assert _is_structured_part_identifier(raw) is expected + + +@pytest.mark.parametrize('row_reconstruction_mode', [ + 'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns', +]) +def test_two_subrow_layout_keeps_structured_part_number_against_later_incoterm_band( + row_reconstruction_mode, +): + """续行已读到结构化内部料号时,不得被后续 Incoterms/条款视觉行无条件覆盖。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('6Y17B2493101', 130)], + [('D4-AR1200163A', 130)], + [('A EXW AWS HUB-DB', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + line_layouts=[ + {'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + ]}, + {'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}, + ], + row_reconstruction_mode=row_reconstruction_mode, + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields['part_number'] == 'D4-AR1200163A' + + def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary(): """脱敏回放 4518838152:配置区内删除标记废弃 00010,合计后的记录不允许泄漏。""" rows = reconstruct_coordinate_profile_rows( diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py index 23543943..5de027a6 100644 --- a/backend/tests/test_shipping_customer_auto_resolution.py +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_customer_auto_resolution.py -用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 -依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。 -逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 +用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。 +依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。 +逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。 """ from copy import deepcopy @@ -11,7 +11,6 @@ from copy import deepcopy import pytest from app import db -from app.core.errors import ConflictError, ValidationError from app.models import ( FileAsset, ShippingCustomer, @@ -28,19 +27,17 @@ from app.models import ( ShippingOrderFieldValue, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingOrderTask, ShippingNotice, ShippingTaskEvent, User, ) from app.services.shipping_notice.customer_auto_resolution import ( AUTO_RESOLUTION_VERSION, - correct_numbered_task_customer, get_auto_resolution_metrics, resolve_auto_customer_from_shadow, try_auto_confirm_task_customer, ) -from app.services.shipping_notice.customer_identity_gate import confirm_task_customer -from app.services.shipping_notice.query_service import get_task_by_ref def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]: @@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): ) db.session.add(candidate) db.session.flush() - task = ShippingNotice( - task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id, - user_id=user.id, source_type="email_attachment", - customer_resolution_status="pending", + task = ShippingOrderTask( + task_no=f"OT-AUTO-{user.id}", user_id=user.id, + candidate_id=candidate.id, source_type="eml", ) db.session.add(task) db.session.flush() @@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None: app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 -def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): - """开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" +def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None: + """断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。""" + assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0 + + +def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app): + """开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。""" with app.app_context(): _allow_auto_confirmation(app) customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") @@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): assert result["status"] == "auto_confirmed" assert result["rule_version"] == AUTO_RESOLUTION_VERSION - assert task.customer_resolution_status == "confirmed" - assert task.customer_resolution_method == "auto_rule" - assert task.customer_id == customer.id - assert task.business_no.startswith("WYC") - assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 - event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one() - assert event.detail_json['rule_set']['checksum'] - assert event.detail_json['evidence'][0]['definition_id'] - assert event.detail_json['evidence'][0]['evidence_id'] - source = event.detail_json['evidence'][0]['source'] - assert source['field_value_id'] and source['decision_id'] and source['extraction_id'] - assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id'] + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert shadow.status == "confirmed" + assert shadow.confirmation_method == "auto_rule" + assert shadow.confirmed_customer_id == customer.id + assert shadow.evidence_json[0]['definition_id'] metrics = get_auto_resolution_metrics() + assert result['business_no'] is None + _assert_ot_did_not_create_notice(task) assert metrics["auto_confirmed_count"] == 1 - assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed" - assert metrics["recent_events"][0]["task_no"] == task.task_no def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): @@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False disabled = try_auto_confirm_task_customer(task) assert disabled["status"] == "disabled" - assert task.business_no is None + _assert_ot_did_not_create_notice(task) _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): @@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): result = try_auto_confirm_task_customer(task) assert result["status"] == "ambiguous" assert len(result["candidate_customer_ids"]) == 2 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): @@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): db.session.rollback() db.session.expire_all() - persisted_task = db.session.get(ShippingNotice, task_id) - assert persisted_task.customer_resolution_status == "pending" - assert persisted_task.customer_id is None - assert persisted_task.business_no is None + persisted_task = db.session.get(ShippingOrderTask, task_id) + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate" assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 @@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic assert result["status"] == "insufficient_labeled_samples" assert result["quality_gate"]["labeled_sample_count"] == 0 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_business_evidence_never_auto_confirms(app): @@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app): status='approved', auto_match_allowed=True, )) task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() original_source = shadow.evidence_json[0]['source'] field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id']) decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id']) @@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app): result = try_auto_confirm_task_customer(task) assert result['status'] == 'rule_snapshot_missing' - assert task.customer_resolution_status == 'pending' + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): @@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): task = _seed_candidate_task(sender='buyer@gmail.com') assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.resolution_context_json = {} db.session.commit() missing = resolve_auto_customer_from_shadow(task) @@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app): _allow_auto_confirmation(app) _customer_with_identifier(code='WYC', value='buyer@wyc.example.com') task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() evidence = deepcopy(shadow.evidence_json) evidence[0]['normalized_value'] = 'attacker@example.com' shadow.evidence_json = evidence db.session.commit() assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' - assert task.customer_resolution_status == 'pending' + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' shadow.evidence_json = [] context = deepcopy(shadow.resolution_context_json) @@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app db.session.add(truth) db.session.flush() task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.manual_customer_id = truth.id db.session.commit() @@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app assert result["status"] == "insufficient_accuracy" assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["accuracy"] == 0 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) -def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app): - """客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。""" +def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None: + """把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。""" + shadow.order_schema_version_id = new_version.id + # JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。 + evidence = deepcopy(shadow.evidence_json) + evidence[0]['source']['order_schema_version_id'] = new_version.id + shadow.evidence_json = evidence + extraction = db.session.get( + ShippingOrderExtraction, evidence[0]['source']['extraction_id'], + ) + extraction.schema_version_id = new_version.id + + +def test_schema_republish_with_same_semantics_still_auto_confirms(app): + """Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。""" with app.app_context(): - wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") - correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") - db.session.add_all([wrong, correct]) + _allow_auto_confirmation(app) + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + + old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) + old_version.status = 'retired' + new_version = ShippingOrderSchemaVersion( + schema_id=old_version.schema_id, version=old_version.version + 1, status='published', + definition_json={'fields': [{ + 'field_id': old_version.definition_json['fields'][0]['field_id'], + 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', + 'scope': 'header', 'value_type': 'string', 'enabled': True, + 'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim', + }]}, + checksum='f' * 64, + ) + db.session.add(new_version) db.session.flush() - first = ShippingNotice( - task_no="SN-CORRECTION-V1", document_version=1, - source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV", - inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}], - match_status="fulfillable", line_results_json=[{"sku": "A"}], - export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx", - ) - db.session.add(first) + _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() - confirm_task_customer(first, customer_id=wrong.id, actor_id=None) - old_business_no = first.business_no - result = correct_numbered_task_customer( - first, - customer_id=correct.id, - reason="自动识别客户错误", - actor_id=None, - ) + result = resolve_auto_customer_from_shadow(task) - replacement = db.session.get(ShippingNotice, result["new_notice_id"]) - assert first.business_no == old_business_no - assert first.lifecycle_status == "voided" - assert replacement.supersedes_task_id == first.id - assert replacement.business_no.startswith("NEW") - assert replacement.business_no != old_business_no - assert replacement.customer_resolution_method == "admin_correction" - assert replacement.inventory_source_status is None - assert replacement.inventory_lines_json is None - assert replacement.export_file_path is None - assert replacement.source_type == "manual" - assert get_task_by_ref(old_business_no).id == first.id - assert get_task_by_ref(replacement.business_no).id == replacement.id - assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2 - metrics = get_auto_resolution_metrics() - assert metrics["corrected_task_count"] == 2 - assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no + assert result['status'] == 'unique_strong_match' + assert result['customer_id'] is not None -def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app): - """纠错必须有原因,且已对外上传业务单需先走外部作废流程。""" +def test_schema_republish_changes_semantics_never_auto_confirms(app): + """Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。""" with app.app_context(): - wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") - correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") - db.session.add_all([wrong, correct]) - db.session.flush() - task = ShippingNotice( - task_no="SN-CORRECTION-BLOCK", - source_type="manual", customer_resolution_status="pending", + _allow_auto_confirmation(app) + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + + old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) + old_version.status = 'retired' + new_version = ShippingOrderSchemaVersion( + schema_id=old_version.schema_id, version=old_version.version + 1, status='published', + definition_json={'fields': [{ + 'field_id': old_version.definition_json['fields'][0]['field_id'], + 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', + 'scope': 'header', 'value_type': 'string', 'enabled': True, + 'available_for_customer_identity': True, + 'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。 + }]}, + checksum='e' * 64, ) - db.session.add(task) + db.session.add(new_version) + db.session.flush() + _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() - confirm_task_customer(task, customer_id=wrong.id, actor_id=None) - with pytest.raises(ValidationError) as exc_info: - correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None) - assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED" - db.session.rollback() + result = resolve_auto_customer_from_shadow(task) - task.upload_status = "uploaded" - db.session.commit() - with pytest.raises(ConflictError) as exc_info: - correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None) - assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED" - db.session.rollback() - assert db.session.query(ShippingNotice).count() == 1 + assert result['status'] == 'rule_snapshot_missing' + assert result['customer_id'] is None diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py index 410338ae..3759a3ac 100644 --- a/backend/tests/test_shipping_customer_identity_gate.py +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -1,146 +1,147 @@ """ backend/tests/test_shipping_customer_identity_gate.py -用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 -依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 -逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。 +用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。 +依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。 +逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断; + 确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。 """ from __future__ import annotations -from io import BytesIO - import pytest -from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError -from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User +from app.models import ( + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + User, +) from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, confirm_task_customer, customer_identity_is_confirmed, ) -from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight -from app.services.shipping_notice.inventory_rpa_workflow import ( - _validate_rpa_callback_gate, - ensure_inventory_via_rpa, -) -from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file -from app.services.shipping_notice.progress_workflow import auto_progress -from app.services.shipping_notice.task_workflow import retry_task -def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: - """创建待确认任务、启用客户和任务用户。""" +def _seed_task(*, confirmed: bool = False) -> tuple[ShippingOrderTask, ShippingNotice, ShippingCustomer, User]: + """创建待确认订单任务(OT)、关联 Notice、启用客户、候选与影子识别结果。""" sequence = db.session.query(User).count() user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}' customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') db.session.add_all([user, customer]) db.session.flush() - task = ShippingNotice( - task_no=f'SN-GATE-{user.id}', user_id=user.id, - customer_resolution_status='pending' if customer_pending else None, - lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], - inventory_source_status='user_confirmed', inventory_source_code='DSV', + + intake = ShippingOrderIntake( + intake_no=f'INT-GATE-{user.id}', asset_id=user.id, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-GATE-{user.id}', intake_id=intake.id, primary_document_id=1, + candidate_key=f'gate-{user.id}', candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + + task = ShippingOrderTask( + task_no=f'OT-GATE-{user.id}', user_id=user.id, status='ready', + current_step='customer_review', candidate_id=candidate.id, ) db.session.add(task) + db.session.flush() + + # OT 的客户确认事实由 ShippingCustomerShadowResolution 承载(不再落 Notice/OT 列)。 + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=intake.id, + resolution_version='test.v1', + status='confirmed' if confirmed else 'unique_candidate', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + if confirmed: + resolution.confirmed_customer_id = customer.id + resolution.confirmation_method = 'manual' + db.session.add(resolution) + + notice = ShippingNotice(task_no=f'SN-GATE-{user.id}', user_id=user.id, source_type='manual', order_task_id=task.id) + db.session.add(notice) db.session.commit() - return task, customer, user - - -def _assert_customer_gate_response(result: dict) -> None: - """断言 Tool 入口返回统一客户检查点。""" - assert result['status'] == 'needs_human' - assert result['checkpoint'] == 'customer_review' - assert 'human_options' not in result + return task, notice, customer, user def test_pending_customer_blocks_every_downstream_entry(app): - """未确认客户时所有库存与履约公共入口都必须在副作用前停止。""" + """未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。""" with app.app_context(): - task, _customer, _user = _seed_task() - app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True - - results = [ - auto_progress({'task_id': task.task_no}), - ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), - upload_inventory_file( - task.task_no, - FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'), - ), - ensure_inventory_via_rpa(task, mode='auto'), - match_inventory({'task_id': task.task_no}), - generate_excel({'task_id': task.task_no}), + task, _notice, _customer, _user = _seed_task() + operations = [ + 'auto_progress', + 'ensure_inventory', + 'upload_inventory_file', + 'ensure_inventory_via_rpa', + 'match_inventory', + 'generate_excel', + 'upload_to_freight', ] - for result in results: - _assert_customer_gate_response(result) - - # upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。 - upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}) - _assert_customer_gate_response(upload) - - callback = _validate_rpa_callback_gate(task) - assert callback is not None - assert callback['status'] == 'failed' + for operation in operations: + with pytest.raises(AppError) as exc_info: + assert_customer_identity_gate(task, operation=operation) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' db.session.refresh(task) - assert task.inventory_lines_json is None - assert task.export_file_path is None - assert task.upload_status is None + assert customer_identity_is_confirmed(task) is False def test_pending_customer_blocks_retry_before_clearing_review_state(app): """重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。""" with app.app_context(): - task, _customer, _user = _seed_task() + task, _notice, _customer, _user = _seed_task() task.pending_human_reason = 'customer_unconfirmed' task.error_message = '标准客户尚未确认' db.session.commit() - result = retry_task({'task_id': task.task_no}) - - _assert_customer_gate_response(result) + with pytest.raises(AppError) as exc_info: + assert_customer_identity_gate(task, operation='retry_task') + assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' db.session.refresh(task) assert task.pending_human_reason == 'customer_unconfirmed' assert task.error_message == '标准客户尚未确认' def test_confirm_customer_does_not_assign_notice_number_before_excel(app): - """客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。""" + """客户确认只固化客户事实;正式单号只能由首个 Excel 生成时分配。""" with app.app_context(): - task, customer, user = _seed_task() - revision = ShippingNotice( - task_no='SN-GATE-REV', user_id=user.id, - supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', - ) - db.session.add(revision) - db.session.commit() + task, _notice, customer, user = _seed_task() updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) - db.session.refresh(revision) - assert updated.customer_resolution_status == 'confirmed' - assert revision.customer_resolution_status == 'pending' - assert updated.customer_resolution_method == 'manual' - assert updated.customer_id == customer.id - assert updated.customer_name_snapshot == customer.standard_name - assert updated.customer_short_code_snapshot == customer.short_code - assert updated.business_no is None - assert updated.business_date is None - assert updated.business_sequence_value is None + db.session.refresh(updated) + + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert resolution.status == 'confirmed' + assert resolution.confirmed_customer_id == customer.id + assert resolution.confirmation_method == 'manual' assert customer_identity_is_confirmed(updated) is True - assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1 - assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0 + # OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。 + assert getattr(updated, 'business_no', None) is None -def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch): - """PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。""" +def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch): + """PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。""" with app.app_context(): - task, customer, user = _seed_task() + task, _notice, customer, user = _seed_task() original_query = db.session.query lock_arguments: list[dict] = [] - class NoticeQuerySpy: + class OrderTaskQuerySpy: """保留真实 Query 行为,仅记录客户确认路径的行锁参数。""" def __init__(self, query): @@ -160,21 +161,21 @@ def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, def traced_query(*entities, **kwargs): query = original_query(*entities, **kwargs) - if len(entities) == 1 and entities[0] is ShippingNotice: - return NoticeQuerySpy(query) + if len(entities) == 1 and entities[0] is ShippingOrderTask: + return OrderTaskQuerySpy(query) return query monkeypatch.setattr(db.session, 'query', traced_query) confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) - assert lock_arguments == [{'of': ShippingNotice}] + assert lock_arguments == [{'of': ShippingOrderTask}] def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): """已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。""" with app.app_context(): - task, customer, user = _seed_task() + task, _notice, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) customer.status = 'inactive' db.session.commit() @@ -182,7 +183,7 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): assert_customer_identity_gate(task, operation='match_inventory') assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False) + unconfirmed, _unconfirmed_notice, _other_customer, _other_user = _seed_task() with pytest.raises(AppError) as unconfirmed_error: assert_customer_identity_gate(unconfirmed, operation='match_inventory') assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' @@ -190,10 +191,10 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): def test_workspace_customer_search_and_confirmation_api(app, client): - """业务用户只能确认自己的任务,确认响应返回正式业务编号。""" + """业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): - task, customer, user = _seed_task() + task, notice, customer, user = _seed_task() other_user = User(username='gate-other-user', email='gate-other@example.com', role='user') db.session.add(other_user) db.session.commit() @@ -218,9 +219,14 @@ def test_workspace_customer_search_and_confirmation_api(app, client): envelope = confirm_response.get_json() assert envelope['success'] is True payload = envelope['data'] - assert payload['customer_resolution_status'] == 'confirmed' assert payload['customer_id'] == customer_id - assert payload['business_no'].startswith(short_code) + # 新契约:确认只固化客户事实,业务编号仍由 Excel 阶段分配。 + assert payload.get('business_no') is None + + with app.app_context(): + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert resolution.status == 'confirmed' + assert resolution.confirmed_customer_id == customer_id other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} forbidden_response = client.post( diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py index fb458911..7ccec0f5 100644 --- a/backend/tests/test_shipping_customer_shadow_resolution.py +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -294,3 +294,36 @@ def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app): report = get_shadow_quality_report() assert labeled['is_correct'] is True assert report['labeled_count'] == 1 and report['accuracy'] == 1.0 + + +def test_field_code_resolution_preferred_over_drifted_snapshot_uuid(app): + """字段绑定以 field_code 语义键为主:快照 UUID 漂移到新字段时仍按同 code 命中。""" + from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id + + with app.app_context(): + field, version = _published_field(code='bill_to_customer') + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + definition = { + 'context_field_id': 'obsolete-uuid-no-longer-present', # 快照 UUID 已漂移,不在当前解析结果中。 + 'field_config': {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, + } + header_values = {str(field.id): {'value': 'buyer@example.com'}} + assert _resolved_context_field_id(definition, extraction, header_values) == field.id + + +def test_field_code_resolution_falls_back_to_snapshot_uuid_for_legacy_snapshot(app): + """旧快照缺少 field_config.field_code 时,仍按快照 UUID 直配命中,保持向后兼容。""" + from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id + + with app.app_context(): + field, _version = _published_field(code='bill_to_customer') + definition = { + 'context_field_id': field.id, + 'field_config': {}, # 旧快照无 field_code,只能回退到 UUID 直配。 + } + header_values = {str(field.id): {'value': 'buyer@example.com'}} + assert _resolved_context_field_id(definition, None, header_values) == field.id diff --git a/backend/tests/test_shipping_document_layout_html_table.py b/backend/tests/test_shipping_document_layout_html_table.py index 7ebc001b..3d14adcc 100644 --- a/backend/tests/test_shipping_document_layout_html_table.py +++ b/backend/tests/test_shipping_document_layout_html_table.py @@ -229,7 +229,11 @@ def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it(): def test_material_maps_to_customer_part_number_only_when_schema_declares_it(): - """业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。""" + """业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。 + + aws_part_number 不属于订单 Schema 的表格明细字段(见 test_shipping_order_schema.py + 的标准资产断言),因此 AWS SKU 列必须保持未映射,不能形成内部/AWS 料号字段候选。 + """ result = _map( '' '
Material NoVendor Part NumberAWS SKUQty
CUSTOMER-1INTERNAL-1AWS-12
', @@ -239,10 +243,10 @@ def test_material_maps_to_customer_part_number_only_when_schema_declares_it(): _field('qty', ['Qty'], value_type='integer'), ) + assert [column.status for column in result.columns] == ['mapped', 'mapped', 'unmapped', 'mapped'] assert {field.field_code: field.value for field in result.rows[0].fields} == { 'customer_part_number': 'CUSTOMER-1', 'part_number': 'INTERNAL-1', - 'aws_part_number': 'AWS-1', 'qty': 2, } @@ -280,11 +284,15 @@ def test_customer_material_without_internal_part_is_not_build_complete(): def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed(): - """已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。""" + """已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。 + + line_no 已由系统按单据顺序生成(见 order_schema.field_rules),不再参与表格明细映射; + 改用仍属于表格明细字段的 customer_po_line_no 验证同一污染防护规则。 + """ result = _map( '' '
Item No 00010Vendor Part NumberQty
00020INTERNAL-12
', - _field('line_no', ['Item No']), + _field('customer_po_line_no', ['Item No']), _field('part_number', ['Vendor Part Number'], required=True), _field('qty', ['Qty'], value_type='integer', required=True), ) diff --git a/backend/tests/test_shipping_document_layout_job.py b/backend/tests/test_shipping_document_layout_job.py index 90ed41a5..f747c7d0 100644 --- a/backend/tests/test_shipping_document_layout_job.py +++ b/backend/tests/test_shipping_document_layout_job.py @@ -21,8 +21,11 @@ from app.services.shipping_notice.document_layout.layout_diagnostics import ( LAYOUT_DIAGNOSTIC_COUNT_KEYS, LAYOUT_DIAGNOSTIC_TIMING_KEYS, ) -from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version -from tests.test_shipping_document_layout_lifecycle import _document, _snapshot +from app.services.shipping_notice.document_layout.lifecycle import ( + COORDINATE_EVIDENCE_REF_KEY, + schedule_layout_version, +) +from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot def _assert_layout_job_diagnostics_contract(result: dict) -> None: @@ -69,7 +72,10 @@ def test_layout_job_completes_version_and_updates_document_current(app): 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF', ), patch( 'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot', - return_value=_snapshot(marker='worker'), + return_value={ + **_snapshot(marker='worker'), + 'coordinate_evidence': _externalizable_evidence(), + }, ): run_shipping_document_layout( JobContext(config=dict(app.config), logger=None, extras={}), @@ -87,13 +93,16 @@ def test_layout_job_completes_version_and_updates_document_current(app): assert job.result_json['status'] == 'ready' assert job.result_json['provider_status'] == 'ready' assert job.message == '文档版面解析完成' + # 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] _assert_layout_job_diagnostics_contract(job.result_json) assert 'timings' not in version.payload_json assert 'counts' not in version.payload_json def test_layout_job_reports_compacted_recoverable_pdf_as_success(app): - """表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。""" + """表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。""" app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): document, version, job = _running_layout_job(app) @@ -132,13 +141,14 @@ def test_layout_job_reports_compacted_recoverable_pdf_as_success(app): assert job.message == '文档版面解析完成' assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in version.payload_json['coordinate_evidence'] - assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json -def test_layout_job_failure_requeues_version_and_clears_lease(app): - """可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。""" +def test_layout_job_failure_fails_version_and_clears_lease(app): + """不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。""" with app.app_context(): _document_row, version, job = _running_layout_job(app) with patch( @@ -153,8 +163,9 @@ def test_layout_job_failure_requeues_version_and_clears_lease(app): db.session.refresh(version) db.session.refresh(job) - assert job.status == 'queued' - assert version.status == 'queued' + # 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。 + assert job.status == 'failed' + assert version.status == 'failed' assert version.lease_token is None assert job.error_message == LAYOUT_JOB_ERROR @@ -207,7 +218,7 @@ def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app): 'layout_candidate': {'schema_version': 'shipping_document_layout.v1'}, 'coordinate_evidence': { 'pages': {'1': {'width': 100, 'height': 100}}, - 'page_glyphs': {'1': []}, + 'page_glyphs': {'1': [{'text': 'x'}]}, }, 'issues': [], } diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index db506b0b..3b27ba05 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -21,6 +21,7 @@ from app.models import ( User, ) from app.services.shipping_notice.document_layout.lifecycle import ( + COORDINATE_EVIDENCE_REF_KEY, canonical_layout_payload, claim_layout_version, complete_layout_version, @@ -76,6 +77,19 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict: } +def _externalizable_evidence() -> dict: + """构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。 + + 生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被 + ``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除, + 改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。 + """ + return { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'x'}]}, + } + + def test_layout_snapshot_checksum_and_idempotent_current_version(app): """相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。""" with app.app_context(): @@ -207,7 +221,12 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app): app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): document = _document() - ready = record_inline_layout_snapshot(document, _snapshot()) + # PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。 + ready = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), + }) + assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json reused = schedule_layout_version(document) forced = schedule_layout_version(document, force=True) db.session.commit() @@ -227,7 +246,10 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): original = _document() - ready = record_inline_layout_snapshot(original, _snapshot()) + ready = record_inline_layout_snapshot(original, { + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), + }) duplicate_intake = ShippingOrderIntake( intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id, user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id, @@ -256,12 +278,15 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc def test_recoverable_ready_layout_is_reused_for_duplicate_document(app): - """ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。""" + """ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): original = _document() + # 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref), + # 缺页坐标由正式识别按需从原 PDF 恢复。 incomplete = record_inline_layout_snapshot(original, { - **_snapshot(), 'coordinate_evidence': {'tables': {}}, + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), }) duplicate_intake = ShippingOrderIntake( intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id, @@ -325,8 +350,9 @@ def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkey 'backend': 'pipeline', 'snapshot_version': 'shipping_document_layout.v1', 'tables': [], - # 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。 - 'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}}, + # 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset); + # datasets 仅为末端值源。 + 'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}}, 'xfa_capability': { 'structure_analysis_ready': True, 'structure_analysis_id': source_analysis.id, @@ -483,7 +509,7 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app): def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app): - """PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。""" + """PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): @@ -521,23 +547,27 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab assert document.current_layout_version_id == pending.id assert pending.payload_json['tables'] == snapshot['tables'] assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in pending.payload_json['coordinate_evidence'] - assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] - assert pending.payload_json['matching_features']['version'] == 'v1' - assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2] - assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json - assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。 + assert 'coordinate_evidence' not in pending.payload_json + ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY] + assert ref['asset_no'] + assert ref['checksum'] + assert ref['size'] > 0 + assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1' + # 模板结构保留,无需把外置证据当作容量压缩问题。 + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json + assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json + assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json -def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app): - """普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。""" +def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app): + """普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。""" app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): document = _document() snapshot = { - **_snapshot(marker='inline-compacted'), + **_snapshot(marker='inline-externalized'), 'tables': [{ 'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40}, @@ -556,9 +586,10 @@ def test_inline_layout_compacts_table_glyphs_without_changing_template_structure assert version.status == 'ready' assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in version.payload_json['coordinate_evidence'] - assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,而非内联在快照中。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app): @@ -590,10 +621,11 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map assert 'tables' not in restored['coordinate_evidence'] -def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): - """冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。""" +def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch): + """外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。""" with app.app_context(): document = _document() + # 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。 current = record_inline_layout_snapshot(document, { **_snapshot(), 'coordinate_evidence': { @@ -610,18 +642,34 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}], 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, } + glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}} + page = SimpleNamespace( + page_no=1, width=100, height=200, image=None, + characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)], + ) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_document_profile_service._native_characters_in_table', + lambda *, characters, table_bbox: [glyph], + ) restored = ensure_on_demand_coordinate_evidence( document=document, layout=frozen_layout, page_nos={1}, ) - # 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。 + # 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。 assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H' assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' -def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app): - """同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。""" +def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch): + """外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。""" with app.app_context(): document = _document() current = record_inline_layout_snapshot(document, { @@ -633,19 +681,32 @@ def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_sn }, }) document.current_layout_version = current + # 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。 stale_run_layout = { **_snapshot(), 'coordinate_evidence': { 'pages': {'1': {'width': 100, 'height': 200}}, - 'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, 'sources': {'pages': {'1': 'ocr_coordinate'}}, }, } + glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}} + page = SimpleNamespace( + page_no=1, width=100, height=200, image=None, + characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)], + ) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) restored = ensure_on_demand_coordinate_evidence( document=document, layout=stale_run_layout, page_nos={1}, ) + # 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。 assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT' assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index b734085e..78f6ca8c 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -87,10 +87,20 @@ def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages( } region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False)) raw_table = {'table_id': 'table-1', 'page_no': 1} - assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}] + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}] assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None +def test_quality_region_falls_back_to_table_glyphs_without_page_evidence(): + """页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。""" + evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}} + + assert quality._region_characters_for_quality( + region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'), + evidence=evidence, raw_table={'page_no': 1}, table_id='table-1', + ) == [{'text': 'TABLE'}] + + def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region(): """关键断言:显式跨页区域只能使用后续页自己的 page glyphs。""" evidence = { @@ -965,3 +975,94 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app): frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id']) assert frozen_suite.profile_checksum == published['checksum'] assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs) + + +def test_republish_identical_content_reuses_historical_promoted_suite(app): + """关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。 + + 复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留), + 重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。 + """ + from app.models import ShippingDocumentProfileTestRun + from app.services.shipping_notice import document_profile_quality_service as quality + + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + draft_checksum = str(profile.structure_fingerprint) + published_checksum = str(profile.checksum) + occupant = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id, + ) + new_suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id, + ) + db.session.add_all([occupant, new_suite]) + db.session.flush() + db.session.add_all([ + ShippingDocumentProfileTestRun( + suite_id=occupant.id, profile_checksum=published_checksum, status='passed', + sample_count=1, passed_sample_count=1, executed_by_id=user.id, + ), + ShippingDocumentProfileTestRun( + suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed', + sample_count=1, passed_sample_count=1, executed_by_id=user.id, + ), + ]) + db.session.flush() + + quality.promote_approved_suite_for_publish( + profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id, + ) + db.session.flush() + + # 历史凭证保持原样,仍是发布 checksum 的唯一持有者。 + assert occupant.status == 'approved' + assert occupant.profile_checksum == published_checksum + assert all(run.profile_checksum == published_checksum for run in occupant.runs) + # 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。 + assert new_suite.status == 'superseded' + assert new_suite.profile_checksum == draft_checksum + assert all(run.profile_checksum == draft_checksum for run in new_suite.runs) + reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by( + profile_id=profile.id, event_type='blind_test_suite_superseded', + ).all() + assert any( + (audit.detail_json or {}).get('reason_code') == 'republish_identical_content' + and (audit.detail_json or {}).get('reused_suite_id') == occupant.id + for audit in reuse_audits + ) + + +def test_promote_rejects_invalid_published_checksum_occupant(app): + """关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。""" + from app.core.errors import ConflictError + from app.models import ShippingDocumentProfileTestRun + from app.services.shipping_notice import document_profile_quality_service as quality + + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + draft_checksum = str(profile.structure_fingerprint) + published_checksum = str(profile.checksum) + invalid_occupant = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id, + ) + new_suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id, + ) + db.session.add_all([invalid_occupant, new_suite]) + db.session.flush() + db.session.add(ShippingDocumentProfileTestRun( + suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed', + sample_count=1, passed_sample_count=0, executed_by_id=user.id, + )) + db.session.flush() + + with pytest.raises(ConflictError) as caught: + quality.promote_approved_suite_for_publish( + profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id, + ) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT' + # 冲突时两个套件都不得被改动,保持发布事务可整体回滚。 + assert invalid_occupant.profile_checksum == published_checksum + assert new_suite.status == 'approved' + assert new_suite.profile_checksum == draft_checksum diff --git a/backend/tests/test_shipping_error_explainability_contract.py b/backend/tests/test_shipping_error_explainability_contract.py index ad5d2278..02d16594 100644 --- a/backend/tests/test_shipping_error_explainability_contract.py +++ b/backend/tests/test_shipping_error_explainability_contract.py @@ -90,28 +90,50 @@ def test_rpa_upload_failures_keep_manual_retry_action(): assert projected['next_action'] == 'retry_freight_upload_rpa' -def test_inventory_preparation_reason_code_from_pending(): - """履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。""" - from types import SimpleNamespace - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING +def test_inventory_preparation_reason_code_from_pending(app): + """ + 履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。 + + 核心逻辑:task_blocking_reason 以 ShippingOrderTask.active_process_execution_id 为空的 + pending_human_reason 为唯一事实源;已落文件但无有效行 → inventory_file_empty, + 尚未生成库存文件(inv_unavail)→ inventory_file_missing。 + """ + from app import db + from app.models import ShippingOrderTask + from app.services.shipping_notice.constants import ( + PH_INV_UNAVAIL, + PH_RPA_EXHAUSTED, + PH_RPA_PENDING, + ) from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, manual_upload_reason_code, ) - queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None) - exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None) - # 空列表=已落文件但无有效行;None=尚未生成库存文件 - empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[]) - missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None) + def _pending_task(task_no: str, pending_human_reason: str | None) -> ShippingOrderTask: + """创建并持久化一个无活动执行的 OT;task_blocking_reason 直接读取 pending_human_reason。""" + task = ShippingOrderTask( + task_no=task_no, user_id=1, pending_human_reason=pending_human_reason, + ) + db.session.add(task) + db.session.flush() + return task + + # [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed) + queued = _pending_task('OT-QUEUED', PH_RPA_PENDING) + exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED) assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued' assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted' + + # [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空; + # None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。 + empty = _pending_task('OT-EMPTY', None) + missing = _pending_task('OT-MISSING', PH_INV_UNAVAIL) assert inventory_preparation_reason_code(empty) == 'inventory_file_empty' assert inventory_preparation_reason_code(missing) == 'inventory_file_missing' - upload_failed = SimpleNamespace( - id=None, pending_human_reason='upload_rpa_failed', - ) + # [STEP 3] 上传 RPA 失败归属 freight_upload_rpa,而非人工交接 + upload_failed = _pending_task('OT-UPLOAD-RPA-FAILED', 'upload_rpa_failed') assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed' @@ -121,14 +143,16 @@ def test_build_explainability_reason_unknown_requires_request_id(): 核心逻辑:禁止只显示「系统错误」而不带追溯号。 """ - # [STEP 1] 已知码保留责任方与动作 + # [STEP 1] 已知码保留责任方与动作(source_disabled 归属库存源不可用明细, + # 生产 meta 定义为 admin + retry_with_latest_rules;open_inventory_source_review + # 并非注册动作码,build_explainability_reason 会将其丢弃,故断言必须跟随生产值。) known = build_explainability_reason( reason_code='source_disabled', details={'source_code': 'DSV360_AWSSG'}, ) assert known['reason_code'] == 'source_disabled' assert known['responsible_party'] == 'admin' - assert known['next_action'] == 'open_inventory_source_review' + assert known['next_action'] == 'retry_with_latest_rules' assert known['details']['source_code'] == 'DSV360_AWSSG' # [STEP 2] 未知码强制降级并要求 request_id diff --git a/backend/tests/test_shipping_excel_readiness_order_task.py b/backend/tests/test_shipping_excel_readiness_order_task.py new file mode 100644 index 00000000..a5c0423e --- /dev/null +++ b/backend/tests/test_shipping_excel_readiness_order_task.py @@ -0,0 +1,57 @@ +"""通知准备阶段 Excel 资格边界测试。""" + +from types import SimpleNamespace + + +def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None: + """通知准备阶段的 OT 状态推导不得提前读取正式发货通知单。""" + from app.services.shipping_notice import process_gate_bridge as bridge + + class OrderTask: + id = 21 + + # 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。 + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage', + lambda _task: False, + ) + + class UnexpectedNoticeQuery: + @property + def query(self): + raise AssertionError('通知准备不应查询 ShippingNotice') + + monkeypatch.setattr(bridge, 'ShippingOrderTask', OrderTask) + monkeypatch.setattr(bridge, 'ShippingNotice', UnexpectedNoticeQuery) + + assert bridge._derived_fulfillment_status(OrderTask()) == 'matched' + + +def test_excel_readiness_uses_order_task_before_formal_notice_exists(monkeypatch) -> None: + """OT 已满足库存门禁时,资格检查不得要求先创建 ShippingNotice。""" + from app.services.shipping_notice import process_gate_executor as executor + + order_task = SimpleNamespace(id=21, task_no='OT-READY', match_status='fulfillable') + outcomes: list[dict] = [] + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: order_task) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda task: None if task is order_task else 'wrong_task', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.apply_gate_outcome', + lambda **kwargs: outcomes.append(kwargs), + ) + + result = executor._handle_recheck_excel_readiness( + execution=SimpleNamespace(execution_no='SPE-OT-READY', task_id=21), + gate=SimpleNamespace(gate_code='excel_readiness'), + payload={'actor_user_id': 9}, + ) + + assert result['outcome'] == 'passed' + assert outcomes[0]['passed'] is True diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index 3d89d9d1..75f25409 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -20,7 +20,8 @@ from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, - ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderTask, + ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink, ) from app.services.shipping_notice import excel_template from app.services.shipping_notice.export import ( @@ -32,6 +33,7 @@ from app.services.shipping_notice.export import ( generate_shipment_excel, ) from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export +from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot from app.services.shipping_notice.inventory_file_store import ( active_inventory_lines_for_task, replace_task_inventory_link, @@ -76,11 +78,32 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac ]) is True +def test_unique_notice_warehouse_id_for_header_mapping(): + """Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。""" + from types import SimpleNamespace + from app.services.shipping_notice.export import _unique_notice_warehouse_id + + assert _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id='AWSSG'), + SimpleNamespace(inventory_warehouse_id='awssg'), + ]) == 'AWSSG' + assert _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id=None), + SimpleNamespace(inventory_warehouse_id=''), + ]) is None + with pytest.raises(ValueError, match='多库位'): + _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id='AWSSG'), + SimpleNamespace(inventory_warehouse_id='MOW'), + ]) + + def _freeze_export_snapshot( - task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion, + task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion, *, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None, -) -> None: - """为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。""" + customer_id: int | None = None, inventory_file_id: int | None = None, +) -> ShippingOrderSnapshot: + """为导出测试在 OT 上建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。""" field_codes = { str(item.get('field_id')): str(item.get('field_code') or '') for item in (version.definition_json or {}).get('fields') or [] @@ -91,6 +114,7 @@ def _freeze_export_snapshot( ) snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, + customer_id=customer_id, order_data_version=1, rule_versions_json={}, header_values_json={str(key): value for key, value in (header or {}).items()}, customer_po_number=po_number, @@ -99,20 +123,59 @@ def _freeze_export_snapshot( db.session.flush() for position, field_id, part_number, qty, reservation_id in lines or []: db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=position, part_number=part_number, - reservation_id=reservation_id, qty=Decimal(str(qty)), + snapshot_id=snapshot.id, position=position, line_no=position, + part_number=part_number, reservation_id=reservation_id, qty=Decimal(str(qty)), field_values_json={str(field_id): part_number}, )) db.session.flush() task.order_snapshot_id = snapshot.id record_inventory_verification( - task, inventory_snapshot_id=task.inventory_snapshot_id, source_config_version='test-v1', + task, inventory_snapshot_id=inventory_file_id, source_config_version='test-v1', line_results=[{ 'reservation_id': line.reservation_id, 'part_number': line.part_number, 'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok', } for line in snapshot.lines], ) db.session.flush() + return snapshot + + +def _materialize_export_notice( + *, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: ShippingInventoryFile, + source_code: str, notice_no: str, +) -> ShippingNotice: + """从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。 + + 导出链路只接受已物化的正式 Notice;OT 承载订单/库存事实,Notice 通过 + order_task_id 指向 OT。行级匹配事实按 OT id 落库,库存 Link 绑定 Notice 本身。 + """ + notice = ShippingNotice( + task_no=notice_no, source_type='manual', order_task_id=ot.id, user_id=ot.user_id, + ) + db.session.add(notice) + db.session.flush() + replace_notice_lines_from_snapshot( + notice_id=notice.id, snapshot=snapshot, + inventory_facts_by_snapshot_line_id={ + int(line.id): { + 'inventory_source_code': source_code, + 'inventory_file_id': int(inventory_file.id), + 'inventory_warehouse_id': inventory_file.warehouse_id, + } + for line in snapshot.lines + }, + ) + for line in snapshot.lines: + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no, + match_result='matched', inventory_status='ready', + inventory_snapshot_id=inventory_file.id, inventory_source_code=source_code, + is_current=True, detail_json={}, + )) + db.session.flush() + replace_task_inventory_link(notice, inventory_file, role='owner') + db.session.flush() + return notice @pytest.fixture(autouse=True) @@ -153,23 +216,21 @@ def _workbook_upload() -> FileStorage: def test_filename_pattern_supports_business_number_and_split_business_variables(): """业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。""" task = ShippingNotice( - task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201', - customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1, + task_no='TASK-FILENAME', business_no='WYC26060201', + business_date=date(2026, 6, 2), business_sequence_value=1, ) template = ShippingExcelTemplate( template_code='FILENAME', display_name='Filename', - definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'}, + definition_json={'filename_pattern': '{business_no}_{business_date}_{sequence}.xlsx'}, ) - assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx' + assert _filename(task, template) == 'WYC26060201_260602_01.xlsx' def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path): - """业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。""" + """业务执行必须使用活动库存 Link,忽略请求库存。""" with app.app_context(): - task = ShippingNotice( - task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}], - ) + task = ShippingOrderTask(task_no='OT-INVENTORY-SOURCE', user_id=1) inventory_file = ShippingInventoryFile( inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'), inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1, @@ -185,22 +246,20 @@ def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cac ) assert resolved == [{'part_number': 'ACTIVE'}] - assert task.inventory_lines_json == [{'part_number': 'STALE'}] def test_inventory_execution_keeps_legacy_fallback_without_active_link(app): - """无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。""" + """无活动 Link 的历史任务仍可读取请求库存,避免升级后无法恢复。""" with app.app_context(): - task = ShippingNotice( - task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}], - ) + task = ShippingOrderTask(task_no='OT-INVENTORY-LEGACY', user_id=1) db.session.add(task) db.session.flush() assert resolve_inventory_lines_for_execution( task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}], ) == [{'part_number': 'PAYLOAD'}] - assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}] + # 既无活动 Link 也无旧缓存时返回空,不伪造或回退到其它任务库存。 + assert resolve_inventory_lines_for_execution(task) == [] def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch): @@ -208,7 +267,7 @@ def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp with app.app_context(): storage_path = tmp_path / 'stale.xlsx' storage_path.write_bytes(b'stale-source') - task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE') + task = ShippingOrderTask(task_no='OT-INVENTORY-NO-REPARSE', user_id=1) inventory_file = ShippingInventoryFile( inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path), inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}], @@ -269,6 +328,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): """发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): + from tests.conftest import confirm_test_customer_resolution + schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') db.session.add(schema) db.session.flush() @@ -315,10 +376,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], ) - extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + ot = ShippingOrderTask(task_no='OT-EXPORT-1', user_id=1, status='ready', current_step='customer_review') + db.session.add(ot) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted', + ) db.session.add_all([source, extraction]) db.session.flush() - order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') + order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2) db.session.add(order_line) db.session.flush() header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme') @@ -336,21 +402,26 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): ) db.session.add(confirmed_customer) db.session.flush() - task = ShippingNotice( - task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB', - customer_id=confirmed_customer.id, - customer_resolution_status='confirmed', - # 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。 - inventory_warehouse_id=None, inventory_lines_json=[{ + confirm_test_customer_resolution(ot, customer=confirmed_customer, extraction=extraction) + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-EXPORT-1', user_id=None, + source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'), + inventory_lines_json=[{ _inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9', - }], inventory_snapshot_id=None, + }], + line_count=1, share_mode='task_only', warehouse_id='DUB', source_code='DUB', snapshot_status='ready', ) - db.session.add(task) + db.session.add(inventory_file) db.session.flush() - _freeze_export_snapshot( - task, extraction, version, + snapshot = _freeze_export_snapshot( + ot, extraction, version, header={customer.id: 'acme', po_number.id: '16754796'}, lines=[(1, part.id, 'PN-1', 1, '1000000001')], + customer_id=confirmed_customer.id, inventory_file_id=inventory_file.id, + ) + # 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。 + task = _materialize_export_notice( + ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='DUB', notice_no='TASK-EXPORT-1', ) assert task.business_no is None @@ -427,7 +498,7 @@ def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app): assert _mapping_value( {'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'}, - task=task, order_values={}, inventory_values={}, export_sequence=1, + task=task, order_values={}, inventory_values={}, notice_line_no=1, ) == 1 assert _mapping_value( {'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'}, @@ -523,6 +594,8 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path """库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): + from tests.conftest import confirm_test_customer_resolution + schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') db.session.add(schema); db.session.flush() part = _lookup_standard_fields('part_number')['part_number'] @@ -552,10 +625,16 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], )) - extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + customer = ShippingCustomer(standard_name='键控匹配客户', short_code='KEY', status='active') + db.session.add(customer); db.session.flush() + ot = ShippingOrderTask(task_no='OT-KEYED', user_id=1, status='ready', current_step='customer_review') + db.session.add(ot); db.session.flush() + extraction = ShippingOrderExtraction( + task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted', + ) db.session.add(extraction); db.session.flush() for position, value in enumerate(('PN-A', 'PN-B'), start=1): - line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position)) + line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1) db.session.add(line); db.session.flush() decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=line.id, field_id=part.id, @@ -566,20 +645,27 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path extraction_id=extraction.id, line_id=line.id, field_id=part.id, value_text=value, decision_id=decision.id, )) - task = ShippingNotice( - task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED', - inventory_warehouse_id='DUB', inventory_lines_json=[ + confirm_test_customer_resolution(ot, customer=customer, extraction=extraction) + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx', + storage_path=str(tmp_path / 'keyed.xlsx'), + inventory_lines_json=[ {_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'}, {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'}, ], + line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='KEYED', snapshot_status='ready', ) - db.session.add(task); db.session.flush() - _freeze_export_snapshot( - task, extraction, version, + db.session.add(inventory_file); db.session.flush() + snapshot = _freeze_export_snapshot( + ot, extraction, version, lines=[ (1, part.id, 'PN-A', 1, '1000000002'), (2, part.id, 'PN-B', 1, '1000000003'), ], + customer_id=customer.id, inventory_file_id=inventory_file.id, + ) + task = _materialize_export_notice( + ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='KEYED', notice_no='TASK-KEYED', ) path, _filename, _artifact = generate_shipment_excel(task) @@ -700,6 +786,8 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_ """导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): + from tests.conftest import confirm_test_customer_resolution + schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') db.session.add(schema); db.session.flush() part = _lookup_standard_fields('part_number')['part_number'] @@ -726,9 +814,15 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_ parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], )) - extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + customer = ShippingCustomer(standard_name='模糊匹配客户', short_code='AMB', status='active') + db.session.add(customer); db.session.flush() + ot = ShippingOrderTask(task_no='OT-AMBIGUOUS', user_id=1, status='ready', current_step='customer_review') + db.session.add(ot); db.session.flush() + extraction = ShippingOrderExtraction( + task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted', + ) db.session.add(extraction); db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') + line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2) db.session.add(line); db.session.flush() decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=line.id, field_id=part.id, @@ -739,17 +833,25 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_ extraction_id=extraction.id, line_id=line.id, field_id=part.id, value_text='PN-A', decision_id=decision.id, )) - task = ShippingNotice( - task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id, - inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[ + confirm_test_customer_resolution(ot, customer=customer, extraction=extraction) + ambiguous_file = ShippingInventoryFile( + inventory_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx', + storage_path=str(tmp_path / 'ambiguous.xlsx'), + inventory_lines_json=[ {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'}, {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'}, ], + line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS', + snapshot_status='ready', ) - db.session.add(task); db.session.flush() - _freeze_export_snapshot( - task, extraction, version, - lines=[(1, part.id, 'PN-A', 1, '1000000004')], + db.session.add(ambiguous_file); db.session.flush() + snapshot = _freeze_export_snapshot( + ot, extraction, version, + lines=[(1, part.id, 'PN-A', 1, '1000000004')], + customer_id=customer.id, inventory_file_id=ambiguous_file.id, + ) + task = _materialize_export_notice( + ot=ot, snapshot=snapshot, inventory_file=ambiguous_file, source_code='AMBIGUOUS', notice_no='TASK-AMBIGUOUS', ) with pytest.raises(ValueError, match='库存字段“ODM 编号”'): @@ -770,7 +872,9 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_ db.session.add(inventory_file) db.session.flush() replace_task_inventory_link(task, inventory_file, role='owner') - task.inventory_snapshot_id = inventory_file.id + # 切换活动库存后,行级匹配事实须指向新快照;导出只读取活动 Link。 + for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=ot.id, is_current=True).all(): + match.inventory_snapshot_id = inventory_file.id db.session.flush() path, _filename_value, artifact = generate_shipment_excel(task) @@ -781,7 +885,6 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_ finally: workbook.close() assert artifact.inventory_snapshot_id == inventory_file.id - assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1' def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch): diff --git a/backend/tests/test_shipping_field_asset_governance.py b/backend/tests/test_shipping_field_asset_governance.py index b7868e6e..ca57039a 100644 --- a/backend/tests/test_shipping_field_asset_governance.py +++ b/backend/tests/test_shipping_field_asset_governance.py @@ -111,6 +111,40 @@ def test_extension_create_retire_restore_and_forbid_delete(app): assert updated['display_name_default'] == '新名称' +def test_update_extension_cannot_change_field_code(app): + """断言:扩展字段 field_code 创建后不可变。 + + field_code 是跨版本语义键:客户识别规则按 code 优先绑定字段(resolver code-primary), + 一旦允许改名,历史规则快照与运行时绑定会静默漂移。此处钉死资产服务层锁, + 防止未来新增改名路径时无意破坏该前提。 + """ + with app.app_context(): + assets.ensure_standard_assets_seeded() + created = assets.create_extension( + { + 'field_code': 'ext_channel_ref', + 'scope': 'header', + 'value_type': 'string', + 'display_name': '渠道参考号', + }, + actor_id=None, + ) + current = assets.get_asset(created['id']) + with pytest.raises(ConflictError) as locked: + assets.update_extension( + created['id'], + { + 'field_code': 'ext_channel_ref_renamed', + 'display_name': '渠道参考号', + 'expected_updated_at': current['updated_at'], + }, + actor_id=None, + ) + # 关键断言:改名被拒绝且值未被改动,语义键稳定性由服务层硬锁保证。 + assert locked.value.code == 'SHIPPING.FIELD_ASSET_IMMUTABLE' + assert assets.get_asset(created['id'])['field_code'] == 'ext_channel_ref' + + def test_schema_adopt_writes_per_field_audits(app): """断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。""" from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion diff --git a/backend/tests/test_shipping_field_split_core.py b/backend/tests/test_shipping_field_split_core.py index f6a04943..e53b11fe 100644 --- a/backend/tests/test_shipping_field_split_core.py +++ b/backend/tests/test_shipping_field_split_core.py @@ -320,7 +320,7 @@ def test_unknown_matcher_code_in_diagnostic_when_extension_happens(): """如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。""" seg = BaseSplitSegment( segment_id=new_segment_id(), - segment_code='s', + segment_code='s1', display_name='s', handling='mapped', target_field_id='f-s', diff --git a/backend/tests/test_shipping_formal_task_edit_audit.py b/backend/tests/test_shipping_formal_task_edit_audit.py index 59f4d866..9b71a8ed 100644 --- a/backend/tests/test_shipping_formal_task_edit_audit.py +++ b/backend/tests/test_shipping_formal_task_edit_audit.py @@ -10,7 +10,7 @@ backend/tests/test_shipping_formal_task_edit_audit.py from __future__ import annotations from app import db -from app.models import ShippingAuditEvent +from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES from app.services.shipping_notice.task_workflow import update_notice_line from tests.test_shipping_review_formal_task_edit import ( @@ -76,6 +76,21 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app): }, ) _link_order_task(task, stage='excel_generating') + # 前置:任务已在行级匹配为 matched(否则 before 快照不存在“被失效”的匹配状态)。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(task.id), + snapshot_line_id=1, + line_no=1, + line_index=0, + match_result='matched', + inventory_status='ready', + required_qty='10', + available_qty='10', + shortage_qty='0', + reservation_id='3000000001', + part_number='A001', + is_current=True, + )) db.session.commit() response = update_notice_line({ diff --git a/backend/tests/test_shipping_fulfillment_entry_gates.py b/backend/tests/test_shipping_fulfillment_entry_gates.py index ed494b49..3f7cc1fe 100644 --- a/backend/tests/test_shipping_fulfillment_entry_gates.py +++ b/backend/tests/test_shipping_fulfillment_entry_gates.py @@ -20,12 +20,12 @@ def test_export_rejects_voided_task_before_reading_template(app): generate_shipment_excel(task) -def test_manual_upload_requires_receipt_number_and_evidence(app): - """关键断言:截图/附件和货代回执号缺一不可,不能仅凭客户端声明完成上传。""" +def test_manual_upload_requires_uploadable_artifact(app): + """关键断言:人工上传入口必须先存在可上传的导出 Artifact,不能仅凭客户端声明完成上传。""" with app.app_context(): task = ShippingNotice(task_no='SN-ENTRY-UPLOAD', source_type='test') from app import db db.session.add(task); db.session.commit() with pytest.raises(ValidationError) as error: - record_manual_upload(task, artifact_id=None, evidence_asset_no='asset', operator_id=1, freight_ref_no='') - assert error.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED' + record_manual_upload(task, artifact_id=None, operator_id=1) + assert error.value.code == 'SHIPPING.UPLOAD_ARTIFACT_REQUIRED' diff --git a/backend/tests/test_shipping_gate_orchestration_separation.py b/backend/tests/test_shipping_gate_orchestration_separation.py new file mode 100644 index 00000000..a7f1d2dd --- /dev/null +++ b/backend/tests/test_shipping_gate_orchestration_separation.py @@ -0,0 +1,348 @@ +""" +tests/test_shipping_gate_orchestration_separation.py + +用途:锁定履约 Gate「匹配 Attempt 不内嵌 Excel / 匹配通过后续跑独立 artifact Attempt」。 +依赖:pytest、fulfillment_workflow.try_auto_chain_after_match、process_gate_executor、 + process_gate_bridge、process_gate_service、auto_progress fixtures。 +逻辑:Gate 路径(_orchestrator_internal_dispatch)禁止 generate/upload; + match pass + sync 后须留下可自动投递的 artifact_generation Attempt。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app import db +from app.models import ( + Job, + ShippingInventoryCandidateSet, + ShippingOrderTask, + ShippingProcessGate, + ShippingProcessGateAttempt, +) +from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match +from app.services.shipping_notice.process_gate_bridge import ( + mark_gates_passed_through, + sync_fulfillment_gates_from_task, +) +from app.services.shipping_notice.process_gate_service import ( + complete_gate_attempt, + ensure_execution_for_workflow_version, + queue_gate_attempt, +) + + +def _task_with_candidate(*, task_no: str = 'OT-ORCH-SEP-001') -> ShippingOrderTask: + """创建带冻结候选集的正式 OT,供 20-Gate Execution 绑定。""" + task = ShippingOrderTask(task_no=task_no, user_id=1) + db.session.add(task) + db.session.flush() + candidate = ShippingInventoryCandidateSet( + task_id=task.id, + set_version=1, + lifecycle_status='frozen', + input_fingerprint='b' * 64, + ) + db.session.add(candidate) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + task.current_order_extraction_id = 101 + task.order_snapshot_id = 201 + db.session.commit() + return task + + +def _patch_fulfillable_inventory(monkeypatch) -> None: + """让 sync_fulfillment 能越过 prep,到达 excel_readiness / artifact。""" + inv_file = SimpleNamespace( + id=1, + snapshot_status='ready', + invalidated_at=None, + mapping_confirmed=True, + source_query_json={}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: inv_file, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_lines_for_task', + lambda _task: [{'reservation_id': 'R1', 'part_number': 'P1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status', + lambda _task: 'matched', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: None, + ) + + +def test_try_auto_chain_gate_path_does_not_call_generate_or_upload(app, monkeypatch) -> None: + """Gate Attempt 路径:try_auto_chain 不得同 Attempt 内嵌 generate_excel / upload。""" + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + + task = ShippingOrderTask(task_no='OT-ORCH-CHAIN-0', user_id=1) + db.session.add(task) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow._current_export_artifact', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + + generate_calls: list[dict] = [] + upload_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.upload_to_freight', + lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={ + 'task_id': task.task_no, + '_orchestrator_internal_dispatch': True, + 'source': 'process_gate', + }, + ) + + assert result['status'] == 'ok' + assert generate_calls == [] + assert upload_calls == [] + + +def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch) -> None: + """inventory_matching Handler 成功履约时不得调用 generate_excel。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-HANDLER') + execution = ensure_execution_for_workflow_version(review_case_id=9201, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + generate_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda payload: try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched', 'task_id': task.task_no}, + payload=payload, + ), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}}, + ) + + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + result = _handle_retry_inventory_matching( + execution=execution, + gate=gate, + payload={'actor_user_id': 1}, + ) + + assert result['outcome'] == 'passed' + assert generate_calls == [] + + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + +def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> None: + """匹配事实就绪且无 Artifact 时,submit_auto_progress 须入队 artifact Attempt。""" + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_MATCH_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-ENQ') + execution = ensure_execution_for_workflow_version(review_case_id=9202, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep_enqueue', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=None, + ) + + matching_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + if matching_gate.status != 'passed': + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code='inventory_matching', + trigger_type='auto', + actor_type='system', + actor_id=None, + idempotency_key=f'test-orch-sep-match:{execution.id}', + expected_gate_version=int(matching_gate.evaluation_version), + input_snapshot={'action_code': 'retry_inventory_matching', 'payload': {}}, + ) + assert attempt is not None + complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='passed', + output_snapshot={'action_code': 'retry_inventory_matching'}, + effective_result_json={'match_status': 'fulfillable'}, + ) + + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + queued = submit_auto_progress(task=task, trigger='user_retry', commit=True) + assert queued.get('status') in {'queued', 'running'} + assert queued.get('gate_code') == 'artifact_generation' + attempt = db.session.get(ShippingProcessGateAttempt, int(queued['attempt_id'])) + assert attempt is not None + assert isinstance(attempt.input_snapshot_json, dict) + assert attempt.input_snapshot_json.get('action_code') == 'regenerate_excel_artifact' + assert Job.query.filter_by(id=int(queued['job_id'])).one().job_type == 'shipping_process_gate' + + +def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) -> None: + """端到端:match Handler 不生成;artifact Handler 才调用 generate_excel 一次。""" + from app.services.shipping_notice.process_gate_executor import ( + _handle_regenerate_excel, + _handle_retry_inventory_matching, + ) + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-E2E') + execution = ensure_execution_for_workflow_version(review_case_id=9203, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep_e2e', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + generate_calls: list[dict] = [] + + def _fake_generate(payload): + generate_calls.append(dict(payload or {})) + artifact = SimpleNamespace( + id=99, + file_path='/tmp/orch-sep.xlsx', + file_name='orch-sep.xlsx', + status='ready', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: artifact, + ) + return {'status': 'ok', 'message': 'excel-ok'} + + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + _fake_generate, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda payload: try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched', 'task_id': task.task_no}, + payload=payload, + ), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}}, + ) + + matching_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + match_result = _handle_retry_inventory_matching( + execution=execution, + gate=matching_gate, + payload={'actor_user_id': 1}, + ) + assert match_result['outcome'] == 'passed' + assert generate_calls == [] + + # match handler 内 sync 已投影 artifact;禁止再 force sync matching(会 allow_repass + # 入队 artifact Attempt,把 next_action 清成 queued→None)。 + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + artifact_result = _handle_regenerate_excel( + execution=execution, + gate=artifact_gate, + payload={'actor_user_id': 1}, + ) + assert artifact_result.get('outcome') == 'passed' + assert len(generate_calls) == 1 + assert generate_calls[0].get('_orchestrator_internal_dispatch') is True diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 5e944dab..77feb794 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -60,6 +60,31 @@ def test_physical_table_outside_profile_region_is_not_a_parse_target(): ) is False +def test_header_only_exact_page_region_is_not_a_parse_target(): + """专属页只有无 line_layouts 的壳表区时,不得进入重建并把 NO_VALID 污染到已成功页。""" + regions = [ + { + 'region_id': 'main_lines_page_1', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': .01, 'y0': .43, 'x1': .97, 'y1': .48}, + 'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'field_regions': []}], + }, + { + 'region_id': 'main_lines_page_2', 'page_scope': 'exact_page', 'page_no': 2, + 'region': {'x0': .01, 'y0': .12, 'x1': .97, 'y1': .20}, + 'line_layouts': [], + }, + ] + page = {'width': 792, 'height': 612} + + assert _physical_table_targets_profile_region( + raw_table={ + 'table_id': 'mineru-page2-header', 'page_no': 2, + 'bbox': {'x0': 5, 'y0': 80, 'x1': 760, 'y1': 120}, + }, + table_regions=regions, page_size=page, + ) is False + + def test_empty_virtual_page_does_not_block_a_successful_target_table(): """无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。""" assert _virtual_page_without_rows_is_nonblocking( @@ -490,7 +515,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey assert result['match']['status'] == 'unique_match' assert result['match']['profile_code'] == 'ODP-PRODUCTION' # 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。 - assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1'] + assert seen_table_ids == ['native-text-table-p1-1'] * 3 def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): @@ -615,7 +640,7 @@ def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkey # 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。 assert rows == [] - assert unrelated == [] + assert unrelated is None assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']] diff --git a/backend/tests/test_shipping_inventory_candidate_routing.py b/backend/tests/test_shipping_inventory_candidate_routing.py index e20bea74..d79ee55c 100644 --- a/backend/tests/test_shipping_inventory_candidate_routing.py +++ b/backend/tests/test_shipping_inventory_candidate_routing.py @@ -15,7 +15,7 @@ from app.extensions import db from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot, - ShippingOrderSnapshotLine, ShippingNotice, + ShippingOrderSnapshotLine, ShippingOrderTask, ) from app.services.shipping_notice.inventory_routing_engine import ( evaluate_inventory_source_rules, @@ -75,9 +75,9 @@ def _published_line_fields() -> dict[str, str]: def _task_with_line_values( fields: dict[str, str], values: dict[str, tuple[str, str]], -) -> tuple[ShippingNotice, dict[str, int]]: +) -> tuple[ShippingOrderTask, dict[str, int]]: """创建冻结快照供 Snapshot 路由路径读取。""" - task = ShippingNotice(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual') + task = ShippingOrderTask(task_no='OT-CANDIDATE-ROUTE', user_id=1, source_type='eml') db.session.add(task) db.session.flush() extraction = ShippingOrderExtraction( @@ -86,7 +86,7 @@ def _task_with_line_values( ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() for field_id, (value, _purpose) in values.items(): @@ -112,7 +112,7 @@ def _task_with_line_values( db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, + snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''), part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']], field_values_json=snapshot_values, diff --git a/backend/tests/test_shipping_inventory_configuration.py b/backend/tests/test_shipping_inventory_configuration.py index bb0d38a8..55d9cf57 100644 --- a/backend/tests/test_shipping_inventory_configuration.py +++ b/backend/tests/test_shipping_inventory_configuration.py @@ -17,14 +17,16 @@ from app.extensions import db from app.models import ( ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource, - ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, + ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, - ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, + ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile, ) from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential from app.services.shipping_notice.inventory_source_repository import validate_source_profile from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse +from app.services.shipping_notice.order_schema import service as order_schema_service +from tests.conftest import seed_task_inventory_source def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile: @@ -62,6 +64,75 @@ def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = ' ) +def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None: + """为动态仓库存解析测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。""" + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() + if version is None: + order_schema_service.initialize_schema({'display_name': '库存动态仓测试订单'}, actor_id=None) + fields = { + code: order_schema_service.save_field( + {'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None, + ) + for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal')) + } + draft = order_schema_service.create_draft({}, actor_id=None) + purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'} + saved = order_schema_service.save_draft(draft['id'], { + 'fields': [{ + 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code], + 'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal', + 'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'], + 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + } for code, field in fields.items()], + 'expected_lock_version': draft['lock_version'], + }, actor_id=None) + order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + field_ids = { + str(item['field_code']): str(item['field_id']) + for item in (version.definition_json or {}).get('fields') or [] + } + owner = task + extraction = ShippingOrderExtraction( + task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) + db.session.add(line) + db.session.flush() + for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items(): + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted', + supporting_observation_ids_json=[], resolved_value_json=value, + ) + db.session.add(decision) + db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id, + value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, + value_json=value, + )) + owner.current_order_extraction_id = extraction.id + db.session.flush() + + +def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None: + """为直接构造的库存任务补齐已确认客户,避免绕过客户身份门禁。""" + customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name='库存动态仓测试客户', short_code='RPC', status='active', + ) + db.session.add(customer) + db.session.flush() + from tests.conftest import confirm_test_customer_resolution + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + task._test_customer_confirmed = True + + def test_encrypt_credential_round_trip_requires_runtime_key(app): """凭据必须依赖环境主密钥加密,且可在受控运行时回读。""" app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') @@ -196,92 +267,51 @@ def test_external_mapping_prefers_exact_warehouse_then_source_default(app): def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path): """动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。""" from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task - from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version - from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context with app.app_context(): - source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match') - inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} - schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') - db.session.add(schema) - db.session.flush() - from app.services.shipping_notice import field_asset_service - field_asset_service.ensure_standard_assets_seeded() - part_field = ShippingOrderField.query.filter_by(field_code='part_number', scope='line').one() - reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id', scope='line').one() - version = ShippingOrderSchemaVersion( - schema_id=schema.id, version=1, status='published', checksum='d' * 64, - definition_json={'fields': [ - {'field_id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'}, - {'field_id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'}, - ]}, + base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + crane_profile = ShippingRpaProfile( + profile_code='CRANE_DYNAMIC_PN', display_name='Crane Dynamic PN', + connector_type='crane', login_url='https://test.invalid/crane', + login_config_json={'auth_mode': 'password'}, ) - source.parsing_profile.definition_json = { - 'field_mapping': { - inventory_fields['part_number']: 'Part', - inventory_fields['reservation_id']: 'Reservation', - inventory_fields['available_qty']: 'Qty', - inventory_fields['warehouse_id']: 'Warehouse', - }, - 'match_keys': [ - {'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']}, - {'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']}, - ], - } - db.session.add(source) - db.session.add_all([schema, version]) - db.session.flush() - extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted') - db.session.add(extraction) - db.session.flush() - order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') - db.session.add(order_line) - db.session.flush() - part_decision = ShippingOrderFieldDecision( - extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id, - decision_status='accepted', resolved_value_json='A001', + crane_source = ShippingInventorySource( + source_code='CRANE', display_name='Crane', connector_type='crane', + rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile, + excel_template=base_source.excel_template, + warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, + report_path_json={}, query_parameters_json=[], enabled=True, ) - reservation_decision = ShippingOrderFieldDecision( - extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id, - decision_status='accepted', resolved_value_json='R-1', + task = ShippingOrderTask( + task_no='OT-DYNAMIC-WH', user_id=1, source_type='direct_pdf', status='ready', ) - db.session.add_all([part_decision, reservation_decision]) - db.session.flush() - db.session.add_all([ - ShippingOrderFieldValue( - extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id, - value_text='A001', decision_id=part_decision.id, - ), - ShippingOrderFieldValue( - extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id, - value_text='R-1', decision_id=reservation_decision.id, - ), - ]) - task = ShippingNotice( - task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE', - inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule', - current_order_extraction_id=extraction.id, - ) - task.inventory_source_config_version = inventory_sources_runtime_version() - task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) db.session.add(task) db.session.flush() - order_snapshot = ShippingOrderSnapshot( - task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, - order_data_version=1, rule_versions_json={}, header_values_json={}, - ) - db.session.add(order_snapshot) + _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _confirm_direct_rpa_task_customer(task) + db.session.add_all([crane_profile, crane_source]) db.session.flush() - db.session.add(ShippingOrderSnapshotLine( - snapshot_id=order_snapshot.id, position=1, part_number='A001', reservation_id='R-1', - field_values_json={str(part_field.id): 'A001', str(reservation_field.id): 'R-1'}, - )) - task.order_snapshot_id = order_snapshot.id + seed_task_inventory_source(task, source_code='CRANE') + order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) + schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or [] + order_field_ids = { + str(item.get('field_code') or ''): str(item.get('field_id') or '') + for item in schema_fields + } + definition = dict(base_source.parsing_profile.definition_json or {}) + definition['match_keys'] = [ + {'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']}, + {'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']}, + ] + base_source.parsing_profile.definition_json = definition + db.session.commit() + + inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} path = tmp_path / 'dynamic.xlsx' path.write_bytes(b'not-parsed-in-this-test') snapshot = ShippingInventoryFile( inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready', - source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool', + source_code='CRANE', warehouse_id=None, share_mode='warehouse_pool', inventory_lines_json=[ { inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1', @@ -297,41 +327,71 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t db.session.commit() link = link_snapshot_to_task(task, snapshot, reason='dynamic_test') assert link is not None - assert task.inventory_warehouse_id == 'FRA' assert link.matched_warehouse_id == 'FRA' def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path): """同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。""" from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task - from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version - from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context with app.app_context(): - source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match') - db.session.add(source) - db.session.commit() - task = ShippingNotice( - task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG', - inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule', - lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + crane_profile = ShippingRpaProfile( + profile_code='CRANE_AMBIG_PROFILE', display_name='Crane Ambiguous Profile', + connector_type='crane', login_url='https://test.invalid/crane', + login_config_json={'auth_mode': 'password'}, ) - task.inventory_source_config_version = inventory_sources_runtime_version() - task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) + crane_source = ShippingInventorySource( + source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane', + rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile, + excel_template=base_source.excel_template, + warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, + report_path_json={}, query_parameters_json=[], enabled=True, + ) + task = ShippingOrderTask( + task_no='OT-DYNAMIC-AMBIG', user_id=1, source_type='direct_pdf', status='ready', + ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _confirm_direct_rpa_task_customer(task) + db.session.add_all([crane_profile, crane_source]) + db.session.flush() + seed_task_inventory_source(task, source_code='CRANE_AMBIG') + order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) + schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or [] + order_field_ids = { + str(item.get('field_code') or ''): str(item.get('field_id') or '') + for item in schema_fields + } + definition = dict(base_source.parsing_profile.definition_json or {}) + definition['match_keys'] = [ + {'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']}, + {'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']}, + ] + base_source.parsing_profile.definition_json = definition + db.session.commit() + + inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} path = tmp_path / 'ambiguous.xlsx' path.write_bytes(b'not-parsed-in-this-test') snapshot = ShippingInventoryFile( inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready', - source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool', + source_code='CRANE_AMBIG', warehouse_id=None, share_mode='warehouse_pool', inventory_lines_json=[ - {'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1}, - {'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1}, + { + inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1', + inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1, + }, + { + inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1', + inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 1, + }, ], ) - db.session.add_all([task, snapshot]) + db.session.add(snapshot) db.session.commit() assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None - assert task.inventory_warehouse_id is None def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path): diff --git a/backend/tests/test_shipping_inventory_link_ot_owner.py b/backend/tests/test_shipping_inventory_link_ot_owner.py new file mode 100644 index 00000000..b22d7613 --- /dev/null +++ b/backend/tests/test_shipping_inventory_link_ot_owner.py @@ -0,0 +1,75 @@ +""" +tests/test_shipping_inventory_link_ot_owner.py + +用途:锁定库存 Link 挂在正式 OT 上;传入 ShippingNotice 时仍须解析到该 OT 的 active link。 +依赖:pytest、inventory_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。 +逻辑:复现「Notice.id ≠ OT.id → Excel 导出读到 0 行库存」回归。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingInventoryFile, + ShippingNotice, + ShippingOrderTask, + ShippingTaskInventoryLink, +) +from app.services.shipping_notice.inventory_file_store import ( + active_inventory_file_for_task, + resolve_inventory_lines_for_execution, +) + + +def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) -> None: + """Notice 导出路径必须通过 order_task_id 找到挂在 OT 上的库存 Link。""" + with app.app_context(): + inventory_path = tmp_path / 'ot-owned-inventory.xlsx' + inventory_path.write_bytes(b'inventory-rows') + + # 先占用 Notice 自增 id=1,确保后续正式 Notice.id ≠ OT.id(复现生产错位)。 + db.session.add(ShippingNotice( + task_no='SN-INV-LINK-BURN', + user_id=1, + source_type='manual', + )) + db.session.flush() + + ot = ShippingOrderTask(task_no='OT-INV-LINK-OWNER', user_id=1, source_type='direct_pdf') + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-INV-LINK-OWNER', + storage_path=str(inventory_path), + source_file_name='ot-owned-inventory.xlsx', + snapshot_status='ready', + inventory_lines_json=[ + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001'}, + ], + line_count=1, + ) + db.session.add_all([ot, inventory_file]) + db.session.flush() + + notice = ShippingNotice( + task_no='SN-INV-LINK-OWNER', + user_id=1, + source_type='inventory_gate', + order_task_id=int(ot.id), + ) + db.session.add(notice) + db.session.flush() + assert int(notice.id) != int(ot.id) + + db.session.add(ShippingTaskInventoryLink( + task_id=int(ot.id), + inventory_file_id=int(inventory_file.id), + is_active=True, + access_mode='readonly', + )) + db.session.commit() + + # 断言:不得用 Notice.id 查 Link(会 miss);必须落到 OT Link。 + assert active_inventory_file_for_task(ot) is not None + assert active_inventory_file_for_task(ot).id == inventory_file.id + assert active_inventory_file_for_task(notice) is not None + assert active_inventory_file_for_task(notice).id == inventory_file.id + assert len(resolve_inventory_lines_for_execution(notice)) == 1 diff --git a/backend/tests/test_shipping_inventory_match_invalidation.py b/backend/tests/test_shipping_inventory_match_invalidation.py index 83a533b2..ad0ce8a9 100644 --- a/backend/tests/test_shipping_inventory_match_invalidation.py +++ b/backend/tests/test_shipping_inventory_match_invalidation.py @@ -22,11 +22,12 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app): from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile, ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, - ShippingUploadAttempt, + ShippingOrderTask, ShippingUploadAttempt, ) from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs - task = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1') + task = ShippingOrderTask(task_no='OT-CANDIDATE-INVALIDATE-1', user_id=1) + notice = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1') template = ShippingExcelTemplate( template_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1, status='published', storage_bucket='test', storage_key='template.xlsx', @@ -37,8 +38,9 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app): status='published', file_format='xlsx', definition_json={}, ) schema = ShippingOrderSchema(schema_code='CANDIDATE_INVALIDATE', display_name='Candidate invalidate') - db.session.add_all([task, template, profile, schema]) + db.session.add_all([task, notice, template, profile, schema]) db.session.flush() + notice.order_task_id = task.id version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) db.session.add(version) db.session.flush() @@ -46,7 +48,7 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app): db.session.add(extraction) db.session.flush() artifact = ShippingExportArtifact( - artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.id, template_id=template.id, + artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=notice.id, template_id=template.id, order_schema_version_id=version.id, order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, file_path='artifact.xlsx', file_name='artifact.xlsx', file_checksum='d' * 64, diff --git a/backend/tests/test_shipping_inventory_routing_engine.py b/backend/tests/test_shipping_inventory_routing_engine.py index f5755f6b..02cffc87 100644 --- a/backend/tests/test_shipping_inventory_routing_engine.py +++ b/backend/tests/test_shipping_inventory_routing_engine.py @@ -12,7 +12,7 @@ from app.extensions import db from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot, - ShippingOrderSnapshotLine, ShippingNotice, + ShippingOrderSnapshotLine, ShippingOrderTask, ) from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules from app.services.shipping_notice.order_schema import service as order_schema_service @@ -69,9 +69,9 @@ def _published_line_fields() -> dict[str, str]: def _task_with_line_values( fields: dict[str, str], values: dict[str, tuple[str, str]], -) -> tuple[ShippingNotice, dict[str, int]]: +) -> tuple[ShippingOrderTask, dict[str, int]]: """创建冻结快照;路由测试只允许从该不可变事实读取字段。""" - task = ShippingNotice(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual') + task = ShippingOrderTask(task_no='OT-DYNAMIC-ROUTE', user_id=1, source_type='eml') db.session.add(task) db.session.flush() extraction = ShippingOrderExtraction( @@ -80,7 +80,7 @@ def _task_with_line_values( ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() for field_id, (value, _purpose) in values.items(): @@ -106,7 +106,7 @@ def _task_with_line_values( db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, + snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''), part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']], field_values_json=snapshot_values, diff --git a/backend/tests/test_shipping_inventory_source_adjudication.py b/backend/tests/test_shipping_inventory_source_adjudication.py new file mode 100644 index 00000000..95c71c06 --- /dev/null +++ b/backend/tests/test_shipping_inventory_source_adjudication.py @@ -0,0 +1,152 @@ +""" +tests/test_shipping_inventory_source_adjudication.py + +用途:锁定库存源裁决不得在 unresolved/空候选时兜底全部启用源,并采纳行级 ambiguous。 +依赖:inventory_source_rules、inventory_routing_engine、pytest monkeypatch。 +逻辑:用可控引擎结果复现 OT-C68 类缺陷——行级 PREFIX 多候选被丢弃后膨胀为全源。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.services.shipping_notice.inventory_routing_engine import InventoryRoutingResult +from app.services.shipping_notice import inventory_source_rules as rules + + +def _source(code: str) -> dict: + """构造最小可裁决库存源字典。""" + return { + 'source_code': code, + 'display_name': code, + 'connector_type': 'dbs', + 'warehouse_resolution_mode': 'fixed', + 'fixed_warehouse_id': code, + } + + +def test_result_to_adjudication_unresolved_keeps_empty_candidates(monkeypatch): + """ + unresolved 且规则候选为空时,candidates 必须为空。 + + 关键断言:禁止 list_database_inventory_sources 全源兜底(OT-C68 根因之一)。 + """ + all_sources = [_source(f'SRC_{i}') for i in range(9)] + called = {'list_all': False} + + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: (called.__setitem__('list_all', True) or all_sources), + ) + monkeypatch.setattr(rules, 'get_database_inventory_source', lambda code: None) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + result = InventoryRoutingResult( + 'unresolved', + (), + (), + {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []}, + ) + adjudication = rules._result_to_adjudication(result, context={}) + + assert adjudication.status == 'unresolved' + assert adjudication.reason == 'routing_rule_unresolved' + assert adjudication.candidates == [] + assert called['list_all'] is False + + +def test_result_to_adjudication_ambiguous_only_keeps_rule_sources(monkeypatch): + """ + ambiguous 多候选只保留规则给出的源;缺失 DB 配置的源不得用全库补齐。 + """ + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: [_source('SHOULD_NOT_APPEAR'), _source('ALSO_NO')], + ) + monkeypatch.setattr( + rules, + 'get_database_inventory_source', + lambda code: _source(code) if code in {'A', 'B'} else None, + ) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + result = InventoryRoutingResult( + 'ambiguous', + ('A', 'B', 'MISSING'), + (33,), + { + 'priority': 100, + 'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'], + 'raw_source_codes': ['A', 'B', 'MISSING'], + }, + ) + adjudication = rules._result_to_adjudication(result, context={}) + + assert adjudication.status == 'ambiguous' + assert [item['source_code'] for item in adjudication.candidates] == ['A', 'B'] + + +def test_adjudicate_accepts_unanimous_line_ambiguous(monkeypatch): + """ + 任务级 unresolved、各行一致 ambiguous 时,必须采纳行级候选,不得回落全源。 + + 复现:Reservation 前缀规则给出 3 源 ambiguous,旧逻辑返回 9 个启用源。 + """ + line_ambiguous = InventoryRoutingResult( + 'ambiguous', + ('DSV360_AWSBI_BYAWSCMH01', 'DSV360_AWSBI_BYAWSFRA01', 'DSV360_AWSCV'), + (33,), + { + 'priority': 100, + 'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'], + 'raw_source_codes': [ + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSBI_BYAWSFRA01', + 'DSV360_AWSCV', + ], + }, + ) + task_unresolved = InventoryRoutingResult( + 'unresolved', + (), + (), + {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []}, + ) + + def _evaluate(*, task, line=None, now=None): + del task, now + return task_unresolved if line is None else line_ambiguous + + monkeypatch.setattr(rules, 'evaluate_inventory_source_rules', _evaluate) + monkeypatch.setattr(rules, 'extract_routing_context', lambda _task: {}) + monkeypatch.setattr( + rules, + '_task_routing_lines', + lambda _task, required=None: [{'reservation_id': '2000488715', '_position': 0}], + ) + monkeypatch.setattr( + rules, + 'get_database_inventory_source', + lambda code: _source(code), + ) + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: [_source(f'EXTRA_{i}') for i in range(9)], + ) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + adjudication = rules.adjudicate_inventory_source(SimpleNamespace(id=1)) + + assert adjudication.status == 'ambiguous' + assert [item['source_code'] for item in adjudication.candidates] == [ + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSBI_BYAWSFRA01', + 'DSV360_AWSCV', + ] + assert adjudication.reason == 'routing_rule_ambiguous' diff --git a/backend/tests/test_shipping_inventory_source_warehouse.py b/backend/tests/test_shipping_inventory_source_warehouse.py new file mode 100644 index 00000000..4e2c30fa --- /dev/null +++ b/backend/tests/test_shipping_inventory_source_warehouse.py @@ -0,0 +1,61 @@ +"""库存源仓库事实边界测试。""" + +from types import SimpleNamespace + +from app.models import ShippingNoticeLine +from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + + +def test_fixed_source_warehouse_comes_from_source_configuration_not_order_task() -> None: + """固定仓在 OT 不含仓库属性时仍由库存源配置确定。""" + task = SimpleNamespace(id=1, inventory_source_code='DUBLIN') + source = { + 'source_code': 'DUBLIN', + 'warehouse_resolution_mode': 'fixed', + 'fixed_warehouse_id': ' DUB ', + } + + assert resolve_inventory_source_warehouse_id(task, source=source) == 'DUB' + + +def test_dynamic_source_has_no_warehouse_before_verified_inventory_link() -> None: + """动态仓不得从 OT 推测,须等待库存文件或 Link 的已验证事实。""" + task = SimpleNamespace(id=1, inventory_source_code='DYNAMIC') + source = { + 'source_code': 'DYNAMIC', + 'warehouse_resolution_mode': 'inventory_match', + 'fixed_warehouse_id': None, + } + + assert resolve_inventory_source_warehouse_id(task, source=source) is None + + +def test_shipping_notice_line_owns_confirmed_inventory_facts() -> None: + """正式通知仓库、来源和文件必须是行级字段,而非通知单头或 OT 字段。""" + columns = ShippingNoticeLine.__table__.c + + assert {'inventory_source_code', 'inventory_file_id', 'inventory_warehouse_id'} <= set(columns.keys()) + + +def test_match_completed_requires_all_frozen_order_lines(monkeypatch) -> None: + """单个 Match 成功不能让尚有未匹配 Snapshot 项次的订单通过满足性 Gate。""" + from app.services.shipping_notice import fulfillment_workflow as workflow + + matched = SimpleNamespace(snapshot_line_id=101, match_result='matched', shortage_qty='0') + + class Query: + def filter_by(self, **_kwargs): + return self + + def all(self): + return [matched] + + class MatchModel: + query = Query() + + snapshot = SimpleNamespace(lines=[SimpleNamespace(id=101), SimpleNamespace(id=102)]) + monkeypatch.setattr('app.models.ShippingNoticeLineInventoryMatch', MatchModel) + monkeypatch.setattr(workflow.db.session, 'get', lambda _model, _identifier: snapshot) + monkeypatch.setattr(workflow, '_released_snapshot_line_ids_for_task', lambda _task: set()) + + assert workflow.match_completed(SimpleNamespace(id=1, order_snapshot_id=10)) is False diff --git a/backend/tests/test_shipping_line_scoped_inventory_retry.py b/backend/tests/test_shipping_line_scoped_inventory_retry.py new file mode 100644 index 00000000..85bbfdbd --- /dev/null +++ b/backend/tests/test_shipping_line_scoped_inventory_retry.py @@ -0,0 +1,245 @@ +""" +tests/test_shipping_line_scoped_inventory_retry.py + +用途:守门明细行重抓/重匹配按行 source_codes 收窄,且不伤已发通知行。 +依赖:pytest pure_unit、process_gate_executor、recovery_invalidation_service。 +逻辑:与 display-and-button-contract §6.1 行级收窄约定对齐;不启 Flask/DB。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +pytestmark = pytest.mark.pure_unit + + +def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch): + """行级重抓必须把该行 source_codes 交给 ensure_inventory,并收窄失效范围。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-SCOPE') + captured: list[dict] = [] + invalidate_calls: list[dict] = [] + line = SimpleNamespace(source_codes_json=['DBS']) + candidate_set = SimpleNamespace(id=1) + sources = [SimpleNamespace(source_code='DBS')] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: candidate_set, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines', + lambda _task: [line], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources', + lambda _task: sources, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope', + lambda _task, *, line_scope_key=None: { + 'snapshot_line_id': 1001, + 'line_no': 2, + 'source_codes': ['WH_A'], + } if line_scope_key not in (None, '') else None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **kwargs: invalidate_calls.append(dict(kwargs)) or {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._task_payload', + lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + + _handle_retry_inventory_preparation( + execution=SimpleNamespace(task_id=1, id=21, candidate_set_id=None), + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={ + 'action_code': 'retry_inventory_preparation', + 'actor_user_id': 5, + 'snapshot_line_id': 1001, + }, + ) + + # 关键断言:行级强制 RPA 只带该行源,失效也按同行源收窄。 + assert captured[-1].get('mode') == 'retry_rpa' + assert captured[-1].get('source_codes') == ['WH_A'] + assert captured[-1].get('snapshot_line_id') == 1001 + assert invalidate_calls[-1].get('source_codes') == ['WH_A'] + assert invalidate_calls[-1].get('snapshot_line_id') == 1001 + + +def test_inventory_matching_line_scope_uses_match_inventory_line(monkeypatch): + """行级重匹配必须走 match_inventory_line,并携带该行 source_codes。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-MATCH') + match_calls: list[dict] = [] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope', + lambda _task, *, line_scope_key=None: { + 'snapshot_line_id': 1002, + 'line_no': 3, + 'source_codes': ['WH_B'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._task_payload', + lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory_line', + lambda payload, *, line_no: match_calls.append({'payload': dict(payload), 'line_no': line_no}) + or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda _payload: (_ for _ in ()).throw(AssertionError('整单 match_inventory 不应被行级点击调用')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {}, + ) + + result = _handle_retry_inventory_matching( + execution=SimpleNamespace(task_id=1, id=21), + gate=SimpleNamespace(gate_code='inventory_matching'), + payload={'action_code': 'retry_inventory_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5}, + ) + + assert match_calls and match_calls[0]['line_no'] == 3 + assert match_calls[0]['payload'].get('source_codes') == ['WH_B'] + assert result['outcome'] == 'passed' + + +def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch): + """行级失效不得改写已发通知行匹配,也不得 supersede 已有 Notice Artifact。""" + from app.services.shipping_notice import recovery_invalidation_service as svc + + link_a = SimpleNamespace( + id=11, inventory_file_id=101, matched_source_code='WH_A', + is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + link_b = SimpleNamespace( + id=12, inventory_file_id=102, matched_source_code='WH_B', + is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + match_open = SimpleNamespace( + id=21, snapshot_line_id=1001, inventory_source_code='WH_A', + allowed_source_codes_snapshot=['WH_A'], is_current=True, + invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + match_noticed = SimpleNamespace( + id=22, snapshot_line_id=1002, inventory_source_code='WH_A', + allowed_source_codes_snapshot=['WH_A'], is_current=True, + invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + + class _Query: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **_kwargs): + return self + + def with_for_update(self): + return self + + def all(self): + return list(self._rows) + + def filter(self, *_a, **_k): + return self + + monkeypatch.setattr(svc, '_noticed_snapshot_line_ids', lambda _task_id: {1002}) + monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['inventory_matching']) + monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: SimpleNamespace(id=1)) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + # 纯单测不启 Flask:替换模块内模型符号,避免触碰 Flask-SQLAlchemy query 描述符。 + monkeypatch.setattr( + svc, + 'ShippingTaskInventoryLink', + SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([link_a, link_b]))), + ) + monkeypatch.setattr( + svc, + 'ShippingNoticeLineInventoryMatch', + SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([match_open, match_noticed]))), + ) + monkeypatch.setattr( + svc, + 'ShippingInventoryMapping', + SimpleNamespace( + inventory_file_id=SimpleNamespace(in_=lambda _ids: True), + status='active', + query=SimpleNamespace(filter=lambda *_a, **_k: _Query([])), + ), + ) + monkeypatch.setattr( + svc, + 'ShippingNotice', + SimpleNamespace( + query=SimpleNamespace( + filter_by=lambda **_: (_ for _ in ()).throw(AssertionError('行级失效不得查询 Notice Artifact')) + ) + ), + ) + + result = svc.invalidate_inventory_downstream( + execution=SimpleNamespace(task_id=1), + action_code='retry_inventory_preparation', + attempt_id=9, + source_codes=['WH_A'], + snapshot_line_id=1001, + ) + + assert link_a.is_active is False + assert link_b.is_active is True + assert match_open.is_current is False + assert match_noticed.is_current is True + assert result['links'] == [11] + assert result['matches'] == [21] + assert result['artifacts'] == [] + assert result['uploads'] == [] diff --git a/backend/tests/test_shipping_line_source_ambiguity.py b/backend/tests/test_shipping_line_source_ambiguity.py new file mode 100644 index 00000000..37ac2559 --- /dev/null +++ b/backend/tests/test_shipping_line_source_ambiguity.py @@ -0,0 +1,83 @@ +""" +tests/test_shipping_line_source_ambiguity.py + +用途:锁定多候选库存源「数据自证 + 歧义兜底」契约(设计 D4/D5,2026-08-29)。 +依赖:stp_line_inventory_match.match_order_lines_across_candidates。 +逻辑:同一行命中多源必须 multi_file_conflict 阻断并携带候选源列表(禁止静默选源); + 唯一源命中按行反写 源/可用量/缺口。既有能力以测试固化,防止后续回归。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.stp_line_inventory_match import ( + match_order_lines_across_candidates, +) + + +def test_same_reservation_across_two_sources_marks_conflict_with_candidates(): + """[断言] 同一预约单在两个源都有库存:该行 multi_file_conflict 阻断并带候选源列表, + resolved source 必须为空(选源交由人工 override_line_inventory_source)。""" + result = match_order_lines_across_candidates( + order_lines=[{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}], + inventory_lines=[ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'}, + ], + ) + line = result['line_results'][0] + assert line['disposition'] == 'multi_file_conflict' + assert set(line['candidate_hit_source_codes']) == {'SRC_A', 'SRC_B'} + assert line['resolved_inventory_source_code'] is None + # 歧义行必须阻断整单可履行状态,防止带着未定源进入导出。 + assert result['match_status'] == 'unfulfillable' + assert result['resolutions'][0]['candidate_hit_source_codes'] == line['candidate_hit_source_codes'] + + +def test_unique_source_hit_writes_back_source_qty_and_shortage(): + """[断言] 唯一源命中:足量反写 ok+源+零缺口;不足反写 shortage+缺口数量。""" + base_lines = [ + {'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}, + ] + inventory_full = [ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + ] + result_full = match_order_lines_across_candidates( + order_lines=base_lines, inventory_lines=inventory_full, + ) + line_full = result_full['line_results'][0] + assert line_full['line_status'] == 'ok' + assert line_full['resolved_inventory_source_code'] == 'SRC_A' + assert line_full['available_qty'] == 5.0 + assert line_full['shortage_qty'] == 0.0 + + inventory_short = [ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'SRC_A'}, + ] + result_short = match_order_lines_across_candidates( + order_lines=base_lines, inventory_lines=inventory_short, + ) + line_short = result_short['line_results'][0] + assert line_short['line_status'] == 'partial' # 有货但不足 → partial(disposition=shortage) + assert line_short['disposition'] == 'shortage' + assert line_short['resolved_inventory_source_code'] == 'SRC_A' + assert line_short['available_qty'] == 2.0 + assert line_short['shortage_qty'] == 3.0 + + +def test_disambiguation_via_pinned_allowed_sources_resolves_conflict(): + """[断言] 人工选源后(行 allowed_source_codes 钉住单一源):原冲突行在钉住源内正常匹配, + 这是 override_line_inventory_source 行级重匹配的数据前提。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5', + 'allowed_source_codes': ['SRC_B'], + }], + inventory_lines=[ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'}, + ], + ) + line = result['line_results'][0] + assert line['disposition'] == 'ok' + assert line['resolved_inventory_source_code'] == 'SRC_B' + assert line['available_qty'] == 9.0 diff --git a/backend/tests/test_shipping_manual_upload_evidence.py b/backend/tests/test_shipping_manual_upload_evidence.py index bf8f35a3..7914254f 100644 --- a/backend/tests/test_shipping_manual_upload_evidence.py +++ b/backend/tests/test_shipping_manual_upload_evidence.py @@ -1,52 +1,42 @@ """ -用途:验证人工上传必须引用用户私有回执资产。 -依赖:上传 Attempt 服务、FileAsset 服务、滚动履约测试夹具。 -逻辑:无回执请求被拒;有已上传资产时创建 manual Attempt 并锁定预约单。 +用途:验证人工上传不再要求回执/截图证据,仅记录目标 Excel Artifact 与服务端操作人。 +依赖:上传 Attempt 服务、滚动履约测试夹具。 +逻辑:人工确认无需回执资产即成功创建 manual Attempt 并锁定预约单。 """ from __future__ import annotations -from io import BytesIO - import pytest -from werkzeug.datastructures import FileStorage from app import db -from app.core.errors import ValidationError from app.models import ShippingUploadAttempt, User -from app.services.file_assets.service import upload_file_asset from app.services.shipping_notice.upload_attempt_service import record_manual_upload from tests.test_shipping_upload_attempt import _ready_artifact -def test_manual_upload_requires_receipt_asset(app): - """人工确认不可仅凭文本或参考号,缺少回执文件必须返回专用业务错误。""" +def test_manual_upload_requires_no_receipt_asset(app): + """人工确认不再采集回执/截图证据;仅凭操作者与目标 Excel 即可成功。""" with app.app_context(): task, artifact, _reservation = _ready_artifact() user = User(username='manual-evidence', email='manual-evidence@example.test', password_hash='x') db.session.add(user); db.session.flush() - with pytest.raises(ValidationError) as exc_info: - record_manual_upload(task, artifact_id=artifact.id, evidence_asset_no='', operator_id=user.id) - assert exc_info.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED' + attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id) + assert attempt.mode == 'manual' + assert attempt.evidence_asset_id is None + assert attempt.freight_ref_no is None -def test_manual_upload_records_receipt_asset(app): - """已上传的私有截图资产会成为 manual Attempt 的不可变证据。""" +def test_manual_upload_records_operator_and_locks_reservation(app): + """人工确认记录操作者并完成上传事实;不产生任何截图/PDF 证据。""" with app.app_context(): task, artifact, reservation = _ready_artifact() user = User(username='manual-evidence-ok', email='manual-evidence-ok@example.test', password_hash='x') db.session.add(user); db.session.commit() - payload = upload_file_asset( - user_id=user.id, - upload=FileStorage(stream=BytesIO(b'receipt'), filename='receipt.png', content_type='image/png'), - ) - attempt = record_manual_upload( - task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id, - freight_ref_no='FREIGHT-RECEIPT-1', - ) + attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id) assert attempt.mode == 'manual' assert attempt.status == 'succeeded' - assert attempt.evidence_asset_id is not None - assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1' + assert attempt.evidence_asset_id is None + assert attempt.freight_ref_no is None + assert attempt.operator_id == user.id assert db.session.get(type(reservation), reservation.id).status == 'uploaded' assert ShippingUploadAttempt.query.count() == 1 diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index 66e9d5f0..a9bb332f 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -56,25 +56,43 @@ def test_replacement_links_to_parent_notice(app): def test_create_task_assigns_notice_customer_and_serializes_it(app): - """真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。""" + """真实单票建单直接写分立的客户识别结果,不依赖 ShippingCase;OT 建单本身不阻断。""" + from app.models import ShippingOrderTask, User + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + from app.services.shipping_notice.query_service import serialize_task_for_tool + from tests.conftest import confirm_test_customer_resolution + with app.app_context(): customer = _active_customer(short_code='CRT') + user = User(username='create-task-crt', email='create-task-crt@example.test', password_hash='x') + db.session.add(user) + db.session.flush() result = create_task({ - 'source_type': 'manual', + 'source_type': 'direct_pdf', 'raw_content': 'customer notice', - 'customer_id': customer.id, + 'user_id': user.id, }) - task = ShippingNotice.query.filter_by(task_no=result['task_id']).one() - assert task.customer_resolution_status == 'confirmed' - assert task.customer_id == customer.id - assert result['data']['customer_id'] == customer.id + task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one() + # [FIX] 客户确认由独立识别结果承载;建单不再阻塞(见 create_task 迁移注释)。 + confirm_test_customer_resolution(task, customer=customer) + facts = customer_resolution_facts(task) + assert facts['status'] == 'confirmed' + assert facts['customer_id'] == customer.id + assert serialize_task_for_tool(task)['customer_id'] == customer.id -def test_create_task_rejects_without_customer(app): - """未确认客户时禁止创建 Task,避免落入 customer_review。""" +def test_create_task_defers_customer_confirmation(app): + """未确认客户时不再阻断建单;客户确认交由订单复核/客户门禁处理。""" + from app.models import ShippingOrderTask, User + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + with app.app_context(): - with pytest.raises(ConflictError) as exc_info: - create_task({'source_type': 'manual', 'raw_content': 'customer notice'}) - assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK' + user = User(username='create-task-nocust', email='create-task-nocust@example.test', password_hash='x') + db.session.add(user) + db.session.flush() + result = create_task({'source_type': 'direct_pdf', 'raw_content': 'customer notice', 'user_id': user.id}) + task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one() + assert task is not None + assert customer_resolution_facts(task)['status'] != 'confirmed' diff --git a/backend/tests/test_shipping_notice_business_dedup.py b/backend/tests/test_shipping_notice_business_dedup.py index abe6d681..bec66dd5 100644 --- a/backend/tests/test_shipping_notice_business_dedup.py +++ b/backend/tests/test_shipping_notice_business_dedup.py @@ -21,6 +21,7 @@ from app.models import ( ShippingOrderDocument, ShippingOrderIntake, ShippingNotice, + ShippingOrderTask, User, ) from app.services.shipping_notice.business_fingerprint import ( @@ -88,6 +89,106 @@ def _seed_parsed_intake( return asset, intake +def _seed_existing_notice_task( + user_id: int, + *, + task_no: str, + business_fingerprint: str, + fingerprint_version: str, + content_fingerprint: str | None = None, + content_fingerprint_version: str | None = None, + source_content_hash: str | None = None, + document_version: int = 1, +) -> ShippingNotice: + """ + 构造一个已建单的正式发货通知,作为业务指纹去重的命中目标。 + + 新契约:ShippingNotice 不再保存指纹投影;business/content 指纹转移到被消费的 + ShippingOrderCandidate(consumed_task_id -> 建单前 OT),Notice 经 order_task_id + 挂接该 OT。只有建立 Notice→Task→Candidate 这条链,duplicate_detection 的 + Notice→Task(consumed_task_id)→Candidate 查询才能命中——这是 key 断言, + 不是只为了消除构造参数,而是让「已有任务重复」真正可被探测。 + """ + ot = ShippingOrderTask( + task_no=f'OT-{task_no}', + user_id=user_id, + source_type='eml', + lifecycle_status='active', + ) + db.session.add(ot) + db.session.flush() + + asset = FileAsset( + asset_no=f'FA-{task_no}', + owner_user_id=user_id, + original_filename='existing.txt', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user_id}/{task_no}.txt', + content_hash=source_content_hash or f'hash-{task_no}', + file_size=1, + mime_type='text/plain', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + + intake = ShippingOrderIntake( + intake_no=f'SNI-{task_no}', + asset_id=asset.id, + user_id=user_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v1', + duplicate_status='none', + ) + db.session.add(intake) + db.session.flush() + + doc = ShippingOrderDocument( + intake_id=intake.id, + attachment_key=f'att-{task_no}', + document_type='attachment', + filename=f'{task_no}.pdf', + content_hash=source_content_hash or f'hash-{task_no}', + classification='order_notice', + parse_status='parsed', + ) + db.session.add(doc) + db.session.flush() + + candidate = ShippingOrderCandidate( + candidate_no=f'SNC-{task_no}', + intake_id=intake.id, + primary_document_id=doc.id, + candidate_key=f'test:{task_no}', + business_fingerprint=business_fingerprint, + fingerprint_version=fingerprint_version, + content_fingerprint=content_fingerprint, + content_fingerprint_version=content_fingerprint_version, + consumed_task_id=ot.id, + duplicate_status='none', + candidate_status='accepted', + selected=True, + ) + db.session.add(candidate) + db.session.flush() + ot.candidate_id = candidate.id + + notice = ShippingNotice( + task_no=task_no, + user_id=user_id, + source_type='manual', + document_version=document_version, + order_task_id=ot.id, + lifecycle_status='active', + ) + db.session.add(notice) + db.session.commit() + return notice + + def test_business_fingerprint_ignores_internal_hex_reservation_id(): """内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。""" summary = { @@ -185,16 +286,13 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user): business_summary=summary, fingerprint=fp, ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-PENDING-1', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=fp['fingerprint'], fingerprint_version=fp['version'], document_version=1, ) - db.session.add(existing) - db.session.commit() result = detect_duplicates_for_intake( intake=intake, @@ -250,15 +348,13 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user): 'lines': [], } ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-EXISTING-PO-A', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=existing_fp['fingerprint'], fingerprint_version=existing_fp['version'], source_content_hash='hash-other-file', ) - db.session.add(existing) parent = FileAsset( asset_no='FA-STAGE2-DEDUP-EML', @@ -372,15 +468,13 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user): 'lines': [], } ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-REFRESH-EXISTING', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=existing_fp['fingerprint'], fingerprint_version=existing_fp['version'], source_content_hash='hash-refresh-other', ) - db.session.add(existing) parent = FileAsset( asset_no='FA-REFRESH-DEDUP', @@ -479,16 +573,14 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a } identity = build_business_fingerprint(base) content = build_content_fingerprint(base) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-CONTENT-EXISTING', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=identity['fingerprint'], fingerprint_version=identity['version'], content_fingerprint=content['fingerprint'], content_fingerprint_version=content['version'], ) - db.session.add(existing) parent, intake = _seed_parsed_intake( dedup_user.id, intake_no='SNI-CONTENT-CHECK', diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 06e7e69a..cdef622b 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -30,13 +30,13 @@ def _table_schema_definition() -> dict: aliases = { 'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'], 'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'], - 'amount': ['Amount'], 'currency': ['Currency'], + 'line_amount_with_tax': ['Amount'], 'currency': ['Currency'], 'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'], 'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'], 'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'], 'inventory_source_hint': ['source type'], 'po_number': ['PO'], } - decimal_fields = {'qty', 'unit_price', 'amount'} + decimal_fields = {'qty', 'unit_price', 'line_amount_with_tax'} return {'fields': [{ 'field_id': f'test-{code}', 'field_code': code, 'scope': 'header' if code == 'po_number' else 'line', @@ -1318,7 +1318,8 @@ def test_extract_eml_keeps_inline_pdf_attachment(tmp_path): assert "PO-INLINE-PDF" in text -def test_extract_reservation_id_from_pr_number(): +def test_extract_reservation_id_from_at_delimited_pr_number(): + """PR Number 中以 ``@`` 明确分隔的完整数字可作为 Reservation ID。""" assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351" assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351" @@ -1409,14 +1410,11 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA lines = parse_notice_table_text(text, contract=_table_contract()) assert len(lines) == 1 assert lines[0]["part_number"] == "B3-A08AR11000001" - assert lines[0]["line_no"] == "10" assert lines[0]["qty"] == 9.0 assert lines[0]["unit_price"] == 1607.72 assert lines[0]["amount"] == 14469.48 assert "reservation_id" not in lines[0] assert lines[0]["required_date"] == "2026-06-15" - assert lines[0]["aws_part_number"] == "504-010213-001" - assert lines[0]["currency"] == "USD" def test_normalize_reservation_id_from_excel_float(): @@ -1453,37 +1451,53 @@ def test_does_not_infer_reservation_id_without_configured_header(): def test_parse_notice_table_with_all_fields(): text = """ Part Number\tReservation ID\tQty\tUnit Price\tAmount -10-40594-001\tAWS-311\t2\t15.5\t31.0 -10-40594-002\tORD-3002\t1\t20\t20 +10-40594-001\t1000140351\t2\t15.5\t31.0 +10-40594-002\t1000140352\t1\t20\t20 """ lines = parse_notice_table_text(text, contract=_table_contract()) assert len(lines) == 2 assert lines[0]["part_number"] == "10-40594-001" - assert lines[0]["reservation_id"] == "AWS-311" + assert lines[0]["reservation_id"] == "1000140351" assert lines[0]["qty"] == 2 assert lines[0]["unit_price"] == 15.5 assert lines[0]["amount"] == 31.0 def test_normalize_notice_line_aliases(): + # 表头业务别名不再内置于代码;只经本次冻结 Schema 解析(见 notice_lines 迁移说明)。 + # line_no 为系统生成项次,不参与 normalize 派生,故从结果中移除。 + schema_definition = { + 'fields': [ + {'field_id': 't-line_no', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, 'aliases': ['Line No']}, + {'field_id': 't-part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['quantity']}, + {'field_id': 't-rid', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'aliases': ['com_id']}, + {'field_id': 't-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['price']}, + {'field_id': 't-amount', 'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': []}, + {'field_id': 't-currency', 'field_code': 'currency', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-date', 'field_code': 'required_date', 'scope': 'line', 'value_type': 'date', 'enabled': True, 'aliases': ['delivery_date']}, + {'field_id': 't-cust', 'field_code': 'customer_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-aws', 'field_code': 'aws_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + ] + } line = normalize_notice_line( { "part_number": "A-001", "quantity": "3", - "com_id": "COM-99", + "com_id": "1000140351", "price": "12.5", "delivery_date": "2026/06/15", "customer_part_number": "CUST-001", "aws_part_number": "AWS-001", "currency": "USD", "line_no": "10", - } + }, + schema_definition=schema_definition, ) assert line == { - "line_no": "10", "part_number": "A-001", "qty": 3.0, - "reservation_id": "COM-99", + "reservation_id": "1000140351", "unit_price": 12.5, "amount": 37.5, "currency": "USD", @@ -1611,7 +1625,7 @@ def test_normalize_notice_line_rejects_ambiguous_composite(value): def test_parse_notice_table_maps_three_part_number_roles(): - """MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。""" + """MPN 与 Allocated HHPN 进入内部料号与客户料号;Allocated APN 已移出表格字段目录,不再按行解析。""" lines = parse_notice_table_rows( ["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"], [["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]], @@ -1621,7 +1635,6 @@ def test_parse_notice_table_maps_three_part_number_roles(): assert lines == [{ "part_number": "D4-A08AR12000002", "customer_part_number": "TEMP-S000218929", - "aws_part_number": "504-006055-001", "qty": 10.0, }] @@ -1676,7 +1689,7 @@ def test_extract_notice_fields_structured(): { "part_number": "10-40594-001", "qty": 2, - "reservation_id": "AWS-311", + "reservation_id": "1000140351", "unit_price": 10, "amount": 20, } @@ -1684,7 +1697,7 @@ def test_extract_notice_fields_structured(): "confidence": 0.9, } parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured) - assert parsed["lines"][0]["reservation_id"] == "AWS-311" + assert parsed["lines"][0]["reservation_id"] == "1000140351" assert parsed["lines"][0]["amount"] == 20 assert confidence >= 0.8 assert not any("未解析到有效订单行" in w for w in warnings) @@ -1702,12 +1715,12 @@ def test_heuristic_table_skips_title_row(): text = """ Shipping Notice Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount -10-40594-001\tORD-3002\t4\t5\t20 +10-40594-001\t1000140351\t4\t5\t20 """ parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition()) assert len(parsed["lines"]) == 1 assert parsed["lines"][0]["part_number"] == "10-40594-001" - assert parsed["lines"][0]["reservation_id"] == "ORD-3002" + assert parsed["lines"][0]["reservation_id"] == "1000140351" assert parsed["lines"][0]["qty"] == 4 assert parsed["lines"][0]["unit_price"] == 5 assert parsed["lines"][0]["amount"] == 20 @@ -1733,7 +1746,7 @@ def test_extract_notice_fields_structured_over_heuristic(): def test_extract_notice_fields_heuristic_fallback(): """无 structured 时走后端启发式兜底。""" - text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4" + text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\t1000140351\t4" parsed, _, warnings = extract_notice_fields( raw_text=text, schema_definition=_table_schema_definition(), ) diff --git a/backend/tests/test_shipping_notice_field_adjudication.py b/backend/tests/test_shipping_notice_field_adjudication.py index 313cf526..b352b164 100644 --- a/backend/tests/test_shipping_notice_field_adjudication.py +++ b/backend/tests/test_shipping_notice_field_adjudication.py @@ -170,7 +170,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only(): """Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。""" document = _document( 1, - "MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2", + "MPN\tQty\tReservation ID\nD4-A\t10\t10001\nD4-B\t20\t10002", ) result = adjudicate_order_fields( @@ -181,7 +181,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only(): ) assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"] - assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"] + assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["10001", "10002"] assert trusted_required_fields(result) is True diff --git a/backend/tests/test_shipping_notice_intakes_lifecycle.py b/backend/tests/test_shipping_notice_intakes_lifecycle.py index 73334d52..89a93e1b 100644 --- a/backend/tests/test_shipping_notice_intakes_lifecycle.py +++ b/backend/tests/test_shipping_notice_intakes_lifecycle.py @@ -21,6 +21,8 @@ from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.models import ( FileAsset, + ShippingCustomer, + ShippingCustomerShadowResolution, ShippingDocumentLayoutVersion, ShippingOrderCandidate, ShippingOrderDocument, @@ -29,6 +31,7 @@ from app.models import ( ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingNotice, + ShippingOrderTask, User, ) from app.services.file_assets.service import upload_file_asset @@ -201,12 +204,37 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): classification='order_notice', parse_status='parsed', ) - existing = ShippingNotice( + # 重复目标由建单前 OT(ShippingOrderTask)及其正式 Notice、已消费同哈希 Intake + # 共同构成 exact_file 匹配链(ShippingNotice.order_task_id → OT → consumed Intake → FileAsset)。 + existing_task = ShippingOrderTask( + task_no='OT-CANDIDATE-EXISTING-001', user_id=owner.id, + lifecycle_status='active', + ) + db.session.add(existing_task) + existing_asset = FileAsset( + asset_no='FA-CANDIDATE-EXISTING-001', owner_user_id=owner.id, + original_filename='order-7001.pdf', storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{owner.id}/existing/order-7001.pdf', + content_hash='candidate-api-content-hash', file_size=100, + mime_type='application/pdf', upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(existing_asset) + db.session.flush() + # OT/资产主键在会话内固化,供跨 app_context 重挂 Notice 时使用(避免 DetachedInstance 刷新)。 + existing_task_id = int(existing_task.id) + existing_notice = ShippingNotice( task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, - source_content_hash=asset.content_hash, + order_task_id=existing_task_id, ) - db.session.add_all([document, existing]) + consumed_intake = ShippingOrderIntake( + intake_no='SNI-CANDIDATE-EXISTING-CONSUMED', asset_id=existing_asset.id, + user_id=owner.id, purpose='shipping_notice', parse_status='consumed', + parser_version='v6', consumed_task_id=existing_task_id, + ) + db.session.add_all([document, existing_notice, consumed_intake]) db.session.flush() candidate = ShippingOrderCandidate( candidate_no='SNC-CANDIDATE-API-001', @@ -220,14 +248,10 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}], }, }, - validation_status='needs_review', - conflicts_json=[{'field': 'qty'}], + validation_status='ready', + conflicts_json=[], extraction_source='dify_workflow', selected=True, - duplicate_resolution='open_existing', - duplicate_target_task_no=existing.task_no, - duplicate_resolved_by_id=owner.id, - duplicate_resolved_at=datetime.utcnow(), ) db.session.add(candidate) db.session.commit() @@ -236,13 +260,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): patch_response = client.patch( '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001', - json={ - 'selected': False, - 'business_summary': { - 'po_number': '7001', - 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}], - }, - }, + json={'selected': False}, headers=owner_headers, ) assert patch_response.status_code == 200 @@ -273,13 +291,13 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): assert repeated.status_code == 200 assert repeated.get_json()['data']['candidate_status'] == 'accepted' assert patched['conflicts'] == [] - assert patched['content_fingerprint'] + assert promoted['content_fingerprint'] assert patched['duplicate_resolution'] is None with app.app_context(): db.session.add(ShippingNotice( task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, - source_content_hash='candidate-api-content-hash', + order_task_id=existing_task_id, )) db.session.commit() @@ -323,122 +341,36 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): ) assert consumed.status_code == 409 -def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client): - """人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。""" - from app.core.auth.jwt import issue_local_access_token - - with app.app_context(): - user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x') - db.session.add(user) - db.session.flush() - asset = FileAsset( - asset_no='FA-CANDIDATE-VALIDATION', - owner_user_id=user.id, - original_filename='invalid-order.pdf', - storage_provider='minio', - storage_bucket='hxops-file-assets', - storage_key=f'temporary/{user.id}/invalid-order.pdf', - content_hash='candidate-validation-hash', - file_size=10, - mime_type='application/pdf', - upload_status='ready', - lifecycle_status='temporary', - ) - db.session.add(asset) - db.session.flush() - intake = ShippingOrderIntake( - intake_no='SNI-CANDIDATE-VALIDATION', - asset_id=asset.id, - user_id=user.id, - purpose='shipping_notice', - parse_status='parsed', - parser_version='v6', - ) - db.session.add(intake) - db.session.flush() - document = ShippingOrderDocument( - intake_id=intake.id, - asset_id=asset.id, - document_type='attachment', - attachment_key='invalid-order', - filename='invalid-order.pdf', - content_hash=asset.content_hash, - classification='order_notice', - parse_status='parsed', - ) - db.session.add(document) - db.session.flush() - candidate = ShippingOrderCandidate( - candidate_no='SNC-CANDIDATE-VALIDATION', - intake_id=intake.id, - primary_document_id=document.id, - candidate_key='test:SNC-CANDIDATE-VALIDATION', - structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}}, - validation_status='needs_review', - selected=True, - ) - db.session.add(candidate) - db.session.commit() - headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} - - empty = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': {}}, - headers=headers, - ) - assert empty.status_code == 400 - assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED' - - invalid_qty = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}}, - headers=headers, - ) - assert invalid_qty.status_code == 400 - - invalid_reservation = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={ - 'business_summary': { - 'lines': [ - { - 'part_number': 'SKU-1', - 'qty': 1, - 'reservation_id': '1f1a682dfdc446a393415dee93eb36ce', - } - ] - } - }, - headers=headers, - ) - assert invalid_reservation.status_code == 400 - assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED' - - invalid_selected = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'selected': 'false'}, - headers=headers, - ) - assert invalid_selected.status_code == 400 - - null_summary = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': None}, - headers=headers, - ) - assert null_summary.status_code == 400 - def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user): """provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。""" from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready with app.app_context(): + # 建 Task 前客户必须已确认(ShippingCustomerShadowResolution 承载该事实)。 + customer = ShippingCustomer(standard_name='Acceptance Customer', short_code='ACPT', status='active') + db.session.add(customer) + db.session.flush() candidate = ShippingOrderCandidate( candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate', intake_id=1, primary_document_id=1, selected=True, candidate_status='provisional', is_current_version=True, - validation_status='ready', conflicts_json=[], + validation_status='ready', conflicts_json=[], acceptance_mode='manual', ) + db.session.add(candidate) + db.session.flush() + # 客户确认事实只承载于影子识别结果;不再落 Notice/OT 列。 + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=candidate.intake_id, + resolution_version='test.v1', status='confirmed', + confirmed_customer_id=customer.id, confirmation_method='manual', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': 'ACPT'}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + db.session.add(resolution) + db.session.commit() + with pytest.raises(ConflictError) as provisional: ensure_candidate_fulfillment_ready(candidate) assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED' @@ -514,13 +446,20 @@ def test_create_intake_integrity_race_returns_existing(app, shipping_user, monke def _boom_nested(): class _CM: def __enter__(self): - raise IntegrityError('stmt', {}, Exception('uq')) + # 仅注入一次 IntegrityError:模拟 Intake 唯一约束竞争; + # 后续(如 Submission 归属)SAVEPOINT 正常通过。 + if nested_calls['n'] == 0: + nested_calls['n'] += 1 + raise IntegrityError('stmt', {}, Exception('uq')) + return True def __exit__(self, *args): return False return _CM() + nested_calls = {'n': 0} + monkeypatch.setattr(db.session, 'begin_nested', _boom_nested) payload = create_shipping_notice_intake( @@ -637,7 +576,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user): task_no='SN-REV-LOCK-BASE', user_id=shipping_user.id, source_type='manual', - upload_status='uploaded', document_version=1, ) db.session.add(base) @@ -1062,69 +1000,3 @@ def test_intake_status_api_strips_texts_detail_returns_full(app, client): # 避免未使用变量告警 assert other_id != owner_id -def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch): - """解析完成后取消须删除 Document/Candidate 并归零派生资产引用。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import cancel_intake - - msg = EmailMessage() - msg['Subject'] = 'cancel after parse' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'), - maintype='application', - subtype='pdf', - filename='cancel.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='cancel.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-CANCEL', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.commit() - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'parsed' - derived = ( - db.session.query(FileAsset) - .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) - .one() - ) - assert int(derived.reference_count or 0) >= 1 - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1 - - cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL') - db.session.expire_all() - cancelled = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one() - assert cancelled.parse_status == 'cancelled' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=cancelled.id).count() == 0 - assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=cancelled.id).count() == 0 - derived2 = db.session.get(FileAsset, derived.id) - assert int(derived2.reference_count or 0) == 0 - assert derived2.lifecycle_status == 'temporary' - diff --git a/backend/tests/test_shipping_notice_intakes_parse.py b/backend/tests/test_shipping_notice_intakes_parse.py index eed81883..bffad489 100644 --- a/backend/tests/test_shipping_notice_intakes_parse.py +++ b/backend/tests/test_shipping_notice_intakes_parse.py @@ -804,81 +804,14 @@ def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate( with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): result = run_intake_parse(intake, parent) assert result['status'] == 'parsed' - att = ( - db.session.query(ShippingOrderDocument) - .filter_by(intake_id=intake.id, document_type='attachment') - .one() - ) - assert att.classification == 'supporting' + # 普通发货通知上传只落摘要,不建 Document/Candidate;落库在发送/物化阶段。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=intake.id).count() == 0 -def test_stage2_persist_failure_marks_parse_failed_and_allows_retry( - app, shipping_user, monkeypatch, -): - """阶段二持久化失败须 parse_failed,且可 retry_intake_parse。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import retry_intake_parse - - msg = EmailMessage() - msg['Subject'] = 'fail stage2' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: 999001'), - maintype='application', - subtype='pdf', - filename='one.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='fail.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-FAIL', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.commit() - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', - lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')), - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'parse_failed' - db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one() - assert failed.parse_status == 'parse_failed' - assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED' - - with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777): - retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL') - assert retried['parse_status'] == 'queued' - def test_upload_preprocess_does_not_invoke_candidate_dedup( app, shipping_user, monkeypatch, ): - """上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。""" + """上传预处理只落摘要,不建 Document/Candidate;订单 Candidate 判重函数即使不可用也不影响预处理。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse @@ -937,13 +870,14 @@ def test_upload_preprocess_does_not_invoke_candidate_dedup( assert refreshed.parse_status == 'parsed' assert refreshed.order_extraction_status == 'not_started' assert refreshed.duplicate_matches_json in (None, []) - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() >= 1 + # 普通发货通知上传只落摘要,不建 Document / 不生成 Candidate (落库在发送/物化阶段)。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=refreshed.id).count() == 0 def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( app, shipping_user, monkeypatch, ): - """阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。""" + """普通发货通知上传阶段不落库、不判重:预置的 duplicate 状态在上传后保持原值(stage2 清理已不再存在)。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse @@ -1004,25 +938,24 @@ def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( db.session.commit() with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): result = run_intake_parse(intake, parent) - assert result['status'] == 'parse_failed' + # 普通发货通知上传阶段不落库、不判重:persist_documents_and_candidates 不被调用, + # 即使 monkeypatch 抛异常也不影响。判重属于抽取/建单链路的字段,普通上传分支会 + # 把它重置回默认值(unchecked / 空)而非保留先前值;Intake 回 parsed。 + assert result['status'] == 'parsed' db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by( + parsed = db.session.query(ShippingOrderIntake).filter_by( intake_no='SNI-STAGE2-CLEAR-DUP' ).one() - assert failed.parse_status == 'parse_failed' - assert failed.duplicate_status == 'unchecked' - assert failed.duplicate_matches_json in (None, []) - assert failed.business_fingerprint is None - assert failed.fingerprint_version is None - assert failed.fingerprint_strength is None - assert failed.duplicate_resolution is None - assert failed.duplicate_resolution_reason is None - assert failed.duplicate_target_task_no is None - assert failed.duplicate_resolved_at is None - payload = serialize_intake(failed, asset=parent) - dup = payload.get('duplicate') or {} - assert (dup.get('matches') or []) == [] - assert payload.get('duplicate_resolution') is None + assert parsed.parse_status == 'parsed' + assert parsed.order_extraction_status == 'not_started' + assert parsed.duplicate_status == 'unchecked' + assert (parsed.duplicate_matches_json or []) == [] + assert parsed.business_fingerprint is None + assert parsed.duplicate_resolution is None + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0 + assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0 + payload = serialize_intake(parsed, asset=parent) + assert (payload.get('duplicate') or {}).get('matches') or [] == [] def test_derived_asset_refcount_increments_per_document_link(app, shipping_user): """多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。""" @@ -1383,88 +1316,12 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp summary = failed.structured_result_json or {} assert 'document_count' not in summary -def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch): - """阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。""" +def test_stage2_persist_does_not_run_for_plain_shipping_notice(app, shipping_user, monkeypatch): + """普通发货通知上传阶段不调 stage2 持久化:persist_documents_and_candidates 不可用也不影响(返回 parsed,不建 Document)。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - msg = EmailMessage() - msg['Subject'] = 'fail after cancel' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: CANCELLOCK001'), - maintype='application', - subtype='pdf', - filename='lock.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='lock.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-FAIL-CANCELLED', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.flush() - doc = ShippingOrderDocument( - intake_id=intake.id, - attachment_key='att-001', - document_type='attachment', - filename='lock.pdf', - classification='supporting', - parse_status='parsed', - ) - db.session.add(doc) - db.session.commit() - - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - - def _boom_then_cancel(**kwargs): - # 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled - row = db.session.get(ShippingOrderIntake, intake.id) - row.parse_status = 'cancelled' - db.session.commit() - raise RuntimeError('boom-after-cancel') - - monkeypatch.setattr( - 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', - _boom_then_cancel, - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'skipped' - db.session.expire_all() - final = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one() - assert final.parse_status == 'cancelled' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=final.id).count() == 1 - -def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch): - """阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import serialize_intake - msg = EmailMessage() msg['Subject'] = 'retry clear' msg['From'] = 'a@b.com' @@ -1503,28 +1360,21 @@ def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monk 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', lambda _a: eml_bytes, ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - first = run_intake_parse(intake, parent) - assert first['status'] == 'parsed' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1 - - intake.parse_status = 'parsing' - db.session.commit() + # 上传阶段不调用 persist_documents_and_candidates:即使它抛异常也不影响解析。 monkeypatch.setattr( 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')), ) with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - second = run_intake_parse(intake, parent) - assert second['status'] == 'parse_failed' + result = run_intake_parse(intake, parent) + assert result['status'] == 'parsed' db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() - assert failed.parse_status == 'parse_failed' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=failed.id).count() == 0 - assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=failed.id).count() == 0 - payload = serialize_intake(failed, asset=parent) - assert payload['document_count'] == 0 - assert payload['candidate_count'] == 0 + parsed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() + assert parsed.parse_status == 'parsed' + assert parsed.order_extraction_status == 'not_started' + # 普通发货通知上传不建 Document/Candidate;落库在发送/物化阶段。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0 + assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0 def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user): """补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。""" diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 56c5a88a..f4d64b3a 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -16,7 +16,7 @@ from app.models import ( ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, - ShippingOrderCustomerMatch, + ShippingOrderTask, ) from app.services.shipping_notice.order_schema import service as order_schema_service from tests.conftest import ( @@ -45,7 +45,7 @@ def _tool_headers(): return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"} -def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None: +def _attach_dynamic_order(task: ShippingOrderTask | ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None: """为库存/RPA 测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。""" version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() if version is None: @@ -74,12 +74,18 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation str(item['field_code']): str(item['field_id']) for item in (version.definition_json or {}).get('fields') or [] } + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id) + if owner is None: + owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review') + db.session.add(owner) + db.session.flush() + task.order_task_id = owner.id extraction = ShippingOrderExtraction( - task_id=task.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted', + task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items(): @@ -94,11 +100,11 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=value, )) - task.current_order_extraction_id = extraction.id + owner.current_order_extraction_id = extraction.id db.session.flush() -def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: +def _confirm_direct_rpa_task_customer(task: ShippingOrderTask | ShippingNotice) -> None: """为直接构造的 RPA 回调任务补齐已确认客户。 核心逻辑:测试不经建单工作流时,显式绑定激活客户, @@ -111,15 +117,31 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: ) db.session.add(customer) db.session.flush() - task.customer = customer - task.customer_name_snapshot = customer.standard_name - task.customer_short_code_snapshot = customer.short_code - task.customer_resolution_status = 'confirmed' - task.customer_resolution_method = 'test_fixture' - db.session.add(task) - db.session.flush() + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id) + if owner is None: + owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review') + db.session.add(owner) + db.session.flush() + task.order_task_id = owner.id + from tests.conftest import confirm_test_customer_resolution + extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id) + if extraction is None: + rows = getattr(task, 'lines_json', None) + if not isinstance(rows, list) or len(rows) != 1 or not isinstance(rows[0], dict): + raise ValueError('RPA test task must have an accepted extraction before customer confirmation') + row = rows[0] + _attach_dynamic_order( + task, + part_number=str(row.get('part_number') or ''), + reservation_id=str(row.get('reservation_id') or ''), + quantity=int(row.get('qty') or 0), + ) + extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id) + confirm_test_customer_resolution(owner, customer=customer, extraction=extraction) # 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。 - task._test_customer_confirmed = True + owner._test_customer_confirmed = True + if not isinstance(task, ShippingOrderTask): + task._test_customer_confirmed = True @pytest.fixture(autouse=True) @@ -169,7 +191,7 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch): trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}} monkeypatch.setattr( 'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa', - lambda _task, *, mode: trigger, + lambda _task, *, mode, allow_auto_retry=True: trigger, ) result = inventory_workflow.ensure_inventory({ @@ -203,7 +225,7 @@ def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypat monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'}) monkeypatch.setattr( 'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared', - lambda actual_task, *, mode: calls.append((actual_task, mode)) or prepared, + lambda actual_task, *, mode, allow_auto_retry=True: calls.append((actual_task, mode)) or prepared, ) monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None) monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None) @@ -284,18 +306,92 @@ def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatc assert synced == [task, linked_task] +def test_inventory_loaded_response_reuse_skips_file_line_overwrite(monkeypatch): + """[断言] persist_lines=False 时只推进状态,禁止调用写回 File.inventory_lines_json。""" + from app.services.shipping_notice import inventory_mapping_workflow as workflow + + owner_task = SimpleNamespace(id=1, task_no='OT-REUSE-NO-WRITE') + linked_task = SimpleNamespace(id=2, task_no='OT-REUSE-LINKED') + inventory_file = SimpleNamespace( + inventory_file_no='INV-SHARED', + inventory_lines_json=[{'part_number': 'KEEP', 'qty': 9}], + links=[ + SimpleNamespace(is_active=True, task=owner_task), + SimpleNamespace(is_active=True, task=linked_task), + ], + ) + apply_calls: list[object] = [] + + monkeypatch.setattr(workflow, 'active_inventory_file_for_task', lambda _task: inventory_file) + monkeypatch.setattr( + workflow, + 'apply_inventory_parse_result_to_linked_tasks', + lambda *args, **kwargs: apply_calls.append((args, kwargs)) or [owner_task], + ) + monkeypatch.setattr(workflow, '_can_relink_inventory', lambda _task: True) + monkeypatch.setattr(workflow, 'task_line_purpose_values', lambda _task: []) + monkeypatch.setattr(workflow, 'build_field_alignment_preview', lambda *_a, **_k: {}) + monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(workflow.db.session, 'flush', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice', + lambda _notice: None, + ) + + response = workflow.inventory_loaded_response( + owner_task, + [{'part_number': 'MERGED', 'qty': 1, '__source_code': 'SRC_A'}], + source='snapshot_reuse', + event_type='inventory_snapshot_reused', + commit=False, + persist_lines=False, + ) + + assert apply_calls == [] + assert inventory_file.inventory_lines_json == [{'part_number': 'KEEP', 'qty': 9}] + assert response['status'] == 'ok' + assert response['data']['persist_lines'] is False + + +def test_resolve_inventory_lines_prefers_candidate_prep_when_frozen(monkeypatch): + """[断言] 冻结候选 OT 匹配输入取 prepare 合并行,不依赖 active File 上的单源缓存。""" + from app.services.shipping_notice import inventory_file_store as store + + task = SimpleNamespace(id=88, task_no='OT-RESOLVE-CAND') + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A', 'SRC_B'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'lines': [ + {'part_number': 'P1', '__source_code': 'SRC_A'}, + {'part_number': 'P2', '__source_code': 'SRC_B'}, + ], + }, + ) + monkeypatch.setattr( + store, + 'active_inventory_file_for_task', + lambda _task: (_ for _ in ()).throw(AssertionError('must not fall back to active file')), + ) + + rows = store.resolve_inventory_lines_for_execution(task) + assert [row['__source_code'] for row in rows] == ['SRC_A', 'SRC_B'] + + def test_inventory_loaded_response_clears_stale_match_state(monkeypatch): """库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。""" from app.services.shipping_notice import inventory_mapping_workflow as workflow - task = SimpleNamespace( - id=1, task_no="SN-INV-CLEAR", inventory_lines_json=None, - match_status="unfulfillable", line_results_json=[{"a": 1}], shortage_json={"lines": []}, - ) - linked_task = SimpleNamespace( - id=2, task_no="SN-INV-CLEAR-LINKED", inventory_lines_json=None, - match_status="unfulfillable", line_results_json=None, shortage_json=None, - ) + task = SimpleNamespace(id=1, task_no="SN-INV-CLEAR") + linked_task = SimpleNamespace(id=2, task_no="SN-INV-CLEAR-LINKED") inventory_file = SimpleNamespace(inventory_file_no="INV-CLEAR") monkeypatch.setattr(workflow, "active_inventory_file_for_task", lambda _task: inventory_file) @@ -317,7 +413,7 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch): lambda notice: None, ) - workflow.inventory_loaded_response( + response = workflow.inventory_loaded_response( task, [{"part_number": "A001", "qty": 1}], source="rpa", @@ -325,13 +421,11 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch): commit=False, ) - # 库存内容变更后,task 与其同库存文件的关联任务都不能再读旧匹配结果。 - assert task.match_status is None - assert task.line_results_json is None - assert task.shortage_json is None - assert linked_task.match_status is None - assert linked_task.line_results_json is None - assert linked_task.shortage_json is None + # 新模型不再向 OT 写入库存匹配旧投影;库存事实由 File/Link/Match/Gate 承载。 + assert response['status'] == 'ok' + assert not hasattr(task, 'match_status') + assert not hasattr(task, 'shortage_json') + assert not hasattr(linked_task, 'line_results_json') def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path): @@ -363,9 +457,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit 'report_group': 'Inventory', 'report_name': 'On Hand', }, ) - task = ShippingNotice( - task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual', - lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}], + task = ShippingOrderTask( + task_no='OT-SNAPSHOT-SOURCE-UNIQUE', user_id=1, source_type='direct_pdf', status='ready', ) source_snapshot = ShippingInventoryFile( inventory_file_no='SIF-SOURCE-UNIQUE', storage_path=str(source_file), snapshot_status='ready', @@ -422,28 +515,32 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') with app.app_context(): - task = ShippingNotice( - task_no='SN-MANUAL-PROFILE-001', source_type='manual', - lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}], + task = ShippingOrderTask( + task_no='OT-MANUAL-PROFILE-001', user_id=1, source_type='direct_pdf', status='ready', ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code='DSV360_AWSDU') db.session.add(task) db.session.commit() + assert task.order_snapshot_id is not None upload = FileStorage( stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()), filename='manual-stock.xlsx', ) - result = upload_inventory_file(task.task_no, upload) + result = upload_inventory_file( + task.task_no, + upload, + ) db.session.refresh(task) - assert result['status'] == 'ok' - assert result['checkpoint'] == 'ready_to_match' - assert task.inventory_snapshot_id is not None - assert task.review_status is None - assert task.pending_human_reason is None - snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id) + assert result['status'] == 'ok', result + assert result['data']['stage'] == 'step5_match_inventory' + link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one() + snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id) assert snapshot is not None assert snapshot.mapping_source == 'parsing_profile' assert snapshot.mapping_confirmed is True @@ -473,10 +570,12 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path): stream.seek(0) with app.app_context(): - task = ShippingNotice( - task_no='SN-MANUAL-DRIFT-001', source_type='manual', - lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}], + task = ShippingOrderTask( + task_no='OT-MANUAL-DRIFT-001', user_id=1, source_type='direct_pdf', status='ready', ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code='DSV360_AWSDU') db.session.add(task) @@ -490,8 +589,6 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path): assert result['status'] == 'failed' assert '结构' in result['message'] or '解析' in result['message'] - assert task.inventory_snapshot_id is None - assert task.inventory_lines_json in (None, []) assert ShippingInventoryFile.query.count() == 0 assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0 assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*')) @@ -680,12 +777,12 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): - task = ShippingNotice( - task_no="SN-BATCH-RUNNO", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-BATCH-RUNNO", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") from tests.conftest import seed_rpa_inventory_trigger @@ -702,15 +799,15 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): "status": "success", "success": True, "file_path": str(sample), - "source_code": task.inventory_source_code, - "warehouse_id": task.inventory_warehouse_id, + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", }], })) db.session.refresh(task) assert receipt["status"] == "ok" assert receipt["result_status"] == "accepted" - assert task.inventory_snapshot_id is None + assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0 job = db.session.get(Job, int(receipt["data"]["job_id"])) assert job is not None assert job.status == "queued" @@ -729,8 +826,8 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): "status": "success", "success": True, "file_path": str(sample), - "source_code": task.inventory_source_code, - "warehouse_id": task.inventory_warehouse_id, + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", }], })) assert replay["result_status"] == "accepted" @@ -739,7 +836,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): result = _process_batch_callback(job.payload_json) db.session.refresh(task) assert result["result_status"] == "success" - assert task.inventory_snapshot_id is not None + assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 1 def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): @@ -760,12 +857,12 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) with app.app_context(): - task = ShippingNotice( - task_no="SN-BATCH-FAIL-TASK", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-BATCH-FAIL-TASK", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") from tests.conftest import seed_rpa_inventory_trigger @@ -801,7 +898,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): status="running", lease_token="batch-fail-lease", extra_json={ - "candidate_set_id": 0, + "candidate_set_id": task.active_inventory_candidate_set_id, "execution_id": execution.id, "gate_id": gate.id, }, @@ -826,7 +923,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): "callback_id": "callback-batch-fail-dsv-a1", "attempt_no": 1, "lease_token": "batch-fail-lease", - "candidate_set_id": 0, + "candidate_set_id": task.active_inventory_candidate_set_id, "execution_id": execution.id, "gate_id": gate.id, "status": "failed", @@ -838,13 +935,11 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): assert result["status"] == "ok" assert result["failed_count"] == 1 - assert task.pending_human_reason == "inv_unavail" - assert task.error_message db.session.refresh(rpa_attempt) db.session.refresh(preparation) db.session.refresh(execution) db.session.refresh(gate) - assert rpa_attempt.status == "failed" + assert rpa_attempt.status == "consumed" assert preparation.status == "failed" assert gate.status == "blocked_retryable" assert gate.blocking_reason_code == "inventory_rpa_timeout" @@ -904,15 +999,14 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None, report_path_json={}, query_parameters_json=[], enabled=True, ) - task = ShippingNotice( - task_no="SN-CRANE-EMPTY-WAREHOUSE", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-CRANE-EMPTY-WAREHOUSE", user_id=1, source_type="direct_pdf", status="ready", ) - task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}] + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) - db.session.add_all([crane_profile, crane_source, task]) + db.session.add_all([crane_profile, crane_source]) db.session.flush() seed_task_inventory_source(task, source_code="CRANE") order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) @@ -946,8 +1040,8 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot assert result["success_count"] == 1, result assert result["failed_count"] == 0 - assert task.inventory_snapshot_id is not None - assert task.inventory_warehouse_id == "CRANE-WH" + link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one() + assert link.matched_warehouse_id == "CRANE-WH" def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolvable(app, tmp_path): @@ -982,15 +1076,14 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None, report_path_json={}, query_parameters_json=[], enabled=True, ) - task = ShippingNotice( - task_no="SN-CRANE-UNRESOLVED-LINK", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-CRANE-UNRESOLVED-LINK", user_id=1, source_type="direct_pdf", status="ready", ) - task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}] + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) - db.session.add_all([crane_profile, crane_source, task]) + db.session.add_all([crane_profile, crane_source]) db.session.flush() seed_task_inventory_source(task, source_code="CRANE") order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) @@ -1031,7 +1124,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva assert result["success_count"] == 1, result assert result["failed_count"] == 0 - assert task.inventory_snapshot_id is not None snapshot = ShippingInventoryFile.query.filter_by( rpa_run_no="RUN-CRANE-UNRESOLVED-LINK", source_code="CRANE", ).one() @@ -1043,7 +1135,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva task_id=task.id, inventory_file_id=snapshot.id, is_active=True, ).one() assert link.identity_check_status == "pending_matching" - assert task.pending_human_reason is None sync_fulfillment_gates_from_task(execution=execution) db.session.refresh(execution) @@ -1095,20 +1186,88 @@ def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatc assert job.result_json["callback_result"]["data"]["result_status"] == "failed" +def test_inventory_callback_job_marks_top_level_failure_as_failed(app, monkeypatch): + """事务级失败没有 result_status 时,回调 Job 也必须失败。""" + from app import db + from app.jobs.context import JobContext + from app.jobs.handlers import shipping_inventory_callback_process as handler + from app.models import Job + + with app.app_context(): + job = Job( + domain="shipping_notice", + job_type="shipping_inventory_callback_process", + status="running", + attempts=1, + max_attempts=3, + payload_json={"callback_id": "callback-transaction-failed"}, + ) + db.session.add(job) + db.session.commit() + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.process_rpa_report_inventory_batch", + lambda _payload: { + "status": "failed", + "message": "batch callback transaction failed", + "data": {"run_no": "RUN-TRANSACTION-FAILED"}, + }, + ) + settled = [] + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.settle_failed_inventory_callback", + lambda payload, *, error: settled.append((payload, error)), + ) + + handler.run_shipping_inventory_callback_process( + JobContext(config={}, logger=None, extras={}), {"job_id": job.id}, + ) + db.session.refresh(job) + + assert job.status == "failed" + assert job.error_message == "batch callback transaction failed" + assert settled == [(job.payload_json, "batch callback transaction failed")] + + +def test_rpa_callback_locks_order_task_model(app): + """订单生命周期的库存回调必须锁定 ShippingOrderTask,不得查询旧 Notice。""" + from app import db + from app.models import ShippingOrderTask, User + from app.services.shipping_notice.inventory_rpa_workflow import _lock_task_for_rpa_callback + + with app.app_context(): + user = User(username="callback-lock-user", email="callback-lock@example.com") + db.session.add(user) + db.session.flush() + task = ShippingOrderTask( + task_no="OT-CALLBACK-LOCK", + user_id=int(user.id), + status="processing", + ) + db.session.add(task) + db.session.commit() + + locked = _lock_task_for_rpa_callback(task) + + assert isinstance(locked, ShippingOrderTask) + assert locked.id == task.id + + def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): """单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。""" from app import db from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory with app.app_context(): - task = ShippingNotice( - task_no="SN-FAIL-NO-IDENT", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-FAIL-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") + freeze_test_task_order_snapshot(task) + assert task.order_snapshot_id is not None seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT") db.session.add(task) db.session.commit() @@ -1123,8 +1282,6 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): db.session.refresh(task) assert result["status"] == "needs_human" - assert result["checkpoint"] == "upload_req" - assert task.pending_human_reason == "inv_unavail" failed_events = ShippingTaskEvent.query.filter_by( task_id=task.id, event_type="inventory_rpa_failed", @@ -1319,12 +1476,13 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path): handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): - task = ShippingNotice( - task_no="SN-BATCH-NO-IDENT", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-BATCH-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT") db.session.add(task) @@ -1344,7 +1502,6 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path): assert result["status"] == "ok" assert result["failed_count"] == 1 - assert task.pending_human_reason == "rpa_pending" def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch): @@ -1386,12 +1543,13 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey assert storage_path.is_file() snap_id = snap.id - task = ShippingNotice( - task_no="SN-REUSE-INGEST-FAIL", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-REUSE-INGEST-FAIL", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no=run_no) db.session.add(task) @@ -1415,7 +1573,6 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey assert snap_after.snapshot_status == "ready" assert Path(snap_after.storage_path).is_file() assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1 - assert task.pending_human_reason == "rpa_pending" def test_reused_snapshot_rejects_content_mismatch(app, tmp_path): @@ -1501,27 +1658,23 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, ) with app.app_context(): - task_a = ShippingNotice( - task_no="SN-BATCH-OK", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task_a = ShippingOrderTask( + task_no="OT-BATCH-OK", user_id=1, source_type="direct_pdf", status="ready", ) - task_b = ShippingNotice( - task_no="SN-BATCH-FAIL", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}], + task_b = ShippingOrderTask( + task_no="OT-BATCH-FAIL", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add_all([task_a, task_b]) + db.session.flush() + _attach_dynamic_order(task_a, part_number='A001', reservation_id='00001', quantity=1) + _attach_dynamic_order(task_b, part_number='B001', reservation_id='00002', quantity=1) _confirm_direct_rpa_task_customer(task_a) _confirm_direct_rpa_task_customer(task_b) seed_task_inventory_source(task_a, source_code="DSV360_AWSDU") seed_task_inventory_source(task_b, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task_a, run_no=run_no) seed_rpa_inventory_trigger(task_b, run_no=run_no) - db.session.add_all([task_a, task_b]) db.session.commit() - before_b_status = task_b.pending_human_reason result = _process_batch_callback({ "run_no": run_no, @@ -1546,9 +1699,8 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, assert result["success_count"] == 1 assert result["failed_count"] == 1 - assert task_a.inventory_rpa_consumed_run_no == run_no - assert task_b.inventory_rpa_consumed_run_no is None - assert task_b.pending_human_reason == before_b_status + assert ShippingTaskInventoryLink.query.filter_by(task_id=task_a.id, is_active=True).count() == 1 + assert ShippingTaskInventoryLink.query.filter_by(task_id=task_b.id, is_active=True).count() == 0 def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, monkeypatch): @@ -1582,12 +1734,13 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, ) with app.app_context(): - task = ShippingNotice( - task_no="SN-BATCH-DEFER-CONFIRM", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-BATCH-DEFER-CONFIRM", user_id=1, source_type="direct_pdf", status="ready", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-DEFER-CONFIRM") @@ -1624,25 +1777,22 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m run_no = "RUN-SHARED-LINK" with app.app_context(): - task_ok = ShippingNotice( - task_no="SN-SHARED-OK", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task_ok = ShippingOrderTask( + task_no="OT-SHARED-OK", user_id=1, source_type="direct_pdf", status="ready", ) - task_fail = ShippingNotice( - task_no="SN-SHARED-FAIL", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}], + task_fail = ShippingOrderTask( + task_no="OT-SHARED-FAIL", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add_all([task_ok, task_fail]) + db.session.flush() + _attach_dynamic_order(task_ok, part_number='A001', reservation_id='00001', quantity=1) + _attach_dynamic_order(task_fail, part_number='B001', reservation_id='00002', quantity=1) _confirm_direct_rpa_task_customer(task_ok) _confirm_direct_rpa_task_customer(task_fail) seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU") seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task_ok, run_no=run_no) seed_rpa_inventory_trigger(task_fail, run_no=run_no) - db.session.add_all([task_ok, task_fail]) db.session.commit() ok_result = _process_batch_callback({ @@ -1711,12 +1861,12 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p ) with app.app_context(): - task = ShippingNotice( - task_no="SN-POST-COMMIT-FAIL", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-POST-COMMIT-FAIL", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT") @@ -1729,7 +1879,6 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p assert snap is not None assert Path(snap.storage_path).is_file() assert result.get("data", {}).get("post_commit_warnings") - assert task.inventory_rpa_consumed_run_no == "RUN-POST-COMMIT" def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkeypatch): @@ -1755,12 +1904,12 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey ) with app.app_context(): - task = ShippingNotice( - task_no="SN-PROMOTE-FAIL-REBUILD", - source_type="manual", - pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-PROMOTE-FAIL-REBUILD", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL") @@ -1774,7 +1923,6 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey warnings = result.get("data", {}).get("post_commit_warnings") or [] assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings) assert attachment is not None and attachment.is_file() - assert task.inventory_rpa_consumed_run_no == "RUN-PROMOTE-FAIL" def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path): @@ -1792,11 +1940,13 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path): snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): - task = ShippingNotice( - task_no="SN-REPAIR-ATTACH", - source_type="manual", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-REPAIR-ATTACH", user_id=1, source_type="direct_pdf", status="ready", ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) db.session.flush() @@ -1949,14 +2099,14 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path): other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): - task = ShippingNotice( - task_no="SN-REPAIR-REJECT", - source_type="manual", - lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + task = ShippingOrderTask( + task_no="OT-REPAIR-REJECT", user_id=1, source_type="direct_pdf", status="ready", ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") active_snap = ShippingInventoryFile( inventory_file_no="SIF-ACTIVE-SNAP", storage_path=str(active_file), @@ -2028,3 +2178,341 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat assert list(processed_dir.glob("stuck.xlsx")) assert not stuck.is_file() assert warnings == [] + + +def test_ensure_all_required_sources_writes_single_batch_trigger(monkeypatch, app): + """[断言] 多候选源缺失快照时:一轮 ensure 只写 1 个批次 trigger(单文件多源), + 逐源身份键(task_no/source_run_no/lease_token/callback_id)进入条目, + 且全部 Attempt 共享该 trigger_file_path;批次载荷为 on_demand。""" + from app import db + from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt + from app.services.shipping_notice import per_source_rpa_service + + task = ShippingNotice(task_no='SN-PREP-BATCH-SINGLE') + db.session.add(task) + db.session.flush() + + captured = {} + + def _fake_batch_writer(run_no, sources, payload=None): + captured['run_no'] = run_no + captured['sources'] = [dict(item) for item in sources] + captured['payload'] = dict(payload or {}) + return 'trigger/batch.json' + + monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A', 'SRC_B']) + monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) + monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda task: {'source_code': 'SRC_A'}, + ) + monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', _fake_batch_writer) + + result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto') + + assert result.pending_source_codes == ['SRC_A', 'SRC_B'] + assert result.failed_source_codes == [] + assert captured['run_no'].startswith('BATCH-SN-PREP-BATCH-SINGLE-') + assert [item['source_code'] for item in captured['sources']] == ['SRC_A', 'SRC_B'] + for item in captured['sources']: + assert item['task_no'] == task.task_no + assert item['source_run_no'] + assert item['lease_token'] + assert item['callback_id'].endswith(':C1') + assert captured['payload']['trigger_type'] == 'on_demand' + attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task.task_no).all() + assert len(attempts) == 2 + assert all(att.trigger_file_path == 'trigger/batch.json' for att in attempts) + assert all(att.status == 'queued' for att in attempts) + + +def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app): + """[断言] 多候选缺文件:auto 模式自动触发批次探测并返回 running(D3), + 而非旧的 needs_human + inv_unavail;无候选集的 blocked 场景维持 needs_human。""" + from types import SimpleNamespace + from app.services.shipping_notice import inventory_workflow + from app.services.shipping_notice.state_machine import TaskTransition + + task = SimpleNamespace( + task_no='SN-STP-AUTO-PROBE', + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=5, + error_message='stale', + ) + transitions = [] + probe_calls = [] + + def _fake_transition(actual_task, transition): + transitions.append(transition) + + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'apply_task_transition', _fake_transition) + monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A', 'SRC_B'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'missing_files', + 'lines': [], + 'missing_source_codes': ['SRC_A', 'SRC_B'], + 'loaded_source_codes': [], + 'evidence': [], + 'required_source_codes': ['SRC_A', 'SRC_B'], + }, + ) + + def _fake_probe(actual_task, *, mode, allow_auto_retry=True, source_codes=None): + probe_calls.append((actual_task, mode)) + return SimpleNamespace( + pending_source_codes=['SRC_A', 'SRC_B'], + prepared_source_codes=[], + failed_source_codes=[], + source_attempts={}, + all_prepared=False, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared', + _fake_probe, + ) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert probe_calls == [(task, 'auto')] + assert result['status'] == 'running' + assert result['data']['rpa']['pending_source_codes'] == ['SRC_A', 'SRC_B'] + assert transitions == [TaskTransition.RPA_PENDING] + assert task.error_message is None + + +def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypatch, app): + """[断言] 探测无 pending(全部触发失败)→ needs_human,不得伪装 running。""" + from types import SimpleNamespace + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='SN-STP-PROBE-FAILED', + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=5, + ) + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'missing_files', + 'lines': [], + 'missing_source_codes': ['SRC_A'], + 'loaded_source_codes': [], + 'evidence': [], + 'required_source_codes': ['SRC_A'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared', + lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: SimpleNamespace( + pending_source_codes=[], + prepared_source_codes=[], + failed_source_codes=['SRC_A'], + source_attempts={}, + all_prepared=False, + ), + ) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert result['status'] == 'needs_human' + assert result['data']['blocking_reason']['code'] == 'inventory_preparation_failed' + + +def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, app): + """[断言] 冻结源 ready 复用必须先 link;禁止未绑定直接 inventory_loaded_response 抛 ValueError。""" + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='OT-STP-READY-LINK', + id=701, + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=9, + ) + snapshot = SimpleNamespace( + inventory_file_no='INV-READY-001', + source_code='SRC_A', + warehouse_id='WH1', + ) + call_order: list[str] = [] + + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'candidate_set_id': 9, + 'lines': [{'part_number': 'P1', '__source_code': 'SRC_A', '__inventory_file_no': 'INV-READY-001'}], + 'missing_source_codes': [], + 'loaded_source_codes': ['SRC_A'], + 'evidence': [{ + 'source_code': 'SRC_A', + 'status': 'loaded', + 'inventory_file_no': 'INV-READY-001', + 'line_count': 1, + 'required': True, + }], + 'required_source_codes': ['SRC_A'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: None, + ) + monkeypatch.setattr( + ShippingInventoryFile, + 'query', + SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), + ) + + def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None): + call_order.append(f'link:{reason}') + assert actual_task is task + assert inv_file is snapshot + assert reason == 'stp_candidate_prep' + return SimpleNamespace(id=1) + + def _fake_loaded(actual_task, lines, **kwargs): + call_order.append('loaded') + assert actual_task is task + assert lines + assert kwargs.get('persist_lines') is False + return {'status': 'ok', 'message': 'linked-and-loaded'} + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + _fake_link, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response', + _fake_loaded, + ) + monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert result['status'] == 'ok' + assert call_order == ['link:stp_candidate_prep', 'loaded'] + + +def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app): + """[断言] ready 快照无法绑定 OT 时返回 needs_human,不得抛未绑定 ValueError。""" + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='OT-STP-LINK-FAIL', + id=702, + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=10, + ) + snapshot = SimpleNamespace(inventory_file_no='INV-MISMATCH', source_code='SRC_A', warehouse_id='WH1') + + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow, 'apply_task_transition', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'candidate_set_id': 10, + 'lines': [{'part_number': 'P1', '__inventory_file_no': 'INV-MISMATCH'}], + 'missing_source_codes': [], + 'loaded_source_codes': ['SRC_A'], + 'evidence': [{ + 'source_code': 'SRC_A', + 'status': 'loaded', + 'inventory_file_no': 'INV-MISMATCH', + 'required': True, + }], + 'required_source_codes': ['SRC_A'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: None, + ) + monkeypatch.setattr( + ShippingInventoryFile, + 'query', + SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + lambda *_a, **_k: None, + ) + + def _boom(*_a, **_k): + raise AssertionError('inventory_loaded_response must not run when link failed') + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response', + _boom, + ) + monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _boom) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert result['status'] == 'needs_human' + assert result['data']['blocking_reason']['code'] == 'inventory_file_missing' diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index bbaa098f..0acaaa9e 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -31,14 +31,19 @@ from tests.conftest import v2_inventory_batch_payload @pytest.fixture(autouse=True) def _freeze_schedule_batch_callback_contract(monkeypatch): - """旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。""" + """旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。 + + 排程终态化逻辑已从 HTTP 快速收件(rpa_report_inventory_batch,只入队异步 job) + 解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持 + 同步断言,因此把旧入口重新指向同步处理函数。 + """ from app.services.shipping_notice import inventory_rpa_workflow import sys - original = inventory_rpa_workflow.rpa_report_inventory_batch - def _wrapped(payload): - return original(v2_inventory_batch_payload(payload)) + return inventory_rpa_workflow.process_rpa_report_inventory_batch( + v2_inventory_batch_payload(payload) + ) monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped) monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped) @@ -846,6 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "missing_warehouse.xlsx" _write_sample_inventory(sample, "AWSDU") diff --git a/backend/tests/test_shipping_notice_match_summary.py b/backend/tests/test_shipping_notice_match_summary.py index 91307df0..089cf2de 100644 --- a/backend/tests/test_shipping_notice_match_summary.py +++ b/backend/tests/test_shipping_notice_match_summary.py @@ -7,7 +7,7 @@ def test_format_match_summary_fulfillable(): [ { "part_number": "D4-A08AR12000002", - "reservation_id": "AWS-311", + "reservation_id": "1000140351", "required_qty": 2, "available_qty": 5, "shortage_qty": 0, @@ -17,7 +17,7 @@ def test_format_match_summary_fulfillable(): ) assert "【库存匹配结果】" in msg or "匹配明细" in msg assert "| # | 预订单号 | 内部料号 |" in msg - assert "| 1 | AWS-311 | D4-A08AR12000002 | 2 | 5 | - |" in msg + assert "| 1 | 1000140351 | D4-A08AR12000002 | 2 | 5 | - |" in msg assert "✅ 充足" in msg assert "可生成发货 Excel" in msg diff --git a/backend/tests/test_shipping_notice_openapi_contract.py b/backend/tests/test_shipping_notice_openapi_contract.py index 019d101a..5775a4bf 100644 --- a/backend/tests/test_shipping_notice_openapi_contract.py +++ b/backend/tests/test_shipping_notice_openapi_contract.py @@ -18,7 +18,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: 校验订单抽取 Tool 已下线且库存连接器字段边界保持稳定。 核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations; - 任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。 + 任务状态不再暴露库存连接器实现细节,并拒绝旧 connector 字段名。 Args: spec: 动态接口或静态快照读取出的 OpenAPI 对象。 @@ -31,7 +31,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: assert '/tools/submit_order_extraction' not in paths status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"] - assert "inventory_connector_type" in status_description + assert "inventory_connector_type" not in status_description assert "inventory_source_type" not in status_description assert set(paths) == {"/tools/get_task_status"} diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 04e0749d..116fb61e 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -121,90 +121,7 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it() assert assessment['missing_process_fields'] == ['reservation_id'] -def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app): - """派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。""" - with app.app_context(): - order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None) - customer_line = order_schema_service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = order_schema_service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - part = order_schema_service.save_field( - {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - qty = order_schema_service.save_field( - {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, - ) - draft = order_schema_service.create_draft({}, actor_id=None) - def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict: - return { - 'field_id': field['id'], 'display_name': field['field_code'], 'required': required, - 'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general', - 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], - 'evidence_policy': { - 'required': True, 'source_precedence': ['attachment_text'], - 'conflict_policy': 'block', 'allow_single_source': True, - }, - 'relation_role': None, 'comparator_key': comparator, - } - - saved = order_schema_service.save_draft(draft['id'], { - 'fields': [ - config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'), - config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'), - config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'), - config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'), - ], - 'derivation_rules': [{ - 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True, - 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = order_schema_service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - _user, _session, intake, document, _runtime_context = _seed_extraction_input() - document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10' - db.session.commit() - - result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'source_intake_no': intake.intake_no, 'primary_document_id': document.id, - 'classification': 'shipping_request', 'classification_confidence': 0.99, - 'header_fields': [], - 'lines': [{'fields': [ - {'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99, - }]}, - {'field_id': part['id'], 'observations': [{ - 'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99, - }]}, - {'field_id': qty['id'], 'observations': [{ - 'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99, - }]}, - ]}], - 'conflicts': [{ - 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', - 'owning_gate_code': 'field_completeness', - }], - }]}) - - candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() - decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions'] - assert any( - item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived' - for item in decisions - ) - assert not any( - item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing' - for item in candidate.conflicts_json - ) - assert 'blocking_conflict' not in result['pending_orders'][0]['reasons'] def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field(): @@ -768,9 +685,18 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None: field['observations'][0]['quote'] = 'NOT-IN-SOURCE' -def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: - """为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。""" - fields = _ensure_order_schema() +def _attach_existing_task_dynamic_order( + task: ShippingOrderTask, + *, + po_number: str = '', + lines: list[dict] | None = None, +) -> None: + """为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。 + + ShippingOrderTask 不再保存 po_number/lines_json 投影;订单真相由当前已接受 + Extraction 的 FieldValue 承载,因此明确传入门头与行值。 + """ + _ensure_order_schema() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() extraction = ShippingOrderExtraction( task_id=task.id, @@ -781,7 +707,7 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: db.session.add(extraction) db.session.flush() configs = list((version.definition_json or {}).get('fields') or []) - header_values = {'po_number': task.po_number} + header_values = {'po_number': po_number} for config in configs: if config.get('scope') != 'header': continue @@ -799,8 +725,10 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']), decision_id=decision.id, value_text=str(value), value_json=value, )) - for position, row in enumerate(task.lines_json or []): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + for position, row in enumerate(lines or []): + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for config in configs: @@ -837,13 +765,18 @@ def test_order_field_display_uses_current_catalog_sequence(app): ShippingOrderField.field_code.in_(sequence_by_code), ).all(): field.display_sequence = sequence_by_code.get(str(field.field_code), 99) - task = ShippingNotice( - task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual', - po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}], + owner = User(username='order-display-user', email='order-display@example.com', password_hash='x') + db.session.add(owner) + db.session.flush() + task = ShippingOrderTask( + task_no='OT-ORDER-DISPLAY-SEQUENCE', source_type='eml', + user_id=int(owner.id), ) db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='PO-001', lines=[{'part_number': 'SKU-1', 'qty': 2}], + ) db.session.commit() display = current_order_field_display(task) @@ -1112,11 +1045,10 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin """订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-EXISTING-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-EXISTING-001', user_id=int(user.id), - source_type='manual', - inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}], + source_type='eml', ) db.session.add(existing) db.session.flush() @@ -1134,7 +1066,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin 'content_fingerprint_version': 'shipping-content-v4', 'matches': [{ 'task_no': existing.task_no, - 'match_status': existing.match_status, + 'match_status': 'matched', 'match_type': 'business_fingerprint', }], 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], @@ -1166,9 +1098,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin assert result['opened_existing'][0]['task_no'] == existing.task_no candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() assert candidate.consumed_task_id == existing.id - assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 - - + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1 def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app): """LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。""" with app.app_context(): @@ -1240,33 +1170,42 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part assert document.order_extraction_status == 'partially_completed' -def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app): +def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app, monkeypatch): """同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-BACKFILL-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-BACKFILL-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', error_message='解析失败:未识别到 Reservation ID', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], - step_payload_json={ - 'process_field_gate': { - 'status': 'needs_enrichment', - 'missing_fields': ['reservation_id'], - 'issues': [], - }, - }, ) db.session.add(existing) db.session.flush() - _attach_existing_task_dynamic_order(existing) + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'reservation-backfill-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'reservation-backfill-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = ( f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 " "Reservation ID 1000140351 Source DBS DUB" @@ -1293,7 +1232,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_re assert result['created_count'] == 0 assert not result['pending_orders'], result['pending_orders'] assert result['opened_existing_count'] == 1, result - assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1 candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one() candidate_line = candidate.structured_result_json['business_summary']['lines'][0] assert candidate_line['inventory_source_hint'] == 'DBS DUB' @@ -1406,29 +1345,30 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): @pytest.mark.parametrize( 'task_overrides', [ - {'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, - {'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, - {'match_status': 'matched'}, - {'export_file_path': '/tmp/shipment.xlsx'}, + {'pending_human_reason': 'inv_unavail'}, + {'pending_human_reason': 'shortage'}, + {'pending_human_reason': 'rpa_exhausted'}, + {'pending_human_reason': 'upload_rpa_pending'}, ], ) def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides): """旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。""" with app.app_context(): task_values = { - 'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", - 'po_number': '4510038672', - 'source_type': 'manual', + 'task_no': f"OT-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", + 'user_id': 1, + 'source_type': 'eml', 'review_status': 'rsv_req', 'pending_human_reason': 'rsv_req', - 'lines_json': [{'part_number': 'P123456', 'qty': 24}], } task_values.update(task_overrides) - task = ShippingNotice(**task_values) + task = ShippingOrderTask(**task_values) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG') db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24}], + ) outcome = backfill_exact_file_open_existing_reservations( task=task, @@ -1448,7 +1388,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states ) assert outcome['status'] == 'skipped' - assert 'reservation_id' not in task.lines_json[0] + assert current_line_field_values(task)[0].get('reservation_id') is None assert ShippingTaskEvent.query.filter_by( task_id=int(task.id), event_type='reservation_backfilled_from_exact_file_candidate', @@ -1458,39 +1398,27 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app): """既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。""" with app.app_context(): - tasks = [ - ShippingNotice( - task_no='SN-RSV-BACKFILL-CONFLICT', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}], - ), - ShippingNotice( - task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[ - {'part_number': 'P123456', 'qty': 24}, - {'part_number': 'P123456', 'qty': 24}, - ], - ), - ShippingNotice( - task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24}], - ), + task_lines = [ + ('OT-RSV-BACKFILL-CONFLICT', [{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}]), + ('OT-RSV-BACKFILL-AMBIGUOUS-LINES', [ + {'part_number': 'P123456', 'qty': 24}, + {'part_number': 'P123456', 'qty': 24}, + ]), + ('OT-RSV-BACKFILL-AMBIGUOUS-TARGET', [{'part_number': 'P123456', 'qty': 24}]), ] - db.session.add_all(tasks) - db.session.flush() - for task in tasks: - _attach_existing_task_dynamic_order(task) + tasks = [] + for task_no, lines in task_lines: + task = ShippingOrderTask( + task_no=task_no, + user_id=1, + source_type='eml', + review_status='rsv_req', + pending_human_reason='rsv_req', + ) + db.session.add(task) + db.session.flush() + _attach_existing_task_dynamic_order(task, po_number='4510038672', lines=lines) + tasks.append(task) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS') summary = { 'po_number': '4510038672', @@ -1519,26 +1447,27 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit ] assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped'] - assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD' - assert all('reservation_id' not in line for line in tasks[1].lines_json) - assert 'reservation_id' not in tasks[2].lines_json[0] + assert current_line_field_values(tasks[0])[0]['reservation_id'] == 'R-OLD' + assert current_line_field_values(tasks[1])[0].get('reservation_id') is None + assert current_line_field_values(tasks[2])[0].get('reservation_id') is None def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app): """目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE', - po_number='4510038672', - source_type='manual', + task = ShippingOrderTask( + task_no='OT-RSV-BACKFILL-ALREADY-COMPLETE', + user_id=1, + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], ) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE') db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], + ) outcome = backfill_exact_file_open_existing_reservations( task=task, @@ -1559,25 +1488,42 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap assert outcome['status'] == 'skipped' assert outcome['reason'] == 'target_already_complete' - assert task.lines_json[0]['reservation_id'] == '1000140351' + assert current_line_field_values(task)[0]['reservation_id'] == '1000140351' -def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app): +def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app, monkeypatch): """已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-UNSAFE-OPEN-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-UNSAFE-OPEN-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', - inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}], - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + source_type='eml', ) db.session.add(existing) + db.session.flush() + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'unsafe-open-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'unsafe-open-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351' db.session.commit() context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) @@ -1602,8 +1548,10 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app assert result['opened_existing_count'] == 1 assert result['pending_count'] == 0 assert candidate.consumed_task_id == int(existing.id) - assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}] - assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}] + # 对账被 target_task_not_safe 跳过,当前 Extraction 订单行不得被改写。 + assert current_line_field_values(existing)[0]['part_number'] == 'P123456' + assert current_line_field_values(existing)[0]['qty'] == 24 + assert current_line_field_values(existing)[0].get('reservation_id') is None assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe' @@ -1637,25 +1585,41 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app) assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0 -def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app): +def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app, monkeypatch): """exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-UNVERIFIED-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-UNVERIFIED-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], ) db.session.add(existing) db.session.flush() - _attach_existing_task_dynamic_order(existing) + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'unverified-open-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'unverified-open-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = ( f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351" ) @@ -1686,7 +1650,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app) assert result['opened_existing_count'] == 0 assert result['pending_count'] == 1 assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] - assert 'reservation_id' not in (existing.lines_json[0] or {}) + assert current_line_field_values(existing)[0].get('reservation_id') is None def test_merge_chat_log_payload_requires_exact_turn_ownership(app): diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 4dfd0198..8436d5bd 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -8,7 +8,17 @@ backend/tests/test_shipping_notice_query_service.py import pytest -from app.models import ShippingNotice +from app.models import ( + ShippingNotice, + ShippingOrderTask, + ShippingExportArtifact, + ShippingUploadAttempt, + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderExtraction, +) from app.services.shipping_notice.query_service import ( TaskProjection, @@ -24,19 +34,44 @@ from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT +def test_frozen_order_projection_uses_snapshot_instead_of_current_extraction(monkeypatch): + """冻结后详情必须展示 Snapshot,不能因 Extraction 变化而改变订单内容。""" + from types import SimpleNamespace + from app.services.shipping_notice import query_service + + snapshot = SimpleNamespace( + header_values_json={'header-field': 'PO-FROZEN'}, + schema_version=SimpleNamespace(definition_json={'fields': [ + {'field_id': 'header-field', 'field_code': 'customer_po_number', 'scope': 'header', 'sequence': 1}, + {'field_id': 'line-field', 'field_code': 'part_number', 'scope': 'line', 'sequence': 1}, + ]}), + lines=[SimpleNamespace(id=10, position=0, field_values_json={'line-field': 'PART-FROZEN'})], + ) + task = SimpleNamespace(order_snapshot_id=77) + monkeypatch.setattr(query_service.db.session, 'get', lambda model, identifier: snapshot) + monkeypatch.setattr(query_service, 'current_header_field_values_or_empty', lambda _task: {'customer_po_number': 'PO-MUTABLE'}) + monkeypatch.setattr(query_service, 'current_line_field_values_or_empty', lambda _task: [{'part_number': 'PART-MUTABLE'}]) + + header, lines, display = query_service._order_values_for_projection(task) + + assert header == {'customer_po_number': 'PO-FROZEN'} + assert lines == [{'part_number': 'PART-FROZEN'}] + assert display['line_fields'][0]['field_code'] == 'part_number' + + def test_get_task_by_ref_supports_task_no_and_numeric_id(app): """task_no 与数字主键均应能解析到同一任务。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-TEST-QUERY-001", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-TEST-QUERY-001", user_id=1, + source_type="direct_pdf", ) from app import db db.session.add(task) db.session.commit() - by_no = get_task_by_ref("SN-TEST-QUERY-001") + by_no = get_task_by_ref("OT-TEST-QUERY-001") by_id = get_task_by_ref(str(task.id)) assert by_no is not None assert by_id is not None @@ -50,26 +85,22 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app): with app.app_context(): from app import db - shortage = ShippingNotice( - task_no="SN-FILTER-SHORTAGE", + shortage = ShippingOrderTask( + task_no="OT-FILTER-SHORTAGE", user_id=999999, status='processing', review_status="shortage_review", pending_human_reason="shortage", - source_type="manual", - user_id=999999, ) - ordinary = ShippingNotice( - task_no="SN-FILTER-PARSE", + ordinary = ShippingOrderTask( + task_no="OT-FILTER-PARSE", user_id=2, status='processing', review_status="parse_review", pending_human_reason="low_confidence", - source_type="manual", - user_id=2, ) db.session.add_all([shortage, ordinary]) db.session.commit() rows = list_tasks_for_user(999999) - assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"] + assert [item["task_no"] for item in rows] == ["OT-FILTER-SHORTAGE"] def test_list_tasks_page_for_user_returns_stable_page_and_total(app): @@ -78,7 +109,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app): from app import db db.session.add_all([ - ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual") + ShippingOrderTask(task_no=f"OT-PAGE-{index:02d}", user_id=999999, source_type="direct_pdf") for index in range(1, 6) ]) db.session.commit() @@ -106,8 +137,45 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app): db.session.add_all([ ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"), ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"), - ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"), + ShippingNotice(task_no="SN-PAGE-FILTER-3", source_type="manual"), ]) + uploaded = ShippingNotice.query.filter_by(task_no="SN-PAGE-FILTER-3").one() + template = ShippingExcelTemplate( + template_code='PAGE_FILTER', display_name='Page filter', version=1, status='published', + storage_bucket='test', storage_key='page-filter.xlsx', original_filename='page-filter.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='PAGE_FILTER', display_name='Page filter', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='PAGE_FILTER', display_name='Page filter') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64, + ) + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted', + ) + db.session.add(version) + db.session.flush() + extraction.schema_version_id = version.id + db.session.add(extraction) + db.session.flush() + artifact = ShippingExportArtifact( + task_id=uploaded.id, artifact_no='ART-PAGE-FILTER-3', template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='d' * 64, + file_path='test.xlsx', file_name='test.xlsx', file_checksum='e' * 64, + file_size=1, status='ready', + ) + db.session.add(artifact) + db.session.flush() + db.session.add(ShippingUploadAttempt( + artifact_id=artifact.id, attempt_no=1, mode='manual', status='succeeded', + idempotency_key='IDEMP-PAGE-FILTER-3', + )) db.session.commit() result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10) @@ -125,55 +193,47 @@ def test_task_export_error_message_distinct_for_missing_path(app): empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual") assert task_export_error_message(empty) == "export file not found" - missing = ShippingNotice( - task_no="SN-MISSING-FILE", - source_type="manual", - export_file_path="/tmp/not-a-real-shipping-export.xlsx", - ) - assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。 + # 已持久化任务但没有可用 Artifact 时,统一视为磁盘产物缺失。 + missing = ShippingNotice(task_no="SN-MISSING-FILE", source_type="manual") + missing.id = 999999 + assert task_export_error_message(missing) == "export file missing on disk" def test_task_projection_tool_strips_internal_fields(app): """TOOL 投影应剔除 Agent 不应复述的内部状态字段。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-PROJ-TOOL", - review_status="align_review", - match_status="pending", - pending_human_reason="rpa_pending", - error_message="boom", - source_type="manual", - customer_name="ACME", - lines_json=[{"sku": "A001"}], + task = ShippingOrderTask( + task_no="OT-PROJ-TOOL", user_id=1, review_status="align_review", + pending_human_reason="rpa_pending", error_message="boom", + source_type="direct_pdf", ) data = serialize_task(task, TaskProjection.TOOL) - assert data["task_no"] == "SN-PROJ-TOOL" + assert data["task_no"] == "OT-PROJ-TOOL" assert data["customer_name"] is None assert data["lines"] == [] assert not TOOL_TASK_DATA_OMIT.intersection(data.keys()) -def test_task_projection_internal_keeps_status_fields(app): - """TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。""" +def test_task_projection_internal_keeps_stage_fields(app): + """TOOL_INTERNAL 保留 OT 流程阶段字段,复核旧投影不再作为 Notice 字段。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-PROJ-INT", - review_status="parse_review", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-PROJ-INT", user_id=1, + stage="parse_review", + source_type="direct_pdf", ) data = serialize_task(task, TaskProjection.TOOL_INTERNAL) - assert "review_status" in data - assert data["review_status"] == "parse_review" + assert data["current_step"] == "parse_review" def test_resolve_task_from_payload_by_conversation_id_single_active_task(app): """conversation_id 仅在同会话只有一票可操作任务时允许回退。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-CONV-1", + task = ShippingOrderTask( + task_no="OT-CONV-1", user_id=1, conversation_id="conv-abc", - source_type="manual", + source_type="direct_pdf", ) from app import db @@ -182,7 +242,7 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app): resolved = resolve_task_from_payload({"conversation_id": "conv-abc"}) assert resolved is not None - assert resolved.task_no == "SN-CONV-1" + assert resolved.task_no == "OT-CONV-1" assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01" @@ -194,15 +254,15 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app): db.session.add_all( [ - ShippingNotice( - task_no="SN-CONV-MULTI-1", + ShippingOrderTask( + task_no="OT-CONV-MULTI-1", user_id=1, conversation_id="conv-multi", - source_type="manual", + source_type="direct_pdf", ), - ShippingNotice( - task_no="SN-CONV-MULTI-2", + ShippingOrderTask( + task_no="OT-CONV-MULTI-2", user_id=1, conversation_id="conv-multi", - source_type="manual", + source_type="direct_pdf", ), ] ) @@ -211,10 +271,10 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app): assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None resolved = resolve_task_from_payload( - {"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"} + {"conversation_id": "conv-multi", "task_id": "OT-CONV-MULTI-1"} ) assert resolved is not None - assert resolved.task_no == "SN-CONV-MULTI-1" + assert resolved.task_no == "OT-CONV-MULTI-1" def test_task_can_handle_only_creator(app): @@ -252,24 +312,13 @@ def test_get_task_for_user_rejects_null_owner(app): get_task_visible_to_user, ) - orphan = ShippingNotice( - task_no="SN-NULL-OWNER", - source_type="manual", - user_id=None, - ) - owned = ShippingNotice( - task_no="SN-OWNED", - source_type="manual", - user_id=7, - ) - db.session.add_all([orphan, owned]) + owned = ShippingOrderTask(task_no="OT-OWNED", user_id=7, source_type="direct_pdf") + db.session.add(owned) db.session.commit() - assert get_task_for_user("SN-NULL-OWNER", 7) is None - assert get_task_for_user("SN-OWNED", 7) is not None - assert get_task_for_user("SN-OWNED", 8) is None - assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None - assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None + assert get_task_for_user("OT-OWNED", 7) is not None + assert get_task_for_user("OT-OWNED", 8) is None + assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None def test_serialize_task_summary_enriches_todo_and_can_handle(app): @@ -278,24 +327,23 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): from app import db from app.services.shipping_notice.query_service import serialize_task_summary - task = ShippingNotice( - task_no="SN-ENRICH-1", - review_status="parse_review", + task = ShippingOrderTask( + task_no="OT-ENRICH-1", user_id=11, + stage="parse_review", pending_human_reason="low_confidence", - source_type="manual", - user_id=11, - export_file_name="a.xlsx", - export_file_path="/tmp/a.xlsx", + source_type="direct_pdf", ) db.session.add(task) db.session.commit() data = serialize_task_summary(task, viewer_user_id=11) - assert data["todo_category"] == "review" + assert data["todo_category"] == "in_progress" assert data["created_by"] == 11 assert data["can_handle"] is True - assert data["ui_state"]["checkpoint"]["code"] == "parse_review" - assert data["artifact_summary"]["export_file_name"] == "a.xlsx" + # 无 Gate 且无 review_status:薄回退不投影 order_freeze + assert data["ui_state"]["position"] is None + assert data["ui_state"]["user_mode"] == "auto_continue" + assert data["artifact_summary"] is None no_viewer = serialize_task_summary(task) assert "can_handle" not in no_viewer @@ -305,28 +353,58 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app): """同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。""" with app.app_context(): from app import db - from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch + from app.models import ( + ShippingNoticeLine, ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, + ) from app.services.shipping_notice.query_service import serialize_task_summary - first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11) - second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11) + first_task = ShippingOrderTask(task_no='OT-NOTICE-1', user_id=11) + second_task = ShippingOrderTask(task_no='OT-NOTICE-2', user_id=11) + db.session.add_all([first_task, second_task]); db.session.flush() + first_snapshot = ShippingOrderSnapshot( + task_id=first_task.id, extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + second_snapshot = ShippingOrderSnapshot( + task_id=second_task.id, extraction_id=2, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add_all([first_snapshot, second_snapshot]); db.session.flush() + first_snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=first_snapshot.id, position=0, line_no=1, field_values_json={}, + ) + second_snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=second_snapshot.id, position=0, line_no=1, field_values_json={}, + ) + db.session.add_all([first_snapshot_line, second_snapshot_line]); db.session.flush() + first = ShippingNotice( + task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11, + order_task_id=first_task.id, + ) + second = ShippingNotice( + task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11, + order_task_id=second_task.id, + ) + first_task.order_snapshot_id = first_snapshot.id + second_task.order_snapshot_id = second_snapshot.id db.session.add_all([first, second]); db.session.flush() db.session.add_all([ ShippingNoticeLine( - notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST', - reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'}, + notice_id=first.id, snapshot_line_id=first_snapshot_line.id, position=1, line_no=1, + part_number='PART-FIRST', reservation_id='RES-1', required_qty='12', field_values_json={}, ), ShippingNoticeLine( - notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND', - reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'}, + notice_id=second.id, snapshot_line_id=second_snapshot_line.id, position=1, line_no=1, + part_number='PART-SECOND', reservation_id='RES-2', required_qty='8', field_values_json={}, ), ShippingNoticeLineInventoryMatch( - task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready', - available_qty='20', shortage_qty='0', is_current=True, + task_id=first_task.id, snapshot_line_id=first_snapshot_line.id, line_no=1, + match_result='matched', inventory_status='ready', available_qty='20', shortage_qty='0', is_current=True, ), ShippingNoticeLineInventoryMatch( - task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready', - available_qty='9', shortage_qty='0', is_current=True, + task_id=second_task.id, snapshot_line_id=second_snapshot_line.id, line_no=1, + match_result='matched', inventory_status='ready', available_qty='9', shortage_qty='0', is_current=True, ), ]) db.session.commit() @@ -335,7 +413,7 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app): assert data['business_no'] == 'WVC26082301' assert data['notice_line_summary'] == [{ - 'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST', + 'line_no': 1, 'part_number': 'PART-FIRST', 'customer_part_number': None, 'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20', 'shortage_qty': '0', 'inventory_status': 'ready', @@ -358,8 +436,8 @@ def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app): other = with_po('SN-GROUP-4', 'WYC26082499', 99) db.session.add_all([first, second, no_business, other]); db.session.flush() db.session.add_all([ - ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}), - ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}), + ShippingNoticeLine(notice_id=first.id, snapshot_line_id=1, position=1, line_no=1, part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={}), + ShippingNoticeLine(notice_id=second.id, snapshot_line_id=2, position=1, line_no=1, part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={}), ]) db.session.commit() @@ -387,9 +465,6 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app): first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11) db.session.add(first); db.session.flush() - first.upload_status = 'failed' - first.upload_error_code = 'RPA_UPLOAD_FAILED' - first.upload_error_message = '货代平台拒绝:凭证无效' db.session.commit() original_header_reader = query_service.current_header_field_values_or_empty @@ -401,9 +476,10 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app): item = result['items'][0] assert item['business_no'] == 'WYC26082401' - assert item['upload_status'] == 'failed' - assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED' - assert item['upload_error_message'] == '货代平台拒绝:凭证无效' + # 没有 UploadAttempt 就没有上传结果,Notice 历史投影不再作为事实来源。 + assert item['upload_status'] is None + assert item['upload_error_code'] is None + assert item['upload_error_message'] is None def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app): @@ -413,20 +489,23 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti from app.models import ShippingOrderSnapshot from app.services.shipping_notice import query_service - first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11) - second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11) + first_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-1', user_id=11, source_type='direct_pdf') + second_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-2', user_id=11, source_type='direct_pdf') + db.session.add_all([first_task, second_task]); db.session.flush() + first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11, order_task_id=first_task.id) + second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11, order_task_id=second_task.id) db.session.add_all([first, second]); db.session.flush() - for task in (first, second): + for task, owner in ((first, first_task), (second, second_task)): snapshot = ShippingOrderSnapshot( - task_id=task.id, - extraction_id=task.id, + task_id=owner.id, + extraction_id=owner.id, schema_version_id=1, order_data_version=1, header_values_json={}, customer_po_number='ZNB-16754796', ) db.session.add(snapshot); db.session.flush() - task.order_snapshot_id = snapshot.id + owner.order_snapshot_id = snapshot.id db.session.commit() original_header_reader = query_service.current_header_field_values_or_empty @@ -498,52 +577,166 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app): item = result['items'][0] assert item['business_no'] == 'WYC26082501' + # 权威事实:人工确认成功 → Attempt.status=succeeded,但 Notice 面必须投影为 uploaded。 + assert item['upload_status'] == 'uploaded' # 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。 assert item['upload_mode'] == 'manual' assert item['upload_attempt'] == 1 +def test_freight_notice_groups_available_actions_use_order_task_execution(app): + """货代上传单条菜单必须经 Notice.order_task_id 读 OT Execution,禁止用 Notice.id 查 Gate。 + + 回归点:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id; + Artifact.task_id 才是 Notice 主键。若误用 Notice.id,聚合只会留下 download_excel, + 行内 RPA/确认上传按钮全部消失。 + """ + with app.app_context(): + from app import db + from app.models import ShippingProcessExecution, ShippingProcessGate + from app.services.shipping_notice import query_service + + # 两张表在空库上都会从 1 起号;只给 OT 表垫一条废数据,强制 Notice.id ≠ OT.id, + # 否则「误用 Notice.id 查 Execution」在单测里会碰巧命中。 + db.session.add(ShippingOrderTask( + task_no='OT-GROUP-ACTIONS-PAD', user_id=11, source_type='direct_pdf', + )) + db.session.flush() + + order_task = ShippingOrderTask( + task_no='OT-GROUP-ACTIONS-1', user_id=11, source_type='direct_pdf', + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-GROUP-ACTIONS-1', + business_no='WYC26090601', + source_type='manual', + user_id=11, + order_task_id=order_task.id, + ) + db.session.add(notice) + db.session.flush() + # Notice.id 与 OT.id 必须不同,否则会掩盖「误用 Notice.id 查 Execution」的回归。 + assert int(notice.id) != int(order_task.id) + + execution = ShippingProcessExecution( + execution_no='EXE-GROUP-ACTIONS-1', + task_id=int(order_task.id), + status='blocked', + current_gate_code='manual_upload_handoff', + primary_next_action_code='mark_manual_uploaded', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='manual_upload_handoff', + sequence_no=20, + status='blocked_manual', + evaluation_version=1, + blocking_reason_code='manual_upload_pending', + next_action_code='mark_manual_uploaded', + )) + order_task.active_process_execution_id = int(execution.id) + db.session.commit() + + original_header_reader = query_service.current_header_field_values_or_empty + query_service.current_header_field_values_or_empty = lambda _task: { + 'customer_po_number': 'PO-ACTIONS', + } + try: + result = list_freight_notice_groups_for_task(notice, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + + actions = set(result['items'][0]['available_actions'] or []) + assert 'mark_manual_uploaded' in actions + assert 'retry_freight_upload_rpa' in actions + + def test_list_my_todos_and_count_buckets(app): - """list_my_todos 按 bucket 分类;count 徽标与 pending 一致。""" + """待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。""" with app.app_context(): from app import db from app.services.shipping_notice.query_service import count_my_todos, list_my_todos owner = 55 - review = ShippingNotice( - task_no="SN-TODO-REVIEW", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + review = ShippingOrderTask( + task_no="OT-TODO-REVIEW", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=owner, ) + upload_order = ShippingOrderTask( + task_no="OT-TODO-UPLOAD", source_type="direct_pdf", user_id=owner, + ) + done_order = ShippingOrderTask( + task_no="OT-TODO-DONE", source_type="direct_pdf", user_id=owner, + ) upload = ShippingNotice( task_no="SN-TODO-UPLOAD", source_type="manual", user_id=owner, - export_file_path="/tmp/u.xlsx", - export_file_name="u.xlsx", ) done = ShippingNotice( task_no="SN-TODO-DONE", source_type="manual", user_id=owner, - upload_status="uploaded", ) - other = ShippingNotice( - task_no="SN-TODO-OTHER", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + other = ShippingOrderTask( + task_no="OT-TODO-OTHER", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=99, ) - db.session.add_all([review, upload, done, other]) + db.session.add_all([review, upload_order, done_order, upload, done, other]) + template = ShippingExcelTemplate( + template_code='TODO', display_name='Todo', version=1, status='published', + storage_bucket='test', storage_key='todo.xlsx', original_filename='todo.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='TODO', display_name='Todo', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='TODO', display_name='Todo') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + upload.order_task_id = upload_order.id + done.order_task_id = done_order.id + def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact: + """为 Notice 建立待办分类所需的最小正式 Excel Artifact。""" + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=notice.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + ) + db.session.add(artifact) + return artifact + + upload_artifact = add_artifact(upload, artifact_no='ART-TODO-UPLOAD', status='ready') + done_artifact = add_artifact(done, artifact_no='ART-TODO-DONE', status='uploaded') + db.session.flush() db.session.commit() pending = list_my_todos(owner, bucket="pending", page=1, page_size=20) assert pending["total"] == 2 assert {item["task_no"] for item in pending["items"]} == { - "SN-TODO-REVIEW", + "OT-TODO-REVIEW", "SN-TODO-UPLOAD", } assert all(item["can_handle"] is True for item in pending["items"]) @@ -560,7 +753,7 @@ def test_list_my_todos_and_count_buckets(app): admin_pending = list_my_todos(owner, bucket="pending", is_admin=True) assert admin_pending["total"] >= 3 other_item = next( - item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER" + item for item in admin_pending["items"] if item["task_no"] == "OT-TODO-OTHER" ) assert other_item["can_handle"] is False @@ -661,6 +854,75 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil assert original.case_no not in review_case_nos +def test_reparse_document_with_reviewable_candidate_stays_order_review(app): + """ + 回归 doc67:重解析(reparse_of_run_id 非空)终态切换未跑时,Stream.current_case + 仍是空的旧 Case(candidate_id=None),但同 Document 已存在当前可复核 Candidate。 + 此时工作台必须显示「订单复核」,不能被空的旧 Case 压回「接收解析」。 + """ + with app.app_context(): + from app import db + from app.models import ShippingOrderCandidate + from app.services.shipping_notice.order_extraction_plan import ( + ensure_order_extraction_plan, + ) + from app.services.shipping_notice.order_extraction_run_service import ( + transition_order_extraction_run, + ) + from app.services.shipping_notice.order_review_disposition_service import ( + reparse_case_document, + ) + from app.services.shipping_notice.order_review_service import ( + ensure_run_review_cases, + ) + from app.services.shipping_notice.query_service import list_my_todos + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input(suffix='DOC67-REPARSE') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + # 初始解析:无 Candidate 的 Case 成为当前版本(case14 空旧 Case 语义)。 + original = ensure_run_review_cases(run=source)[0] + assert original.candidate_id is None + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + + replacement_run, _ = reparse_case_document( + user_id=user.id, case_no=original.case_no, reason='rule_updated', + ) + ensure_order_extraction_plan(replacement_run) + # 重解析 Run 产生当前可复核 Candidate(candidate13 语义);finalizer 未切换当前 Case。 + db.session.add(ShippingOrderCandidate( + candidate_no='CAND-DOC67', + intake_id=int(intake.id), + primary_document_id=document.id, + candidate_key='doc67-reparse', + order_extraction_run_id=replacement_run.id, + )) + db.session.commit() + for unit in replacement_run.extraction_plan.units: + unit.status = 'candidate_ready' + db.session.commit() + replacement = ensure_run_review_cases(run=replacement_run)[0] + # 关键:不调用 activate_review_case,模拟重解析终态切换未跑 → case19 未成为当前。 + assert replacement.candidate_id is not None + assert replacement.case_no != original.case_no + + pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50) + review_case_nos = { + item['review_case_no'] + for item in pending['items'] + if item.get('item_kind') == 'review_case' + } + # 当前 Case 仍是空的旧 Case;同 Document 已有可复核 Candidate → 必须订单复核。 + assert original.case_no in review_case_nos + hit = next(item for item in pending['items'] if item.get('review_case_no') == original.case_no) + assert hit['ui_state']['lifecycle_stage'] == 'order_review' + assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [ + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', + ] + + def test_open_review_case_without_current_candidate_enters_intake_parse(app): """无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。""" with app.app_context(): @@ -793,11 +1055,10 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app): # 520 > 旧 limit(500),用于证明截断不再作为 total 来源。 total_tasks = 520 tasks = [ - ShippingNotice( - task_no=f"SN-TODO-PAGE-{index:04d}", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + ShippingOrderTask( + task_no=f"OT-TODO-PAGE-{index:04d}", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=owner, ) for index in range(total_tasks) @@ -823,79 +1084,74 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app): assert far["items"] == [] -def test_todo_category_lightweight_matches_orm_and_count(app): +def test_todo_category_sql_matches_formal_notice_facts(app): """ 轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。 断言意图:UNION 分页下推的 SQL 分类不得漂移口径。 """ with app.app_context(): - from types import SimpleNamespace - from app import db from app.services.shipping_notice.query_service import ( _task_todo_category_sql_expr, - _todo_category_from_task_row, count_my_todos, list_my_todos, task_todo_category, ) owner = 88 - fixtures = [ - ShippingNotice( - task_no="SN-LW-REVIEW", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-UPLOAD", - source_type="manual", - user_id=owner, - export_file_path="/tmp/lw.xlsx", - export_file_name="lw.xlsx", - ), - ShippingNotice( - task_no="SN-LW-SHORTAGE", - # 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。 - review_status="shortage_review", - pending_human_reason="shortage", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-DONE", - upload_status="uploaded", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-PROGRESS", - source_type="manual", - user_id=owner, - ), + order_tasks = [ + ShippingOrderTask(task_no=f"OT-LW-{key}", source_type="direct_pdf", user_id=owner) + for key in ('UPLOAD', 'DONE') ] - db.session.add_all(fixtures) + fixtures = [ + ShippingNotice(task_no="SN-LW-UPLOAD", source_type="manual", user_id=owner), + ShippingNotice(task_no="SN-LW-DONE", source_type="manual", user_id=owner), + ShippingNotice(task_no="SN-LW-PROGRESS", source_type="manual", user_id=owner), + ] + db.session.add_all([*order_tasks, *fixtures]) + db.session.flush() + fixtures[0].order_task_id = order_tasks[0].id + fixtures[1].order_task_id = order_tasks[1].id + template = ShippingExcelTemplate( + template_code='LW', display_name='LW', version=1, status='published', storage_bucket='test', + storage_key='lw.xlsx', original_filename='lw.xlsx', file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='LW', display_name='LW', version=1, status='published', file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='LW', display_name='LW') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted') + db.session.add(extraction) + db.session.flush() + def add_artifact(notice, artifact_no, status): + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=notice.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + ) + db.session.add(artifact) + return artifact + + done_artifact = add_artifact(fixtures[1], 'ART-LW-DONE', 'uploaded') + add_artifact(fixtures[0], 'ART-LW-UPLOAD', 'ready') + db.session.flush() + db.session.add(ShippingUploadAttempt( + artifact_id=done_artifact.id, attempt_no=1, mode='manual', status='succeeded', + idempotency_key='lw-done-upload', + )) db.session.commit() category_expr = _task_todo_category_sql_expr() for task in fixtures: - row = SimpleNamespace( - review_status=task.review_status, - pending_human_reason=task.pending_human_reason, - customer_resolution_status=task.customer_resolution_status, - order_snapshot_id=task.order_snapshot_id, - current_order_extraction_id=task.current_order_extraction_id, - inventory_lines_json=task.inventory_lines_json, - match_status=task.match_status, - export_file_path=task.export_file_path, - upload_status=task.upload_status, - ) expected = task_todo_category(task) - # 轻量路径与 ORM 路径同分类。 - assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected # SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。 sql_category = ( db.session.query(category_expr) @@ -905,42 +1161,49 @@ def test_todo_category_lightweight_matches_orm_and_count(app): assert sql_category == expected pending = list_my_todos(owner, bucket="pending", page=1, page_size=50) - assert pending["total"] == 3 + assert pending["total"] == 1 counts = count_my_todos(owner) - assert counts["pending"] == 3 + assert counts["pending"] == 1 assert counts["done"] == 1 assert counts["processing"] == 1 - assert counts["total_pending_badge"] == 3 + assert counts["total_pending_badge"] == 1 def test_serialize_task_detail_workbench_view_drops_editor_fields(app): - """工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。""" + """工作台 view=workbench 跳过 DETAIL 重投影,保留 ui_state/产物/行摘要,全量视图不受影响。""" with app.app_context(): + from unittest.mock import patch + from app import db from app.services.shipping_notice.query_service import serialize_task_detail - task = ShippingNotice( - task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11, - export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx", + task = ShippingOrderTask( + task_no="OT-WORKBENCH-VIEW", source_type="direct_pdf", user_id=11, ) db.session.add(task) db.session.commit() full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True) - wb = serialize_task_detail( - task, viewer_user_id=11, include_stage_context=True, view="workbench", - ) + with patch( + 'app.services.shipping_notice.query_service.serialize_task', + ) as serialize_task_mock: + wb = serialize_task_detail( + task, viewer_user_id=11, include_stage_context=True, view="workbench", + ) - # full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。 + # workbench 不得进入 SUMMARY/DETAIL 重投影(算之前就轻)。 + serialize_task_mock.assert_not_called() + # full 保留编辑器重字段;workbench 身份壳不含它们。 for key in ( "lines", "order_header", "order_header_fields", "order_line_fields", - "events", "field_conflicts", ): assert key in full assert key not in wb # workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。 - assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW" + assert wb["ui_state"]["task_no"] == "OT-WORKBENCH-VIEW" assert wb["ui_state"]["stage_context"] is not None - assert wb["artifact_summary"]["export_file_name"] == "n.xlsx" + assert wb["artifact_summary"] is None assert "notice_line_summary" in wb - assert "export_artifacts" in wb + assert "export_artifacts" not in wb + assert wb["task_no"] == "OT-WORKBENCH-VIEW" + assert wb["order_task_no"] == "OT-WORKBENCH-VIEW" \ No newline at end of file diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index f6617e61..a3ba82cb 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -56,6 +56,24 @@ def test_reservation_contract_only_accepts_five_or_ten_digits(): assert not is_valid_reservation_id("12345678901", numeric_only=True) +def test_validated_reservation_id_strips_optional_parenthesized_note(): + """完整数字可带括号备注;括号内容不是预约单号,普通尾随文本仍拒绝。""" + assert validated_reservation_id("3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("R2 @3000112934") == "3000112934" + assert validated_reservation_id("R2 @3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("R2 @3000112934 PENROSE") == "" + assert validated_reservation_id("3000112934 PENROSE") == "" + assert validated_reservation_id("abc3000112934(PENROSE)") == "" + assert validated_reservation_id("00011293") == "" + assert validated_reservation_id("30001129345") == "" + + +def test_validated_reservation_id_rejects_amount_text_as_numeric_token(): + """金额行中的五位整数片段不能被当成 Reservation ID。""" + assert validated_reservation_id("941.76 28,252.80") == "" + + def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present(): """专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。""" assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{ diff --git a/backend/tests/test_shipping_notice_state_machine.py b/backend/tests/test_shipping_notice_state_machine.py index db8cb73a..a25e4a72 100644 --- a/backend/tests/test_shipping_notice_state_machine.py +++ b/backend/tests/test_shipping_notice_state_machine.py @@ -1,92 +1,87 @@ """ tests/test_shipping_notice_state_machine.py -用途:校验发货通知 checkpoint 内部流程映射与 STP checkpoint_kind。 -依赖:pytest、state_machine、constants、ShippingNotice。 -逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。 +用途:校验发货通知位置→用户模式查找表与 Gate/review 薄回退。 +依赖:pytest、state_machine、constants、ShippingOrderTask。 +逻辑:validate_registry 无错误;关键位置 user_mode 正确;resolve_task_ui_state + 无 Gate 时仅凭 review_status 回退。 """ from types import SimpleNamespace -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_PARSE_REVIEW, - CP_UPLOADED, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, + POSITION_UPLOADED, PH_LOW_CONF, RS_PARSE_REVIEW, + RS_REJECTED, +) +from app.services.shipping_notice.state_machine import ( + UserMode, + resolve_task_ui_state, + user_mode_for_position, + validate_registry, ) -from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry def test_validate_registry_has_no_errors() -> None: - """checkpoint 仅维护内部流程分类。""" + """位置→用户模式查找表非空且自洽。""" assert validate_registry() == [] -def test_checkpoint_kinds_for_stp_stop_points() -> None: - """STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。""" - assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD - assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN - assert checkpoint_kind_for(CP_UPLOADED) == CheckpointKind.COMPLETE +def test_user_modes_for_stp_stop_points() -> None: + """STP 关键位置 user_mode:导出就绪待人工 / 解析复核 / 已上传终态。""" + assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD + assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN + assert user_mode_for_position(POSITION_UPLOADED) == UserMode.COMPLETE def test_resolve_task_ui_state_parse_review(app) -> None: - """pending_review + parse_review 应映射为 must_human / parse_review。""" + """无 Gate 时 review_status=parse_review 应映射为 must_human / parse_review。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-PARSE", + task = ShippingOrderTask( + task_no="OT-SM-PARSE", + user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", ) ui = resolve_task_ui_state(task) - assert ui.checkpoint == CP_PARSE_REVIEW - assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN + assert ui.position == POSITION_PARSE_REVIEW + assert ui.user_mode == UserMode.MUST_HUMAN -def test_resolve_task_ui_state_export_ready(app) -> None: - """matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。""" +def test_resolve_task_ui_state_rejected(app) -> None: + """无 Gate 时 review_status=rejected → complete / rejected。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-EXPORT", - source_type="manual", - export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", + task = ShippingOrderTask( + task_no="OT-SM-REJECT", + user_id=1, + review_status=RS_REJECTED, ) ui = resolve_task_ui_state(task) - assert ui.checkpoint == CP_EXPORT_READY - assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD - assert not hasattr(ui, 'human_options') + assert ui.position == 'rejected' + assert ui.user_mode == UserMode.COMPLETE -def test_resolve_task_ui_state_uploaded_complete(app) -> None: - """upload_status=uploaded 应为 complete。""" +def test_resolve_without_review_status_is_thin(app) -> None: + """无 Gate 且无 review_status 时不从领域标量投影位置(薄回退)。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-UPLOADED", - upload_status="uploaded", - source_type="manual", - ) + task = ShippingOrderTask(task_no="OT-SM-THIN", user_id=1) ui = resolve_task_ui_state(task) - assert ui.checkpoint == CP_UPLOADED - assert ui.checkpoint_kind == CheckpointKind.COMPLETE + assert ui.position is None + assert ui.user_mode == UserMode.AUTO_CONTINUE def test_resolve_with_mocked_simple_namespace_attributes() -> None: - """无 DB 会话时可用简易命名空间验证 uploaded 终态分支。""" + """无 DB 会话时简易命名空间:无 review_status → 薄回退 None/auto。""" task = SimpleNamespace( - upload_status="uploaded", review_status=None, pending_human_reason=None, - customer_resolution_status=None, - order_snapshot_id=None, - inventory_lines_json=None, - match_status=None, - export_file_path=None, - current_order_extraction_id=None, - step_payload_json=None, + order_task_id=None, + id=None, ) ui = resolve_task_ui_state(task) # type: ignore[arg-type] - assert ui.checkpoint_kind == CheckpointKind.COMPLETE - assert ui.checkpoint == CP_UPLOADED + assert ui.user_mode == UserMode.AUTO_CONTINUE + assert ui.position is None diff --git a/backend/tests/test_shipping_notice_stp_acceptance.py b/backend/tests/test_shipping_notice_stp_acceptance.py index d3b3109c..5920ccda 100644 --- a/backend/tests/test_shipping_notice_stp_acceptance.py +++ b/backend/tests/test_shipping_notice_stp_acceptance.py @@ -8,29 +8,66 @@ tests/test_shipping_notice_stp_acceptance.py from __future__ import annotations +from types import SimpleNamespace + import pytest -from app.models import ShippingNotice, User +from app.models import ( + ShippingExcelTemplate, + ShippingExportArtifact, + ShippingInventoryParsingProfile, + ShippingNotice, + ShippingOrderExtraction, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderTask, + User, +) from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_PARSE_REVIEW, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, PH_LOW_CONF, RS_PARSE_REVIEW, ) from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match, upload_to_freight from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.query_service import count_my_todos, list_my_todos -from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for -from app.services.shipping_notice.ui_state import build_task_ui_state +from app.services.shipping_notice.state_machine import UserMode, user_mode_for_position -def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None: +def _seed_export_artifact_view(monkeypatch) -> None: + """Excel 就绪事实只能由正式 Artifact 裁决:屏蔽旧 Notice 文件投影。 + + 生产函数分别经 upload_attempt_service(state_machine.resolve_task_ui_state 本地导入)与 + fulfillment_workflow(模块级 latest_export_artifact / latest_upload_attempt)读取导出产物; + 两处命名空间均需桩化,避免触达真实 Artifact 表。 + """ + artifact = SimpleNamespace(id=0, file_path="/tmp/stp-export.xlsx", file_name="stp-export.xlsx", status="ready") + monkeypatch.setattr( + "app.services.shipping_notice.upload_attempt_service.latest_export_artifact", + lambda _task: artifact, + ) + monkeypatch.setattr( + "app.services.shipping_notice.fulfillment_workflow.latest_export_artifact", + lambda _task: artifact, + ) + monkeypatch.setattr( + "app.services.shipping_notice.upload_attempt_service.latest_upload_attempt", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.fulfillment_workflow.latest_upload_attempt", + lambda _task: None, + ) + + +def test_stp_user_mode_matrix_covers_nine_scenario_stops() -> None: """九条场景依赖的停点 kind 不得漂移。""" - assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN - assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD + assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN + assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD -def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None: +def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None: """场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。""" with app.app_context(): from app import db @@ -38,16 +75,18 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True task = ShippingNotice( task_no="SN-STP-WAIT-UPLOAD", + business_no="SN-STP-WAIT-UPLOAD", source_type="manual", - export_file_path="/tmp/stp-export.xlsx", - export_file_name="stp-export.xlsx", ) db.session.add(task) db.session.commit() + # Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + result = auto_progress({"task_id": task.task_no, "source": "system"}) assert result["status"] == "ok" - assert result.get("checkpoint") == CP_EXPORT_READY + assert result.get("position") == POSITION_EXPORT_READY assert "upload_to_freight" in (result.get("forbidden_next_tools") or []) assert result.get("stop_agent_turn") is True assert "登记凭据" in str(result.get("message") or "") @@ -59,118 +98,162 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None: from app import db app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True - task = ShippingNotice( - task_no="SN-STP-MUST-HUMAN", + owner = ShippingOrderTask( + task_no="OT-STP-MUST-HUMAN", + user_id=1, + source_type="direct_pdf", review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, + ) + db.session.add(owner) + db.session.flush() + task = ShippingNotice( + task_no="SN-STP-MUST-HUMAN", + business_no="SN-STP-MUST-HUMAN", source_type="manual", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() result = auto_progress({"task_id": task.task_no, "source": "system"}) assert result["status"] == "needs_human" - assert result.get("checkpoint") == CP_PARSE_REVIEW + assert result.get("position") == POSITION_PARSE_REVIEW -def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch) -> None: - """场景:AUTO_UPLOAD=true 时匹配后串联须调用 upload_to_freight(mode=auto)。""" +def test_try_auto_chain_gate_path_skips_generate_and_upload(app, monkeypatch) -> None: + """Gate Attempt 路径:匹配成功后不得内嵌 generate_excel / upload_to_freight。""" with app.app_context(): from app import db - app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True - app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True - task = ShippingNotice( - task_no="SN-STP-RPA-ON", - match_status="fulfillable", - source_type="manual", - line_results_json=[{"line_status": "ok"}], - export_file_path="/tmp/already.xlsx", - export_file_name="already.xlsx", - ) + task = ShippingNotice(task_no='SN-STP-CHAIN-GATE', source_type='manual') db.session.add(task) db.session.commit() - upload_calls: list[dict] = [] - - def _fake_upload(payload): - upload_calls.append(dict(payload or {})) - return {"status": "running", "message": "rpa-triggered"} - monkeypatch.setattr( - "app.services.shipping_notice.fulfillment_workflow.upload_to_freight", - _fake_upload, + 'app.services.shipping_notice.fulfillment_workflow._current_export_artifact', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + + generate_calls: list[dict] = [] + upload_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.upload_to_freight', + lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'}, ) result = try_auto_chain_after_match( task, - {"status": "ok", "message": "matched"}, - payload={"task_id": task.task_no}, - ) - # 关键断言:自动链接入货代上传 RPA。 - assert len(upload_calls) == 1 - assert upload_calls[0].get("mode") == "auto" - assert result["status"] == "running" - - -def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch) -> None: - """场景:AUTO_UPLOAD=false 时停在人工上传,不调用 upload_to_freight。""" - with app.app_context(): - from app import db - - app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False - app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True - - task = ShippingNotice( - task_no="SN-STP-NO-RPA", - match_status="fulfillable", - source_type="manual", - line_results_json=[{"line_status": "ok"}], - export_file_path="/tmp/already.xlsx", - export_file_name="already.xlsx", - ) - db.session.add(task) - db.session.commit() - - upload_calls: list[dict] = [] - - def _fake_upload(payload): - upload_calls.append(dict(payload or {})) - return {"status": "running", "message": "should-not-run"} - - monkeypatch.setattr( - "app.services.shipping_notice.fulfillment_workflow.upload_to_freight", - _fake_upload, - ) - - result = try_auto_chain_after_match( - task, - {"status": "ok", "message": "matched"}, - payload={"task_id": task.task_no}, + {'status': 'ok', 'message': 'matched'}, + payload={ + 'task_id': task.task_no, + '_orchestrator_internal_dispatch': True, + 'source': 'process_gate', + }, ) + assert result['status'] == 'ok' + assert generate_calls == [] assert upload_calls == [] - assert result["status"] == "ok" - assert "upload_to_freight" in (result.get("forbidden_next_tools") or []) + + +def test_try_auto_chain_legacy_path_submits_artifact_auto_progress(app, monkeypatch) -> None: + """非 Gate 遗留路径:只提交 artifact_generation auto_progress,禁止直跑 generate。""" + with app.app_context(): + from app import db + + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + + task = ShippingNotice(task_no='SN-STP-CHAIN-LEGACY', source_type='manual') + db.session.add(task) + db.session.commit() + + progress_calls: list[dict] = [] + generate_calls: list[dict] = [] + + def _fake_progress(task_no, **kwargs): + progress_calls.append({'task_no': task_no, **kwargs}) + return {'status': 'running', 'message': 'queued-artifact'} + + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + _fake_progress, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={'task_id': task.task_no, 'source': 'legacy_tool'}, + ) + assert generate_calls == [] + assert len(progress_calls) == 1 + assert progress_calls[0]['resume_gate_code'] == 'artifact_generation' + assert result['status'] == 'running' + + +def test_try_auto_chain_skips_when_auto_generate_disabled(app, monkeypatch) -> None: + """AUTO_GENERATE_EXCEL=false 时遗留路径也不提交下游 chain。""" + with app.app_context(): + from app import db + + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = False + + task = ShippingNotice(task_no='SN-STP-NO-CHAIN', source_type='manual') + db.session.add(task) + db.session.commit() + + progress_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + lambda *args, **kwargs: progress_calls.append(kwargs) or {'status': 'running'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={'task_id': task.task_no}, + ) + assert progress_calls == [] + assert result['status'] == 'ok' + assert result.get('message') == 'matched' def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch) -> None: """场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。""" with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-MANUAL-CFM", + business_no="SN-STP-MANUAL-CFM", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="confirmed", - inventory_source_code="SRC1", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42) monkeypatch.setattr( @@ -231,22 +314,22 @@ def test_upload_to_freight_manual_confirm_ignores_inventory_source_stability(app """ with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM-UNSTABLE", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-MANUAL-CFM-UNSTABLE", + business_no="SN-STP-MANUAL-CFM-UNSTABLE", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="resolved", - inventory_source_code="SRC1", - inventory_connector_type="crane", - inventory_source_config_version="stale-version", - inventory_routing_fingerprint="stale-fingerprint", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42) # 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。 @@ -302,19 +385,22 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon """关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。""" with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-CLOSE-FAIL", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-CLOSE-FAIL", + business_no="SN-STP-CLOSE-FAIL", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="confirmed", - inventory_source_code="SRC1", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42) bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending") @@ -388,28 +474,76 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None: db.session.add_all([owner, admin]) db.session.flush() + # 复核系列(mine / other)以 Notice 挂接 OT,复核事实读取 OT 字段。 + mine_owner = ShippingOrderTask( + task_no="OT-STP-OWN", + user_id=owner.id, + source_type="direct_pdf", + review_status=RS_PARSE_REVIEW, + pending_human_reason=PH_LOW_CONF, + ) + upload_owner = ShippingOrderTask(task_no="OT-STP-UPLOAD", user_id=owner.id, source_type="direct_pdf") + other_owner = ShippingOrderTask( + task_no="OT-STP-OTHER", + user_id=admin.id, + source_type="direct_pdf", + review_status=RS_PARSE_REVIEW, + pending_human_reason=PH_LOW_CONF, + ) + db.session.add_all([mine_owner, upload_owner, other_owner]) + db.session.flush() + mine = ShippingNotice( task_no="SN-STP-OWN", user_id=owner.id, - review_status=RS_PARSE_REVIEW, - pending_human_reason=PH_LOW_CONF, source_type="manual", + order_task_id=mine_owner.id, ) waiting_upload = ShippingNotice( task_no="SN-STP-UPLOAD", user_id=owner.id, source_type="manual", - export_file_path="/tmp/own.xlsx", - export_file_name="own.xlsx", + order_task_id=upload_owner.id, ) other = ShippingNotice( task_no="SN-STP-OTHER", user_id=admin.id, - review_status=RS_PARSE_REVIEW, - pending_human_reason=PH_LOW_CONF, source_type="manual", + order_task_id=other_owner.id, ) db.session.add_all([mine, waiting_upload, other]) + db.session.flush() + + # manual_upload 分类必须由正式 Excel Artifact 裁决。 + template = ShippingExcelTemplate( + template_code="STP_TP", display_name="STP template", version=1, status="published", + storage_bucket="test", storage_key="test/stp.xlsx", original_filename="stp.xlsx", + file_checksum="a" * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code="STP_PF", display_name="STP profile", version=1, status="published", + file_format="xlsx", definition_json={}, + ) + schema = ShippingOrderSchema(schema_code="STP_SCHEMA", display_name="STP schema") + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status="published", definition_json={}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash="b" * 64, status="accepted", + ) + db.session.add(extraction) + db.session.flush() + db.session.add(ShippingExportArtifact( + artifact_no="ART-STP-UPLOAD", task_id=waiting_upload.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum="c" * 64, + file_path="/tmp/stp-own.xlsx", file_name="stp-own.xlsx", + file_checksum="d" * 64, file_size=1, status="ready", + )) db.session.commit() pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50) diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index fa52d7c7..cc4dfa20 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -2,7 +2,7 @@ backend/tests/test_shipping_notice_tools.py 用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。 -依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。 +依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。 逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。 """ @@ -13,16 +13,32 @@ import pytest from app import db from app.models import ( - ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, - ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, - ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, - ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, - ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingTaskEvent, ShippingTaskInventoryLink, + Agent, + ChatLog, + ChatSession, + ShippingCustomer, + ShippingInventoryField, + ShippingInventoryRoutingRule, + ShippingInventoryFile, + ShippingInventoryRoutingRuleCondition, + ShippingNotice, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, + ShippingTaskEvent, + ShippingTaskInventoryLink, + User, ) from app.services.shipping_notice.match import match_notice_lines from app.services.shipping_notice.order_schema import service as order_schema_service -from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source +from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source def _tool_headers(app): @@ -34,46 +50,63 @@ def _tool_headers(app): } -def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None: +def _seed_test_user(*, username: str) -> int: + """创建测试用户并返回主键,供 OT 建单与能力强令牌使用。""" + user = User(username=username, email=f"{username}@example.test", password_hash='x') + db.session.add(user) + db.session.flush() + return int(user.id) + + +def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None: """为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。""" - order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None) - fields = { - code: order_schema_service.save_field( - {'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None, + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() + if version is None: + order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None) + fields = { + code: order_schema_service.save_field( + {'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None, + ) + for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal')) + } + draft = order_schema_service.create_draft({}, actor_id=None) + purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'} + configs = [{ + 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code], + 'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal', + 'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'], + 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + } for code, field in fields.items()] + saved = order_schema_service.save_draft( + draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None, ) - for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal')) + published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + + field_ids = { + str(item['field_code']): str(item['field_id']) + for item in (version.definition_json or {}).get('fields') or [] } - draft = order_schema_service.create_draft({}, actor_id=None) - purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'} - configs = [{ - 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code], - 'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal', - 'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'], - 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, - 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', - } for code, field in fields.items()] - saved = order_schema_service.save_draft( - draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None, - ) - published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + extraction = ShippingOrderExtraction( - task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted', + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity} for code, value in values.items(): decision = ShippingOrderFieldDecision( - extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_status='accepted', + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted', supporting_observation_ids_json=[], resolved_value_json=value, ) db.session.add(decision) db.session.flush() db.session.add(ShippingOrderFieldValue( - extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_id=decision.id, + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id, value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=value, )) @@ -81,14 +114,14 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation # RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时 # 建立最小履约真相,避免旧测试绕过阶段 1 门禁。 snapshot = ShippingOrderSnapshot( - task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], + task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, order_data_version=task.order_data_version or 1, rule_versions_json={'fulfillment_policy': { 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, 'definition': {'field_bindings': [ - {'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'}, - {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'}, - {'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'}, + {'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'}, ]}, }}, header_values_json={}, @@ -96,26 +129,41 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id, + snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id, qty=quantity, field_values_json={ - str(fields['part_number']['id']): part_number, - str(fields['reservation_id']['id']): reservation_id, - str(fields['qty']['id']): quantity, + str(field_ids['part_number']): part_number, + str(field_ids['reservation_id']): reservation_id, + str(field_ids['qty']): quantity, }, )) task.order_snapshot_id = snapshot.id db.session.flush() +def _confirm_test_task_customer(task: ShippingOrderTask) -> None: + """为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。""" + customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name='RPA 直接回调测试客户', short_code='RPC', status='active', + ) + db.session.add(customer) + db.session.flush() + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + task._test_customer_confirmed = True + + def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" app.config["INTEGRATION_API_KEY"] = "" + user_id = _seed_test_user(username='auth-dedicated') res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) assert res.status_code == 200 @@ -126,11 +174,12 @@ def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = "integration-secret" + user_id = _seed_test_user(username='auth-integration') res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) assert res.status_code == 200 @@ -145,7 +194,7 @@ def test_shipping_notice_tool_auth_reports_missing_config(app, client): res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "any"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf"}, ) assert res.status_code == 503 @@ -157,7 +206,7 @@ def test_parse_notice_tool_is_removed(app, client): response = client.post( "/api/shipping-notice/tools/parse_notice", headers=_tool_headers(app), - json={"task_id": "SN-REMOVED"}, + json={"task_id": "OT-REMOVED"}, ) assert response.status_code == 404 @@ -179,14 +228,14 @@ def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch): ) result = fulfillment_workflow.generate_excel({ - 'task_id': 'SN-FORMAL-EXCEL-ONLY', + 'task_id': 'OT-FORMAL-EXCEL-ONLY', 'operator_id': 7, 'idempotency_key': 'formal-excel-only', }) assert result['status'] == 'running' assert submitted == { - 'task_no': 'SN-FORMAL-EXCEL-ONLY', + 'task_no': 'OT-FORMAL-EXCEL-ONLY', 'trigger': 'tool_api_generate_excel', 'expected_version': None, 'idempotency_key': 'formal-excel-only', @@ -222,20 +271,36 @@ def test_match_notice_lines_reports_progress(): def test_contract_get_task_status_accepts_task_no_anchor(app, client): - """契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。""" + """契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。""" + from app.services.shipping_notice.chat_tool_capability import issue_chat_capability + headers = _tool_headers(app) + with app.app_context(): + app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret" + user_id = _seed_test_user(username='status-anchor') + agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor') + db.session.add(agent) + db.session.flush() + session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id) + db.session.add(session) + db.session.commit() + session_id = session.session_id + agent_id = int(agent.id) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, - json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"}, + json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id, + "raw_content": "客户:ACME 料号A001 x 10"}, ) task_id = create_res.get_json()["task_id"] + token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id) + status_res = client.post( "/api/shipping-notice/tools/get_task_status", headers=headers, - json={"task_no": task_id}, + json={"task_no": task_id, "shipping_chat_capability_token": token}, ) data = status_res.get_json() @@ -273,12 +338,11 @@ def test_confirm_inventory_source_route_is_removed(app, client): """库存源人工确认已下线,任何旧 Tool 写入口均不得可达。""" headers = _tool_headers(app) with app.app_context(): - task = ShippingNotice( - task_no="SN-HTTP-CONFIRM-SRC", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-HTTP-CONFIRM-SRC", + user_id=1, + source_type="eml", pending_human_reason="inventory_source_unresolved", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}], ) db.session.add(task) db.session.commit() @@ -286,7 +350,7 @@ def test_confirm_inventory_source_route_is_removed(app, client): res = client.post( "/api/shipping-notice/tools/confirm_inventory_source", headers=headers, - json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, + json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, ) assert res.status_code == 404 @@ -304,91 +368,13 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords(): assert "match_inventory" not in spec_text -@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"]) -def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision): - """已启用库存站点不得通过任务决策重开旧列映射路径。""" - headers = _tool_headers(app) - with app.app_context(): - task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual") - db.session.add(task) - db.session.commit() - - response = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision}, - ) - - assert response.status_code == 200 - body = response.get_json() - # These decisions must never reopen manual mapping or mutate the task. - assert body["status"] == "failed" - assert "已发布解析方案" in body["message"] - - -def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path): - """重新上传库存只重置正式库存结果,不进入任务级字段映射。""" - headers = _tool_headers(app) - with app.app_context(): - task = ShippingNotice( - task_no="SN-REUPLOAD-INVENTORY", - source_type="manual", - inventory_lines_json=[{"part_number": "A001", "available_qty": 10}], - match_status="fulfillable", - line_results_json=[{"part_number": "A001"}], - shortage_json={"lines": []}, - export_file_path=str(tmp_path / "shipment.xlsx"), - export_file_name="shipment.xlsx", - ) - db.session.add(task) - db.session.flush() - inventory_file = ShippingInventoryFile( - inventory_file_no="SIF-REUPLOAD-001", - storage_path=str(tmp_path / "inventory.xlsx"), - source_file_name="inventory.xlsx", - ) - db.session.add(inventory_file) - db.session.flush() - link = ShippingTaskInventoryLink( - task_id=task.id, - inventory_file_id=inventory_file.id, - link_role="owner", - ) - db.session.add(link) - db.session.commit() - - response = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"}, - ) - - assert response.status_code == 200 - body = response.get_json() - assert body["status"] == "needs_human" - assert body["checkpoint"] == "upload_req" - assert "human_options" not in body - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one() - link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one() - assert link.is_active is False - assert task.pending_human_reason == "inv_unavail" - assert task.pending_human_reason == "inv_unavail" - assert task.inventory_lines_json is None - assert task.match_status is None - assert task.line_results_json is None - assert task.shortage_json is None - assert task.export_file_path is None - assert task.export_file_name is None - - def test_parse_inventory_from_chat_text_route_is_removed(app, client): """正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。""" headers = _tool_headers(app) parse_inv = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, ) assert parse_inv.status_code == 404 assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -400,7 +386,7 @@ def test_parse_inventory_empty_text_route_is_removed(app, client): res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": " "}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": " "}, ) assert res.status_code == 404 assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -413,7 +399,7 @@ def test_match_by_supplier_sku_and_reservation_id(app, client): "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n", }, ) @@ -427,7 +413,7 @@ def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, clie "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n", }, ) @@ -441,7 +427,7 @@ def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, clie "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": ( "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n" "D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n" @@ -459,87 +445,10 @@ def test_legacy_task_inventory_mapping_routes_are_removed(app, client): "/api/shipping-notice/tools/get_inventory_schema_preview", "/api/shipping-notice/tools/apply_inventory_mapping", ): - response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"}) + response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"}) assert response.status_code == 404 -@pytest.mark.auto_rpa -def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch): - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - inventory_drop = tmp_path / "inventory_drop" - trigger.mkdir() - inventory_drop.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.review_status = None - task.pending_human_reason = "inv_unavail" - task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}] - task.match_status = "fulfillable" - task.shortage_json = {"lines": []} - task.line_results_json = [{"part_number": "OLD", "status": "ok"}] - task.export_file_path = str(tmp_path / "old.xlsx") - task.export_file_name = "old.xlsx" - task.upload_status = "failed" - task.upload_mode = "rpa" - task.upload_error_message = "old upload failed" - task.freight_ref_no = "OLD-REF" - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.commit() - - from app.services.shipping_notice import decision_workflow - - with app.app_context(): - retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) - assert retry_data["status"] == "running" - assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"} - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == "rpa_pending" - assert task.pending_human_reason == "rpa_pending" - assert task.review_status is None - assert task.inventory_lines_json is None - assert task.match_status is None - assert task.shortage_json is None - assert task.line_results_json is None - assert task.export_file_path is None - assert task.export_file_name is None - assert task.upload_status is None - assert task.upload_error_message is None - assert task.freight_ref_no is None - event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first() - assert event is not None - assert event.detail_json.get("force_refresh") is True - assert len(list(trigger.glob("inventory_export_*.json"))) == 1 - - @pytest.mark.auto_rpa def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch): from datetime import datetime, timedelta @@ -557,17 +466,21 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt lambda: None, ) + with app.app_context(): + user_id = _seed_test_user(username='rpa-timeout-recheck') + create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) task_id = create_res.get_json()["task_id"] with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() assert task is not None _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) + _confirm_test_task_customer(task) task.pending_human_reason = PH_RPA_PENDING task.step_payload_json = { "rpa_inventory_source": { @@ -591,7 +504,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt with app.app_context(): result = _run_single_task(task_id) - task = ShippingNotice.query.filter_by(task_no=task_id).first() + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() assert task is not None assert result["status"] == "needs_human" assert task.pending_human_reason == PH_RPA_EXHAUSTED @@ -602,171 +515,13 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt assert len(list(trigger.glob("inventory_export_*.json"))) == 0 -@pytest.mark.auto_rpa -def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch): - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - from datetime import datetime, timedelta - - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED - - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - inventory_drop = tmp_path / "inventory_drop" - trigger.mkdir() - inventory_drop.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.pending_human_reason = PH_RPA_EXHAUSTED - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - base_time = datetime.utcnow() - timedelta(minutes=5) - for idx in range(3): - db.session.add( - ShippingTaskEvent( - task_id=task.id, - event_type="inventory_rpa_triggered", - detail_json={"attempt": idx + 1}, - created_at=base_time + timedelta(seconds=idx), - ) - ) - db.session.commit() - - from app.services.shipping_notice import decision_workflow - - with app.app_context(): - retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) - assert retry_data["status"] == "running" - assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1 - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == "rpa_pending" - assert task.pending_human_reason == "rpa_pending" - assert task.error_message is None - progress = (task.step_payload_json or {}).get("current_step_progress") or {} - assert progress.get("current") == 1 - assert progress.get("extra", {}).get("manual_retry_round") is True - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4 - assert len(list(trigger.glob("inventory_export_*.json"))) == 1 - - -def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client): - headers = _tool_headers(app) - - first = ShippingNotice( - task_no="SN-MULTI-CONV-001", - conversation_id="conv-test-multi", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}], - ) - second = ShippingNotice( - task_no="SN-MULTI-CONV-002", - conversation_id="conv-test-multi", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}], - ) - with app.app_context(): - db.session.add_all([first, second]) - db.session.commit() - - confirm_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"conversation_id": "conv-test-multi", "decision": "confirm"}, - ) - confirm_data = confirm_res.get_json() - assert confirm_data["status"] == "failed" - assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"] - - status_res = client.post( - "/api/shipping-notice/tools/get_task_status", - headers=headers, - json={"conversation_id": "conv-test-multi"}, - ) - status_data = status_res.get_json() - assert status_data["status"] == "failed" - assert "任务编号" in status_data["message"] - - with app.app_context(): - rows = { - task.task_no: task - for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"])) - .order_by(ShippingNotice.task_no) - .all() - } - assert rows["SN-MULTI-CONV-001"].review_status == "parse_review" - assert rows["SN-MULTI-CONV-002"].review_status == "parse_review" - - -def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch): - headers = _tool_headers(app) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - import app.services.shipping_notice.decision_workflow as decision_workflow - - captured: dict[str, object] = {} - - def fake_request_formal_gate_action(**kwargs): - captured.update(kwargs) - return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"} - - monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action) - - res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"}, - ) - data = res.get_json() - assert data["status"] == "running" - assert data["task_id"] == task_id - assert data["message"] == "已提交正式 20-Gate 恢复动作" - assert captured["task"].task_no == task_id - assert captured["action_code"] == "retry_inventory_preparation" - - def test_parse_inventory_oversized_text_route_is_removed(app, client): """旧正式库存文本入口无论内容大小都不可访问。""" headers = _tool_headers(app) res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200}, ) assert res.status_code == 404 assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -776,12 +531,13 @@ def test_chat_actions_empty_when_task_rejected(app): from app.services.shipping_notice.ui_state import build_task_ui_state with app.app_context(): - task = ShippingNotice( - task_no="SN-20260101-TEST0001", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-20260101-TEST0001", + user_id=1, + source_type="eml", review_status="rejected", ) ui_state = build_task_ui_state(task) - assert ui_state["checkpoint"]["code"] == "rejected" + assert ui_state["review_status"] == "rejected" assert ui_state["actions"] == {"primary": None, "secondary": []} assert "action_buttons" not in ui_state diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index a26d008f..0fb1eed8 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -2,16 +2,24 @@ tests/test_shipping_notice_ui_state.py 用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。 -依赖:pytest、ShippingNotice、ui_state、state_machine constants。 -逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。 +依赖:pytest、ShippingNotice、ui_state、state_machine constants、库存源/发货模板模型。 +逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确; + stage_context.preparation 短缺行投影 release_required_fields; + preparation.source_options 下发已启用源供行级覆写下拉; + 行级 selected_source_code(Candidate)与 source_code(Match)分字段; + Notice 详情经 order_task_id→OT 读取 Snapshot/Match。 """ from app import db from app.core.auth.jwt import issue_local_access_token -from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User +from app.models import ( + ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, + ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User, +) from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_PARSE_REVIEW, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, PH_LOW_CONF, RS_PARSE_REVIEW, ) @@ -24,7 +32,7 @@ _REQUIRED_SUMMARY_KEYS = { "message", "issues", "stage", - "checkpoint_kind", + "user_mode", "current_todo", "pause_reason", "next_auto_step", @@ -34,6 +42,43 @@ _REQUIRED_SUMMARY_KEYS = { } +def _frozen_task_with_line( + *, + task_no: str, + user_id: int = 1, + reservation_id: str | None = None, + part_number: str | None = None, + qty: str | None = None, + field_values_json: dict | None = None, +) -> tuple[ShippingOrderTask, ShippingOrderSnapshotLine]: + """建立通知准备测试所需的最小 OT 冻结档与订单项次。""" + task = ShippingOrderTask(task_no=task_no, user_id=user_id, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=task.id, + schema_version_id=1, + order_data_version=1, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + reservation_id=reservation_id, + part_number=part_number, + qty=qty, + field_values_json=field_values_json or {}, + ) + db.session.add(line) + db.session.flush() + return task, line + + def test_unified_actions_deduplicates_gate_primary_action(): """Gate 主动作同时出现在展示列表时,只能渲染一次。""" state = _unified_actions( @@ -95,23 +140,24 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback() def test_build_task_ui_state_summary_has_required_keys(app) -> None: """summary 必须包含 STP 可解释字段全集。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-SUMMARY", + task = ShippingOrderTask( + task_no="OT-UI-SUMMARY", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys()) - assert state["checkpoint"]["code"] == CP_PARSE_REVIEW - assert state["checkpoint_kind"] == "must_human" + # 无 Gate 时按领域标量回退:parse_review 不得再被 OT 空 stage 盖成 order_freeze。 + assert state["position"] == POSITION_PARSE_REVIEW + assert state["user_mode"] == "must_human" assert "stp_facts" not in state["summary"] def test_task_ui_state_stage_context_is_opt_in(app) -> None: """列表等轻量调用默认不得加载阶段工作面详情。""" with app.app_context(): - task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual") + task = ShippingOrderTask(task_no="OT-UI-LIGHTWEIGHT", user_id=1, source_type="direct_pdf") state = build_task_ui_state(task) detailed_state = build_task_ui_state(task, include_stage_context=True) @@ -122,13 +168,13 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: - """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" + """无正式 Gate 时位置不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STAGE-ACTIONS", + task = ShippingOrderTask( + task_no="OT-UI-STAGE-ACTIONS", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert state["stage"]["code"] == "unclassified" @@ -139,13 +185,13 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: - """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" + """正式工作台入口必须来自 Gate,不能按旧位置码生成。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-LIFECYCLE-ENTRIES", + task = ShippingOrderTask( + task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert state["lifecycle_stage"] == "unclassified" @@ -162,7 +208,7 @@ def test_task_ui_state_ignores_superseded_process_execution(app) -> None: user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual') + task = ShippingOrderTask(task_no='OT-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') @@ -182,10 +228,10 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice( - task_no='SN-UI-GATE-AUTHORITY', + task = ShippingOrderTask( + task_no='OT-UI-GATE-AUTHORITY', user_id=user.id, - source_type='manual', + source_type='direct_pdf', # 模拟历史字段尚未同步:旧字段仍像解析复核。 review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, @@ -215,10 +261,10 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice( - task_no='SN-UI-UPLOAD-GATE-AUTHORITY', + task = ShippingOrderTask( + task_no='OT-UI-UPLOAD-GATE-AUTHORITY', user_id=user.id, - source_type='manual', + source_type='direct_pdf', review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, ) @@ -241,17 +287,11 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None: """库存和上传历史字段不能再替代正式 Gate 生成生命周期。""" with app.app_context(): - fulfillment = ShippingNotice( - task_no="SN-UI-FULFILLMENT", - source_type="manual", - match_status="partial", - inventory_lines_json=[{"part_number": "P-1"}], - ) - upload = ShippingNotice( - task_no="SN-UI-UPLOAD", - source_type="manual", - upload_status="uploaded", + fulfillment = ShippingOrderTask( + task_no="OT-UI-FULFILLMENT", user_id=1, + source_type="direct_pdf", ) + upload = ShippingOrderTask(task_no="OT-UI-UPLOAD", user_id=1, source_type="direct_pdf") assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified" upload_state = build_task_ui_state(upload, include_stage_context=True) assert upload_state["stage"]["code"] == "unclassified" @@ -262,37 +302,81 @@ def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> Non def test_entry_surface_parse_review_is_review_workbench(app) -> None: """解析复核应进入人工复核工作台。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-REVIEW", + task = ShippingOrderTask( + task_no="OT-UI-REVIEW", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert state["summary"]["entry_surface"] == "review_workbench" -def test_entry_surface_export_ready_is_task_workbench(app) -> None: - """Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。""" +def test_build_task_ui_state_queries_process_gate_once(app, monkeypatch) -> None: + """build_task_ui_state 同一次构建只查 Gate 摘要一次,禁止再经 resolve 二次查库。""" + with app.app_context(): + calls = {'n': 0} + + def _fake_gate(_task): + calls['n'] += 1 + return { + 'current_gate_code': 'inventory_sufficiency', + 'status': 'blocked', + 'lifecycle_stage': 'fulfillment_prep', + 'current_blocking_gate': { + 'gate_code': 'inventory_sufficiency', + 'status': 'blocked_manual', + }, + 'primary_action': None, + 'action_presentation': [], + } + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + _fake_gate, + ) + task = ShippingOrderTask(task_no="OT-UI-GATE-ONCE", user_id=1, source_type="direct_pdf") + state = build_task_ui_state(task) + assert calls['n'] == 1 + assert state['lifecycle_stage'] == 'fulfillment_prep' + + +def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None: + """Gate artifact_generation 投影 export_ready 时进入工作台;未验证 Artifact 不得授权下载。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-EXPORT", source_type="manual", - export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", + ) + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda _task: { + 'current_gate_code': 'artifact_generation', + 'status': 'waiting_human', + 'lifecycle_stage': 'freight_upload', + 'current_blocking_gate': { + 'gate_code': 'artifact_generation', + 'status': 'blocked_manual', + }, + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.resolve_task_export_download', + lambda _task: None, ) state = build_task_ui_state(task) - assert state["checkpoint"]["code"] == CP_EXPORT_READY - assert state["checkpoint_kind"] == "wait_manual_upload" + assert state["position"] == POSITION_EXPORT_READY + # Gate freight_upload + waiting_human → wait_manual_upload + assert state["user_mode"] == "wait_manual_upload" assert state["summary"]["entry_surface"] == "task_workbench" assert state["summary"].get("pause_reason_code") == "wait_manual_upload" - assert "登记凭据" in str(state["summary"].get("pause_reason") or "") + assert "货代平台上传" in str(state["summary"].get("pause_reason") or "") button_ids = [ item.get("code") for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] if item ] - # 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。 + # 关键断言:没有可验证 Artifact 时不得生成下载按钮。 assert "download_excel" not in button_ids assert "mark_manual_uploaded" not in button_ids @@ -303,8 +387,6 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa task = ShippingNotice( task_no="SN-UI-RESOLVED-EXPORT", source_type="manual", - export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", ) monkeypatch.setattr( 'app.services.shipping_notice.ui_state.resolve_task_export_download', @@ -373,18 +455,27 @@ def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatc def test_stp_facts_candidates_frozen_projected(app) -> None: """多候选冻结任务须投影 stp_facts.frozen_candidate_codes。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-FROZEN", - source_type="manual", - inventory_source_status="candidates_frozen", - inventory_source_method="stp_build_freeze", - step_payload_json={ - "line_inventory_candidates": { - "source_codes": ["DBS_DUB", "DBS_RTM"], - "frozen_at": "build", - }, - }, + task = ShippingOrderTask( + task_no="OT-UI-STP-FROZEN", user_id=1, source_type="direct_pdf", ) + db.session.add(task) + db.session.flush() + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add_all([ + ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code=code, candidate_order=index, + ) + for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1) + ]) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.commit() state = build_task_ui_state(task) facts = state["summary"]["stp_facts"] assert facts["inventory_source_status"] == "candidates_frozen" @@ -393,33 +484,37 @@ def test_stp_facts_candidates_frozen_projected(app) -> None: def test_stp_facts_projects_line_resolutions(app) -> None: - """stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。""" + """stp_facts 须从当前行级 Match 投影逐行库存证据,不能读取 OT payload。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-LINES", - source_type="manual", - match_status="fulfillable", - inventory_source_status="resolved", - inventory_source_code="DBS_DUB", - inventory_source_method="stp_line_match", - step_payload_json={ - "line_inventory_resolutions": [ - { - "line_index": 0, - "disposition": "ok", - "effective_reservation_id": "3000092917", - "part_number": "PN-1", - "resolved_inventory_source_code": "DBS_DUB", - "inventory_file_no": "INV-1", - "inventory_row_ref": { - "reservation_id": "3000092917", - "part_number": "PN-1", - "source_code": "DBS_DUB", - }, - }, - ], - }, + user = User(username='ui-stp-lines', email='ui-stp-lines@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask( + task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching', ) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=3, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, line_no=1, + reservation_id='3000092917', part_number='PN-1', qty='10', field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, + match_result='matched', inventory_status='ready', required_qty='10', available_qty='10', + matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1', + inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True, + )) + db.session.commit() + state = build_task_ui_state(task, include_stage_context=True) rows = state["summary"]["stp_facts"]["line_resolutions"] assert rows[0]["effective_reservation_id"] == "3000092917" @@ -428,39 +523,59 @@ def test_stp_facts_projects_line_resolutions(app) -> None: assert rows[0]["inventory_file_no"] == "INV-1" stage_context = state["stage_context"] assert stage_context["preparation"]["status"] == "ready" - assert stage_context["preparation"]["lines"] == [{ - "line_key": None, - "line_no": "1", - "line_no_source": "sequence", - "reservation_id": "3000092917", - "part_number": "PN-1", - "required_qty": None, - "available_qty": None, - "shortage_qty": None, - "source_code": "DBS_DUB", - "status": "ok", - }] + # §1.5:行级字段是展示契约核心,但不锁全 dict(随 §1.5 字段扩展)。断言关键现存字段 + 新增明细按钮字段。 + line = stage_context["preparation"]["lines"][0] + assert line["snapshot_line_id"] == snapshot_line.id + assert line["line_no"] == 1 + assert line["customer_po_line_no"] is None + assert line["reservation_id"] == "3000092917" + assert line["part_number"] == "PN-1" + assert line["required_qty"] == "10" + assert line["available_qty"] == "10" + assert line["shortage_qty"] == "0" + assert line["source_code"] == "DBS_DUB" + # §1.5 status 现取 user_line_status(展示契约),不再是裸 match_result 的 disposition。 + assert line["status"] == "inventory_matched" + assert line["source_ambiguous"] is False + assert line["source_candidates"] == [] + assert line["can_fulfill_complete_line"] is True + # §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮; + # line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。 + assert line["inventory_file_no"] == "INV-1" + assert line["is_shortage"] is False + assert line["inventory_allowed_actions"] == [] + assert line["line_allowed_actions"] == ["close_unfulfillable"] + assert line["user_line_status"] == "inventory_matched" # 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。 assert stage_context["upload"]["outcome"] == "not_started" def test_stage_context_prefers_current_structured_inventory_match(app) -> None: - """通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。""" + """通知准备必须从 Snapshot 与行级 Match 投影,不依赖 OT JSON 或 NoticeLine。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STRUCTURED-MATCH", - source_type="manual", - match_status="partial", - inventory_source_code="DBS_DUB", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", - line_results_json=[], - ) + user = User(username='ui-structured-match', email='ui-structured-match@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching') db.session.add(task) db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, line_no=1, + reservation_id='RSV-1', part_number='PN-1', qty='10', field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", @@ -477,48 +592,240 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None: preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] assert preparation["has_match_result"] is True - assert preparation["lines"] == [{ - "line_key": "line-1", - "line_no": "1", - "line_no_source": "sequence", - "reservation_id": "RSV-1", - "part_number": "PN-1", - "required_qty": "10", - "available_qty": "7", - "shortage_qty": "3", - "source_code": "DBS_DUB", - "status": "matched", - }] + line = preparation["lines"][0] + assert line["snapshot_line_id"] == snapshot_line.id + assert line["line_no"] == 1 + assert line["customer_po_line_no"] is None + assert line["reservation_id"] == "RSV-1" + assert line["part_number"] == "PN-1" + assert line["required_qty"] == "10" + assert line["available_qty"] == "7" + assert line["shortage_qty"] == "3" + assert line["source_code"] == "DBS_DUB" + assert line["status"] == "shortage" + assert line["source_ambiguous"] is False + assert line["source_candidates"] == [] + # §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。 + assert line["is_shortage"] is True + assert line["user_line_status"] == "shortage" + assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"} + assert "retry_inventory_preparation" in line["inventory_allowed_actions"] +def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None: + """库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。 + + 与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。 + """ + from app.models import ShippingTaskInventoryRpaAttempt + + with app.app_context(): + user = User(username='ui-rpa-running', email='ui-rpa-running@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='inventory_matching') + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, line_no=1, + reservation_id='RSV-RPA', part_number='PN-RPA', qty='10', field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line.id, + line_no=1, + line_index=0, + match_result='matched', + inventory_status='ready', + required_qty='10', + available_qty='7', + matched_qty='7', + shortage_qty='3', + reservation_id='RSV-RPA', + part_number='PN-RPA', + inventory_source_code='DBS_DUB', + is_current=True, + )) + db.session.add(ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, + source_code='DBS_DUB', + attempt_no=1, + source_run_no='PSR-UI-RPA-1', + status='running', + )) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + line = preparation['lines'][0] + # 关键断言:RPA 运行中必须清空库存动作,前端 Bot 不得渲染/触发。 + assert line['user_line_status'] == 'acquiring_inventory' + assert line['inventory_allowed_actions'] == [] + + +def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None: + """行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。""" + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [ + {'source_code': 'src_a', 'display_name': 'Source A'}, + {'source_code': 'SRC_B', 'display_name': ''}, + ], + ) + with app.app_context(): + user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching') + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=2, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={}) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0, + match_result='source_conflict', inventory_status='source_conflict', + allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + assert preparation['lines'][0]['source_ambiguous'] is True + assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B'] + assert preparation['lines'][0]['source_code'] is None + assert preparation['source_locked'] is False + # 关键断言:行级覆写下拉依赖 preparation.source_options;编码统一大写。 + assert preparation['source_options'] == [ + {'source_code': 'SRC_A', 'display_name': 'Source A'}, + {'source_code': 'SRC_B', 'display_name': 'SRC_B'}, + ] + + +def test_stage_context_projects_selected_source_without_backfilling_match_source(app) -> None: + """CandidateSet 单源只填 selected_source_code,禁止回填 Match 的 source_code。""" + with app.app_context(): + task, line = _frozen_task_with_line( + task_no='OT-UI-SELECTED-SOURCE', + reservation_id='RSV-SEL', + part_number='PN-SEL', + qty='2', + ) + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='b' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1, + )) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + row = preparation['lines'][0] + # 关键断言:取数目标与匹配结论分字段;未匹配时 source_code 必须为空。 + assert row['snapshot_line_id'] == line.id + assert row['selected_source_code'] == 'DSV360_AWSSG' + assert row['source_code'] is None + assert row['source_ambiguous'] is False + + +def test_stage_context_notice_resolves_ot_match_and_selected_source(app) -> None: + """Notice 详情入口须经 order_task_id→OT 读 Snapshot/Match/Candidate,禁止用 Notice.id。""" + with app.app_context(): + # 垫偏 OT.id,避免空库 Notice.id==OT.id 碰巧绿。 + for index in range(3): + db.session.add(ShippingOrderTask( + task_no=f'OT-UI-SPACER-{index}', user_id=1, source_type='direct_pdf', + )) + db.session.flush() + task, line = _frozen_task_with_line( + task_no='OT-UI-NOTICE-RESOLVE', + reservation_id='RSV-NOTICE', + part_number='PN-NOTICE', + qty='3', + ) + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1, + )) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0, + match_result='matched', inventory_status='ready', required_qty='3', available_qty='3', + matched_qty='3', shortage_qty='0', reservation_id='RSV-NOTICE', part_number='PN-NOTICE', + inventory_source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True, + )) + notice = ShippingNotice( + task_no='SN-UI-NOTICE-RESOLVE', + source_type='manual', + user_id=1, + order_task_id=task.id, + ) + db.session.add(notice) + db.session.commit() + + assert int(notice.id) != int(task.id) + preparation = build_task_ui_state(notice, include_stage_context=True)['stage_context']['preparation'] + row = preparation['lines'][0] + # 关键断言:SN 入口仍投影 OT 上的匹配正式源与取数目标。 + assert preparation['frozen_order']['task_no'] == task.task_no + assert preparation['frozen_order']['snapshot_id'] == task.order_snapshot_id + assert row['source_code'] == 'DSV360_AWSSG' + assert row['selected_source_code'] == 'DSV360_AWSSG' + assert preparation['has_match_result'] is True + def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None: """库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。""" with app.app_context(): - task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual") - db.session.add(task) - db.session.flush() - db.session.add(ShippingNoticeLine( - notice_id=task.id, - position=0, - line_key="line-frozen-1", + task, line = _frozen_task_with_line( + task_no="OT-UI-FROZEN-ORDER", reservation_id="RSV-FROZEN", part_number="PN-FROZEN", - required_qty="6", - )) + qty="6", + ) db.session.commit() preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] # 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。 assert preparation["frozen_order_lines"] == [{ - "line_key": "line-frozen-1", - "line_no": "1", - "line_no_source": "sequence", + "snapshot_line_id": line.id, + "line_no": 1, "reservation_id": "RSV-FROZEN", "part_number": "PN-FROZEN", "required_qty": "6.00000000", }] - assert preparation["lines"] == [] + assert preparation["lines"][0]["snapshot_line_id"] == line.id + assert preparation["lines"][0]["line_no"] == 1 + assert preparation["lines"][0]["reservation_id"] == "RSV-FROZEN" + assert preparation["lines"][0]["part_number"] == "PN-FROZEN" + assert preparation["lines"][0]["available_qty"] is None assert preparation["has_match_result"] is False @@ -530,7 +837,9 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat with app.app_context(): inventory_path = tmp_path / "task-inventory.xlsx" inventory_path.write_bytes(b"inventory-content") - task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual") + task = ShippingOrderTask( + task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf", + ) inventory_file = ShippingInventoryFile( inventory_file_no="SIF-UI-DOWNLOAD", storage_path=str(inventory_path), @@ -568,8 +877,8 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm db.session.flush() inventory_path = tmp_path / 'inventory-download.xlsx' inventory_path.write_bytes(b'inventory-download-content') - task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual') - no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual') + task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf') + no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf') inventory_file = ShippingInventoryFile( inventory_file_no='SIF-INVENTORY-DOWNLOAD-API', storage_path=str(inventory_path), @@ -589,16 +898,16 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'} # 关键断言:活动 link 文件可下载,并以服务端原始内容响应。 - success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers) + success = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers) assert success.status_code == 200 assert success.data == b'inventory-download-content' assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '') # 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。 - missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers) + missing = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers) assert missing.status_code == 404 assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND' - forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers) + forbidden = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers) assert forbidden.status_code == 404 @@ -614,7 +923,9 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, denied_path = tmp_path / 'dbs.xlsx' allowed_path.write_bytes(b'crane-content') denied_path.write_bytes(b'dbs-content') - task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual') + task, snapshot_line = _frozen_task_with_line( + task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, + ) allowed_file = ShippingInventoryFile( inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path), source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready', @@ -626,7 +937,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, db.session.add_all([task, allowed_file, denied_file]) db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( - task_id=task.id, line_key='line-crane', line_index=0, + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no, inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True, )) @@ -634,7 +945,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'} allowed = client.get( - '/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE', + '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE', headers=headers, ) assert allowed.status_code == 200 @@ -642,41 +953,33 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '') denied = client.get( - '/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS', + '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS', headers=headers, ) assert denied.status_code == 404 def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None: - """结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。""" + """行级 Match 的事实字段应补齐冻结订单行的库存展示。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STRUCTURED-PARTIAL", - source_type="manual", - match_status="partial", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", - step_payload_json={"line_inventory_resolutions": [{ - "line_index": 0, - "line_key": "line-1", - "effective_reservation_id": "RSV-LEGACY", - "part_number": "PN-LEGACY", - "inventory_file_no": "INV-1", - "disposition": "ok", - }]}, + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-STRUCTURED-PARTIAL", + reservation_id="RSV-LEGACY", + part_number="PN-LEGACY", + qty="10", ) - db.session.add(task) - db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", required_qty="10", available_qty="8", shortage_qty="2", + reservation_id="RSV-LEGACY", + part_number="PN-LEGACY", inventory_source_code="DBS_DUB", is_current=True, )) @@ -696,18 +999,16 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch from app.services.shipping_notice import query_service with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-DETAIL-CONTEXT", - source_type="manual", - match_status="fulfillable", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-DETAIL-CONTEXT", + reservation_id="RSV-DETAIL", + part_number="PN-DETAIL", + qty="2", ) - db.session.add(task) - db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", @@ -725,36 +1026,244 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task) monkeypatch.setattr(api, '_ok', lambda data: data) - payload = api.workspace_shipping_task_detail(task.task_no) + # 视图函数经 request.args 读取 view 参数,必须包一层请求上下文(直接调用无 request)。 + with app.test_request_context(): + payload = api.workspace_shipping_task_detail(task.task_no) preparation = payload['ui_state']['stage_context']['preparation'] assert preparation['has_match_result'] is True assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL' def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None: - """历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。""" - from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW - + """行级多源冲突应覆盖通知准备的暂停原因。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-MULTI", - review_status=RS_SHORTAGE_REVIEW, - pending_human_reason="shortage", - source_type="manual", - match_status="fulfillable", - inventory_source_status="candidates_frozen", - inventory_source_method="stp_line_match", - step_payload_json={ - "multi_source_excel_block": True, - "resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"], - "line_inventory_resolutions": [ - {"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"}, - {"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"}, - ], - }, + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1", ) + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, + match_result='source_conflict', inventory_status='source_conflict', + allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True, + )) + db.session.commit() state = build_task_ui_state(task) summary = state["summary"] assert summary["pause_reason_code"] == "multi_source_excel_block" assert summary["stp_facts"]["multi_source_excel_block"] is True assert summary["entry_surface"] == "task_workbench" + + +def test_preparation_editable_present_for_live_formal_task(monkeypatch): + """活任务(active/blocked/空值)判定可操作;作废/归档/删除/待作废/取消视图不可操作。 + + 按 ShippingNotice 真实 lifecycle_status 值域逐值覆盖(不用 WorkflowItem 的 + {'closed', 'cancelled'} 终态集);排除集见 ui_state 的 + _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES 注释。 + """ + class FakeTask: + id = 1 + task_no = 'SN-LIVE-1' + order_task_no = 'SN-LIVE-1' + # 真实值域:ShippingNotice 无 in_progress 写入方,活任务为 active。 + lifecycle_status = 'active' + export_file_path = '' + order_snapshot_id = None + inventory_source_code = None + match_status = None + + # 直接依赖 _build_stage_context 内部较重;此处最小断言 editable 键存在且为 bool 语义。 + # 实现时若 _build_stage_context 依赖过多,改为抽纯谓词 _preparation_editable(task) 单测。 + from app.services.shipping_notice.ui_state import _preparation_editable + + # 关键断言:活任务(active)判定可操作(任务级 editable=True 语义)。 + assert _preparation_editable(FakeTask()) is True + + class BlockedTask(FakeTask): + lifecycle_status = 'blocked' + + # 关键断言:blocked 是新任务暂堵态(task_supersession_service.py),不算作废/历史 + # 视图,保持可编辑——与 case 级 edit_formal_task 镜像语义一致;闸口语义由 + # pending_human_reason 等机制表达,不在此谓词收紧。 + assert _preparation_editable(BlockedTask()) is True + + class NoStatusTask(FakeTask): + lifecycle_status = None + + # 边界断言:空/缺失 lifecycle_status 不得误判为终态,默认可操作。 + assert _preparation_editable(NoStatusTask()) is True + + # 关键断言:每个非可操作生命周期必须置 False,供 Prep 波次出单门控拦截—— + # 终态 voided/archived/deleted;co8 只读语义 pending_void + # (freight_cancellation_service.py:154);兼容双拼 cancelled/canceled。 + for status in ('voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled'): + class NonEditableTask(FakeTask): + pass + NonEditableTask.lifecycle_status = status + # 意图:该值域命中 _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES → editable=False。 + assert _preparation_editable(NonEditableTask()) is False + + class NoisyStatusTask(FakeTask): + lifecycle_status = ' Voided ' + + # 边界断言:strip/lower 归一化必须保留(防终态因空白/大小写漏判为可编辑)。 + assert _preparation_editable(NoisyStatusTask()) is False + + +def test_stage_context_line_actions_without_match_rows(app) -> None: + """正式 OT 无匹配行时,preparation.lines 仍须下发明细库存重试动作。 + + 断言:has_formal_ot 不得用 current_match_rows 判定;无 match 时 fact 兜底 preparing, + inventory_allowed_actions 含 retry_inventory_preparation。 + """ + with app.app_context(): + user = User(username='ui-no-match-actions', email='ui-no-match-actions@example.com') + db.session.add(user) + db.session.flush() + task, _line = _frozen_task_with_line( + task_no='OT-UI-NO-MATCH-ACTIONS', + user_id=user.id, + reservation_id='RSV-NM-1', + part_number='PN-NM-1', + qty='4', + ) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + assert preparation["has_match_result"] is False + assert len(preparation["lines"]) == 1 + line = preparation["lines"][0] + # 关键断言:无 Match 行时明细仍可点「重试库存准备」,不得因 has_formal_ot=False 空动作。 + assert "retry_inventory_preparation" in line["inventory_allowed_actions"] + assert "close_unfulfillable" in line["line_allowed_actions"] + + +def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None: + """[断言] preparation 携带任务级 editable(active=True / voided=False); + 行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。""" + with app.app_context(): + task, first_line = _frozen_task_with_line( + task_no="OT-UI-PREP-EDITABLE", + reservation_id="RSV-PO-1", part_number="PN-PO-1", qty="5", + field_values_json={"customer_po_line_no": "7"}, + ) + second_line = ShippingOrderSnapshotLine( + snapshot_id=first_line.snapshot_id, position=1, line_no=2, + reservation_id="RSV-PO-2", part_number="PN-PO-2", qty="3", field_values_json={}, + ) + db.session.add(second_line) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + # 关键断言:活任务(默认 active)必须下发任务级可操作标志 True。 + assert preparation["editable"] is True + # 未绑定 Schema 字段 ID 时,冻结档不会把 field_code 当成正式字段事实。 + assert preparation["lines"][0]["customer_po_line_no"] is None + # 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。 + assert preparation["lines"][1]["customer_po_line_no"] is None + + +def test_stage_context_preparation_projects_shortage_release_template_fields(app) -> None: + """短缺行必须按库存源发货模板投影人工补录字段,禁止 fail-closed 空列表。""" + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryField, + ShippingInventorySource, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ) + + with app.app_context(): + location = ShippingInventoryField.query.filter_by(field_code='location').one() + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id)) + assert template is not None + template.definition_json = { + 'mappings': [ + { + 'row_mode': 'line', + 'source_kind': 'inventory_field', + 'source_key': str(location.id), + }, + ], + } + + user = User(username='ui-release-fields', email='ui-release-fields@example.com') + db.session.add(user) + db.session.flush() + schema = ShippingOrderSchema(schema_code='UI_RELEASE_FIELDS', display_name='UI Release Fields') + db.session.add(schema) + db.session.flush() + schema_version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + definition_json={'fields': []}, + ) + db.session.add(schema_version) + db.session.flush() + + task = ShippingOrderTask( + task_no='OT-UI-RELEASE-FIELDS', + user_id=user.id, + stage='inventory_matching', + ) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=schema_version.id, + order_data_version=1, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + reservation_id='RSV-RELEASE', + part_number='PN-RELEASE', + qty='10', + field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() + # 无库存快照时模板库存字段全部人工补录;源码必须能解析到 published 发货模板。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line.id, + line_no=1, + line_index=0, + match_result='not_found', + inventory_status='ready', + required_qty='10', + available_qty='0', + matched_qty='0', + shortage_qty='10', + reservation_id='RSV-RELEASE', + part_number='PN-RELEASE', + inventory_source_code='DSV360_AWSDU', + inventory_snapshot_id=None, + is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + line = preparation['lines'][0] + + assert line['is_shortage'] is True + assert line['release_field_resolution_error'] is None + assert line['release_required_fields'] == [ + {'field_id': str(location.id), 'display_name': '库位'}, + ] + assert line['release_template_fields'] == [ + { + 'field_id': str(location.id), + 'display_name': '库位', + 'value': None, + 'value_source': 'manual_required', + 'requires_manual': True, + }, + ] diff --git a/backend/tests/test_shipping_notice_user_facing_status.py b/backend/tests/test_shipping_notice_user_facing_status.py index f677d05b..41f8bca0 100644 --- a/backend/tests/test_shipping_notice_user_facing_status.py +++ b/backend/tests/test_shipping_notice_user_facing_status.py @@ -2,11 +2,11 @@ tests/test_shipping_notice_user_facing_status.py 用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。 -依赖:pytest、ShippingNotice 模型、user_facing_status。 -逻辑:构造最小 ShippingNotice 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。 +依赖:pytest、ShippingOrderTask 模型、user_facing_status。 +逻辑:构造最小 ShippingOrderTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。 """ -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.user_facing_status import user_facing_task_stage @@ -15,10 +15,12 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None: """ rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。 - 核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。 + 核心逻辑:pending_human_reason 是属于建单前 OT(ShippingOrderTask)的流程阻断事实; + 正式 Notice 只承载单据。构造 rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。 """ - task = ShippingNotice( - task_no="SN-TEST-RPA-PENDING", + task = ShippingOrderTask( + task_no="OT-TEST-RPA-PENDING", + user_id=1, pending_human_reason=PH_RPA_PENDING, ) diff --git a/backend/tests/test_shipping_order_auto_freeze_policy.py b/backend/tests/test_shipping_order_auto_freeze_policy.py index 140e126a..59430b35 100644 --- a/backend/tests/test_shipping_order_auto_freeze_policy.py +++ b/backend/tests/test_shipping_order_auto_freeze_policy.py @@ -22,8 +22,9 @@ from app.models import ( Job, ShippingDocumentProfileAutoFreezeQualification, ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, ShippingOrderDocumentProfile, - ShippingOrderCustomerMatch, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderRouteDecision, @@ -52,7 +53,7 @@ def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrde def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None: - """为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。""" + """为 Run 构造已确认的客户识别结果,供范围门禁测试复用。""" extraction = ShippingOrderExtraction( run_id=run_id, intake_id=intake_id, @@ -63,18 +64,20 @@ def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int ) 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(), + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-AF-{run_id}-{customer.id}', intake_id=int(intake_id), primary_document_id=1, + candidate_key=f'auto-freeze-{run_id}-{customer.id}', order_extraction_id=extraction.id, + candidate_status='accepted', order_extraction_run_id=int(run_id), + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=int(intake_id), resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, identity_rule_set_checksum='a' * 64, + top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id, + confirmation_method='manual', confirmed_at=datetime.utcnow(), )) diff --git a/backend/tests/test_shipping_order_build_eligibility.py b/backend/tests/test_shipping_order_build_eligibility.py index c179d662..434d3bfb 100644 --- a/backend/tests/test_shipping_order_build_eligibility.py +++ b/backend/tests/test_shipping_order_build_eligibility.py @@ -12,7 +12,6 @@ from __future__ import annotations from app.extensions import db from app.models import ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition from app.services.shipping_notice.order_build_eligibility_service import ( - apply_manual_inventory_candidates, assess_order_build_eligibility, project_line_inventory_candidates, ) @@ -210,42 +209,8 @@ def test_unavailable_rule_candidates_are_filtered(app): assert routing['can_build'] is True -def test_manual_decision_not_silently_overwritten_by_rule_suggestion(app): - """人工决定优先;规则建议可并存但不覆盖有效候选。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - db.session.add(_rule( - code='FORCE_OTHER', priority=100, sources=['DSV360_AWSDU'], - conditions=[(field_ids['reservation_id'], 'is_not_empty', None)], - )) - db.session.commit() - line_meta = { - 'line_key': 'line-1', - 'inventory_routing': { - 'selection_mode': 'manual', - 'candidate_inventory_source_codes': ['DSV360_AWSDU'], - 'manual_reason': 'planner confirmed', - 'suggestion_pending': True, - 'rule_suggestion': {'source_codes': ['DSV360_AWSDU']}, - }, - } - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:有效候选仍是人工值;selection_mode 保持 manual。 - assert routing['selection_mode'] == 'manual' - assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] - assert routing['can_build'] is True - - def test_zero_candidates_blocks_build(app): - """无路由命中时 can_build=False 且 block_reason=no_inventory_source_candidates。""" + """无路由命中时 can_build=True(库存路由不阻断 OT 创建),但行级仍记录 block_reason。""" with app.app_context(): field_ids = _published_line_fields() fields = _schema_fields_map(field_ids) @@ -260,14 +225,14 @@ def test_zero_candidates_blocks_build(app): line_metas=[{'line_key': 'line-1'}], ) - # 关键断言:零候选阻断建单并给出稳定原因码。 - assert result['can_build'] is False + # 关键断言:库存路由属可人工修正事实,不阻断正式 OT 创建;行级仍给出稳定原因码。 + assert result['can_build'] is True assert result['line_projections'][0]['block_reason'] == 'no_inventory_source_candidates' assert any(item['code'] == 'no_inventory_source_candidates' for item in result['issues']) def test_require_manual_review_action_blocks_build(app): - """require_manual_review 规则将 status=conflicted 且 can_build=False。""" + """require_manual_review 规则将 status=conflicted;can_build=True(库存路由不阻断),行级保留 block_reason。""" with app.app_context(): field_ids = _published_line_fields() fields = _schema_fields_map(field_ids) @@ -287,8 +252,8 @@ def test_require_manual_review_action_blocks_build(app): line_metas=[{'line_key': 'line-1'}], ) - # 关键断言:强制人工复核阻断建单。 - assert result['can_build'] is False + # 关键断言:强制人工复核属可人工修正事实,不阻断正式 OT 创建;行级仍路由到 conflicted。 + assert result['can_build'] is True assert result['line_projections'][0]['routing_status'] == 'conflicted' assert result['line_projections'][0]['block_reason'] == 'require_manual_review' @@ -323,57 +288,6 @@ def test_header_only_reservation_fills_effective_reservation(app): assert result['can_build'] is True -def test_manual_selection_with_reason_and_enabled_source_allows_build(app): - """人工选择已启用库存源并填写原因时 can_build=True。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - line_meta: dict = {'line_key': 'line-1'} - apply_manual_inventory_candidates( - line_meta=line_meta, - source_codes=['DSV360_AWSDU'], - reason='客户邮件指定 Dublin 库存池', - ) - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:人工覆盖优先于规则零候选。 - assert routing['selection_mode'] == 'manual' - assert routing['can_build'] is True - assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] - - -def test_manual_selection_without_reason_is_blocked(app): - """人工选择未填写原因时 can_build=False 且 block_reason=manual_inventory_source_reason_required。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - line_meta = { - 'line_key': 'line-1', - 'inventory_routing': { - 'selection_mode': 'manual', - 'candidate_inventory_source_codes': ['DSV360_AWSDU'], - 'manual_reason': '', - }, - } - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:缺原因不得放行建单。 - assert routing['can_build'] is False - assert routing['block_reason'] == 'manual_inventory_source_reason_required' - - def test_auto_freeze_reasons_own_single_user_blocking_finding(app, monkeypatch): """资格失败只产生一条用户阻断 Finding,不平行产生多个 auto_build_gate_*。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_order_customer_matching.py b/backend/tests/test_shipping_order_customer_matching.py deleted file mode 100644 index 3ffacbc4..00000000 --- a/backend/tests/test_shipping_order_customer_matching.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -backend/tests/test_shipping_order_customer_matching.py - -用途:验证订单 Bill-to / Ship-to 与货代客户主数据的角色化匹配。 -依赖:订单 Schema 模型、客户主数据模型、order_customer_matching 服务。 -逻辑:覆盖标准名称、审核别名、歧义、未命中和人工确认快照。 -""" - -from app import db -from app.models import ( - ShippingCustomer, - ShippingCustomerExternalRef, - ShippingCustomerIdentifier, - ShippingCustomerSite, - ShippingCustomerSiteIdentifier, - ShippingOrderExtraction, - ShippingOrderSchema, - ShippingOrderSchemaVersion, -) -from app.services.shipping_notice.customer_normalization import normalize_customer_name -from app.services.shipping_notice.order_customer_matching import ( - confirm_order_customer_match, - refresh_order_customer_matches, -) - - -def _extraction() -> ShippingOrderExtraction: - """构造角色化客户匹配测试所需的最小订单解析记录。""" - schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单字段') - db.session.add(schema) - db.session.flush() - version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='draft', definition_json={}) - db.session.add(version) - db.session.flush() - extraction = ShippingOrderExtraction( - schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', - ) - db.session.add(extraction) - db.session.flush() - return extraction - - -def test_order_customer_matching_resolves_roles_and_short_codes(app): - """Bill-to/Ship-to 应可命中不同客户,简称必须来自主数据。""" - with app.app_context(): - bill_to = ShippingCustomer(standard_name='Amazon Web Services', short_code='AWS') - db.session.add(bill_to) - db.session.flush() - ship_to = ShippingCustomerSite( - customer_id=bill_to.id, site_name='Amazon Dublin DC', site_code='DUB01', status='active', - ) - db.session.add(ship_to) - db.session.flush() - db.session.add(ShippingCustomerSiteIdentifier( - site_id=ship_to.id, - identifier_type='name_alias', source_system='', - raw_value='AWS Dublin DC', - normalized_value=normalize_customer_name('AWS Dublin DC'), - status='approved', - )) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'bill_to_customer': 'Amazon Web Services', - 'ship_to_customer': 'AWS Dublin DC', - }) - - by_role = {item['role']: item for item in results} - assert by_role['bill_to']['customer_id'] == bill_to.id - assert by_role['bill_to']['short_code'] == 'AWS' - assert by_role['ship_to']['customer_id'] == bill_to.id - assert by_role['ship_to']['site_id'] == ship_to.id - assert by_role['ship_to']['short_code'] == 'AWS' - - -def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app): - """同一别名对应多个客户时不得自动选择,人工确认后锁定标准名称和简称。""" - with app.app_context(): - first = ShippingCustomer(standard_name='Customer One', short_code='ONE') - second = ShippingCustomer(standard_name='Customer Two', short_code='TWO') - db.session.add_all([first, second]) - db.session.flush() - normalized = normalize_customer_name('Shared Alias') - db.session.add_all([ - ShippingCustomerIdentifier( - customer_id=first.id, identifier_type='name_alias', raw_value='Shared Alias', - normalized_value=normalized, status='approved', - ), - ShippingCustomerIdentifier( - customer_id=second.id, identifier_type='name_alias', raw_value='Shared Alias', - normalized_value=normalized, status='approved', - ), - ]) - extraction = _extraction() - results = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Shared Alias'}) - bill_to = next(item for item in results if item['role'] == 'bill_to') - assert bill_to['status'] == 'ambiguous' - assert bill_to['customer_id'] is None - assert len(bill_to['candidates']) == 2 - - confirmed = confirm_order_customer_match( - extraction.id, role='bill_to', customer_id=second.id, actor_id=None, reason='业务复核确认订购客户', - ) - assert confirmed['status'] == 'confirmed' - assert confirmed['standard_name'] == 'Customer Two' - assert confirmed['short_code'] == 'TWO' - assert confirmed['confirmation_reason'] == '业务复核确认订购客户' - assert len(confirmed['identity_fingerprint']) == 64 - assert confirmed['identity_rule_version'] == 'order-customer-fingerprint.v1' - - -def test_order_customer_fingerprint_is_stable_and_confirmation_requires_reason(app): - """相同原文及规则必须得到稳定指纹,人工绑定不能缺失可审计理由。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Fingerprint Customer', short_code='FPC') - db.session.add(customer) - extraction = _extraction() - first = refresh_order_customer_matches(extraction, {'bill_to_customer': ' Fingerprint Customer '}) - fingerprint = next(item for item in first if item['role'] == 'bill_to')['identity_fingerprint'] - second = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Fingerprint Customer'}) - assert next(item for item in second if item['role'] == 'bill_to')['identity_fingerprint'] == fingerprint - try: - confirm_order_customer_match(extraction.id, role='bill_to', customer_id=customer.id, actor_id=None, reason='') - except Exception as error: - assert getattr(error, 'code', None) == 'SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED' - else: - raise AssertionError('confirmation without reason must be blocked') - - -def test_order_customer_matching_prefers_external_customer_and_site_codes(app): - """外部客户编码和 Ship-to Code 应优先于不可靠的原文名称。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Canonical Customer', short_code='CAN') - db.session.add(customer) - db.session.flush() - db.session.add(ShippingCustomerExternalRef( - customer_id=customer.id, source_system='ERP', legacy_customer_key='C001', - )) - site = ShippingCustomerSite( - customer_id=customer.id, site_name='Dublin Site', site_code='DUB01', status='active', - ) - db.session.add(site) - db.session.flush() - db.session.add(ShippingCustomerSiteIdentifier( - site_id=site.id, identifier_type='external_code', source_system='ERP', - raw_value='DUB-EXT', normalized_value='DUB-EXT', status='approved', - )) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'bill_to_customer': 'Wrong Name', 'bill_to_customer_code': 'c001', 'bill_to_source_system': 'erp', - 'ship_to_customer': 'Wrong Site', 'ship_to_code': 'dub-ext', 'ship_to_source_system': 'erp', - }) - - by_role = {item['role']: item for item in results} - assert by_role['bill_to']['customer_id'] == customer.id - assert by_role['bill_to']['resolution_method'] == 'external_customer_code' - assert by_role['ship_to']['site_id'] == site.id - assert by_role['ship_to']['resolution_method'] == 'external_site_code' - - -def test_ship_to_matching_falls_back_to_name_when_external_code_misses(app): - """Ship-to 外部编码未命中时应继续使用站点标准名称,避免有效站点被错误判为未匹配。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Fallback Customer', short_code='FBC') - db.session.add(customer) - db.session.flush() - site = ShippingCustomerSite( - customer_id=customer.id, site_name='Fallback Delivery Site', site_code='FBS01', status='active', - ) - db.session.add(site) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'ship_to_customer': 'Fallback Delivery Site', - 'ship_to_code': 'UNKNOWN-CODE', - 'ship_to_source_system': 'ERP', - }) - - ship_to = next(item for item in results if item['role'] == 'ship_to') - assert ship_to['site_id'] == site.id - assert ship_to['resolution_method'] == 'site_name' diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index a124d7c6..0cec410e 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -660,8 +660,25 @@ def _bind_ready_profile_sample( table_id: str = 'sample-table', content_hash: str = 's' * 64, filename: str = 'sample.pdf', + physical_page_count: int = 1, + include_top_level_pages: bool = True, ) -> ShippingOrderDocumentProfileSample: - """为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。""" + """ + 为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。 + + Args: + profile_id: 绑定该样本的草稿模板主键。 + sample_role: 样本角色。 + table_id: 第一页视觉主表身份。 + content_hash: 样本文档内容哈希。 + filename: 受控样本文档名。 + physical_page_count: 原 PDF 的物理页数;坐标证据为每页保留尺寸。 + include_top_level_pages: 为 False 时模拟坐标证据外置后的持久化 Layout,不在根 payload + 重复保存页面列表。 + + Returns: + 已绑定到 Profile 的样本记录。 + """ suffix = f'{profile_id}-{str(sample_role).upper()}-{ShippingOrderDocumentProfileSample.query.count() + 1}' user = User( username=f'profile-sample-{suffix}', @@ -708,10 +725,9 @@ def _bind_ready_profile_sample( ) db.session.add(document) db.session.flush() - record_inline_layout_snapshot(document, { + snapshot = { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', - 'pages': [{'page_no': 1}], 'tables': [{ 'table_id': table_id, 'page_no': 1, @@ -719,7 +735,10 @@ def _bind_ready_profile_sample( 'html': '
ok
', }], 'coordinate_evidence': { - 'pages': {'1': {'width': 200, 'height': 100}}, + 'pages': { + str(page_no): {'width': 200, 'height': 100} + for page_no in range(1, physical_page_count + 1) + }, 'page_glyphs': {'1': [{ 'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}, }]}, @@ -728,7 +747,10 @@ def _bind_ready_profile_sample( }]}, 'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {table_id: 'pdf'}}, }, - }) + } + if include_top_level_pages: + snapshot['pages'] = [{'page_no': page_no} for page_no in range(1, physical_page_count + 1)] + record_inline_layout_snapshot(document, snapshot) db.session.commit() service.add_profile_sample( profile_id, @@ -1448,6 +1470,28 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon ).one().id == replacement['id'] +def test_profile_publish_freezes_physical_page_count_from_externalized_coordinate_evidence(app, monkeypatch): + """外置坐标证据含全部物理页时,发布冻结页数不能退化为仅有表格的页数。""" + with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None, + ) + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample( + draft['id'], + sample_role='annotation', + physical_page_count=2, + include_top_level_pages=False, + ) + + service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version']) + + frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id) + # 关键断言:第二页即使没有业务表格,仍是同一 PDF 的冻结物理页面。 + assert frozen.page_count_snapshot == 2 + + def test_clone_draft_inherits_annotation_sample_but_not_training_sample(app, monkeypatch): """从已发布模板新建草稿时,编辑器 PDF 画布可用且不会复用训练发布资格。""" with app.app_context(): @@ -1948,6 +1992,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap 'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}], + 'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}}, }) db.session.commit() document_id = document.id @@ -2055,8 +2100,8 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap assert updated['lock_version'] == draft['lock_version'] + 1 -def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(app, monkeypatch): - """页面预览只允许绑定样本,令牌限管理员/单页/单次且响应禁止缓存和暴露存储地址。""" +def test_profile_page_preview_is_bound_ttl_reusable_and_never_exposes_storage_url(app, monkeypatch): + """页面预览只允许绑定样本;PNG 令牌在 TTL 内可翻页回访,响应禁止缓存和暴露存储地址。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): schema = _schema_version() @@ -2099,11 +2144,14 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url( preview_store: dict[str, str] = {} class PreviewStore: - """模拟 Redis 的 TTL 写入和原子 GETDEL,验证预览令牌无法重放。""" + """模拟 Redis 的 TTL 写入与 GET;PNG 页令牌在过期前可重复读取以支持翻页。""" def setex(self, key, _ttl, value): preview_store[key] = value + def get(self, key): + return preview_store.get(key) + def getdel(self, key): return preview_store.pop(key, None) @@ -2130,11 +2178,13 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url( assert image.mimetype == 'image/png' assert image.headers['Cache-Control'] == 'private, no-store, max-age=0' assert b'private-bucket' not in image.data and b'internal/preview.pdf' not in image.data + # 关键断言:TTL 内再次用同一 token 拉同页必须成功,否则标注画布翻页会「画布不可用」。 replay = client.get( f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/preview-pages/1", query_string={'preview_token': grant['preview_token']}, headers=headers, ) - assert replay.status_code == 404 + assert replay.status_code == 200 + assert replay.mimetype == 'image/png' candidates = client.get( f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/preview-pages/1/text-candidates", query_string={'document_id': document_id}, headers=headers, @@ -2214,14 +2264,16 @@ def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypatch): - """开发环境允许单进程内存兜底,仍需保持一次性令牌语义。""" + """开发环境允许单进程内存兜底;PNG 令牌在 TTL 内可重复 get。""" 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.get('preview-token') == '{"page_no":1}' + assert store.get('preview-token') == '{"page_no":1}' assert store.getdel('preview-token') == '{"page_no":1}' - assert store.getdel('preview-token') is None + assert store.get('preview-token') is None def test_preview_page_region_text_reads_only_the_admin_selected_glyphs(app, monkeypatch): @@ -2377,7 +2429,8 @@ def test_profile_region_preview_excludes_configured_header_regions_from_line_row ) assert preview['rows'] == [['customer_po_line_no'], ['10']] - assert preview['source_row_indices'] == [[], [0]] + # 整页候选保留表头作为第 0 个视觉行;真实数据行的证据索引必须保持为第 1 行。 + assert preview['source_row_indices'] == [[], [1]] def test_profile_region_preview_uses_schema_field_order(app, monkeypatch): @@ -2645,6 +2698,7 @@ def test_profile_sample_api_reports_header_contamination_but_v2_can_use_independ '' '
ITEM NO 00010Part NumberQty
00020INTERNAL-236
' )}], + 'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}}, }) db.session.commit() document_id = document.id diff --git a/backend/tests/test_shipping_order_edit_window.py b/backend/tests/test_shipping_order_edit_window.py new file mode 100644 index 00000000..5d2255d1 --- /dev/null +++ b/backend/tests/test_shipping_order_edit_window.py @@ -0,0 +1,120 @@ +""" +tests/test_shipping_order_edit_window.py + +用途:确认后订单编辑窗谓词(order_edit_window_service.editable_scope,设计 D10/§3.1)契约。 +依赖:ShippingNotice/ShippingNoticeLine、order_edit_window_service.progress_workflow。 +逻辑:header=全部通知无 Export Artifact 且无活动 Attempt;行=行所属通知无 Excel 且无活动 Attempt + (未入波次行不受首单 Excel 限制)。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ShippingNotice, ShippingNoticeLine +from app.services.shipping_notice.order_edit_window_service import ( + assert_field_editable, + editable_scope, +) + + +def _make_notice(task_no: str, *, order_task_id: int | None = None) -> ShippingNotice: + """构造最小 ShippingNotice;Excel 锁定由测试 monkeypatch _notice_has_export_artifact 判定。""" + notice = ShippingNotice( + task_no=task_no, + order_task_id=order_task_id, + ) + db.session.add(notice) + db.session.flush() + return notice + + +def _make_line(notice: ShippingNotice, position: int, snapshot_line_id: int) -> None: + """行身份使用冻结快照行 id(snapshot_line_id)作为编辑窗 key。""" + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), + position=position, + line_no=position + 1, + snapshot_line_id=snapshot_line_id, + field_values_json={}, + )) + db.session.flush() + + +def test_editable_scope_fresh_order_all_editable(app, monkeypatch): + """[断言] 全新订单(无 Excel、无活动 Attempt):header 与全部行均可编辑。""" + from app.services.shipping_notice.order_edit_window_service import _notice_has_active_attempt + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False) + notice = _make_notice('SN-EW-FRESH') + _make_line(notice, 0, 1) + _make_line(notice, 1, 2) + + scope = editable_scope(notice) + assert scope['header'] is True + assert scope['lines']['1'] is True + assert scope['lines']['2'] is True + + +def test_editable_scope_header_locked_by_excel_unassigned_lines_stay_editable(app, monkeypatch): + """[断言] 首单已生成 Excel:header 锁;未入波次行仍可编辑(D10 不受首单 Excel 限制)。""" + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: True) + notice = _make_notice('SN-EW-EXCEL') + _make_line(notice, 0, 1) + _make_line(notice, 1, 2) + + scope = editable_scope(notice) + assert scope['header'] is False + assert scope['lines']['1'] is True # 未入波次行不受首单 Excel 限制 + assert scope['lines']['2'] is True + + +def test_editable_scope_busy_attempt_locks_header_and_lines(app, monkeypatch): + """[断言] 存在活动 Gate Attempt:header 与全部行均锁定(系统处理中)。""" + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False) + notice = _make_notice('SN-EW-BUSY') + _make_line(notice, 0, 1) + + scope = editable_scope(notice) + assert scope['header'] is False + assert scope['lines']['1'] is False + + +def test_assert_field_editable_delegates_scope(app): + """[断言] 保存守卫按作用域映射谓词;header/line 互不串用。""" + scope = {'header': False, 'lines': {'1': True, '2': False}} + assert assert_field_editable(scope, field={'scope': 'header'}) is False + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='1') is True + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='2') is False + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id=None) is False + + +def test_order_has_active_attempt_reflects_notice_attempts(app, monkeypatch): + """[断言] order_has_active_attempt 聚合同订单全部通知的活动 Attempt。""" + from app.services.shipping_notice.order_edit_window_service import ( + order_has_active_attempt, + ) + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True) + notice = _make_notice('SN-EW-BUSY-AGGR') + assert order_has_active_attempt(notice) is True + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + assert order_has_active_attempt(notice) is False + + +def test_edit_window_busy_error_returns_system_busy(app, monkeypatch): + """[断言] 活动 Attempt 时保存守卫返回 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY;空闲时 None。""" + from app.services.shipping_notice import task_workflow + + notice = _make_notice('SN-EW-BUSY-GUARD') + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: True) + err = task_workflow._edit_window_busy_error(notice) + assert err is not None + assert 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY' in repr(err) + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: False) + assert task_workflow._edit_window_busy_error(notice) is None diff --git a/backend/tests/test_shipping_order_extraction_dify_guide.py b/backend/tests/test_shipping_order_extraction_dify_guide.py index 2da77e88..f7a2b648 100644 --- a/backend/tests/test_shipping_order_extraction_dify_guide.py +++ b/backend/tests/test_shipping_order_extraction_dify_guide.py @@ -62,7 +62,7 @@ def _table_first_column_after(marker: str, *, table_label: str | None = None) -> ] -def _review_request(*, scope: str = 'header', line_key: str | None = None) -> dict: +def _review_request(*, scope: str = 'header', draft_line_id: str | None = None) -> dict: """构造单字段最小证据请求信封。""" return { 'contract_version': 'order-review-llm.v1', @@ -73,7 +73,7 @@ def _review_request(*, scope: str = 'header', line_key: str | None = None) -> di 'field_id': 'field-1', 'field_code': 'po_number', 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': None, }], 'evidence_pack': { @@ -119,7 +119,7 @@ def test_review_request_accepts_one_header_field(): def test_review_request_rejects_multiple_fields_and_line_without_key(): - """复核分支必须一次只处理一个字段,明细字段必须绑定 line_key。""" + """复核分支必须一次只处理一个字段,明细字段必须绑定 draft_line_id。""" main = _node_main('## 7. REVIEW_PARSE_REQUEST') multiple = _review_request() multiple['target_fields'].append(dict(multiple['target_fields'][0], field_id='field-2')) @@ -136,7 +136,7 @@ def test_review_request_rejects_multiple_fields_and_line_without_key(): 'review_request_json': '', } assert line_result['request_valid'] is False - assert line_result['request_error_code'] == 'LINE_KEY_REQUIRED' + assert line_result['request_error_code'] == 'DRAFT_LINE_ID_REQUIRED' def test_review_context_removes_secrets_and_limits_to_current_pack(): diff --git a/backend/tests/test_shipping_order_extraction_progress.py b/backend/tests/test_shipping_order_extraction_progress.py index 966fbf74..334805da 100644 --- a/backend/tests/test_shipping_order_extraction_progress.py +++ b/backend/tests/test_shipping_order_extraction_progress.py @@ -107,7 +107,7 @@ def test_progress_event_accepts_email_supplement_merge_summary(app): 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'} + assert {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}.items() <= event.summary_json.items() def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app): @@ -154,11 +154,11 @@ def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app): 'expansion_wave_started', 'budget_stopped', ] - assert events[2].summary_json == { + assert { 'reason_codes': ['required_field_missing'], 'selection_batch': 2, 'unit_count': 2, - } + }.items() <= events[2].summary_json.items() assert run.current_stage_code == 'budget_stopped' assert list(run.active_stage_codes_json or []) == [] diff --git a/backend/tests/test_shipping_order_extraction_quality_migration.py b/backend/tests/test_shipping_order_extraction_quality_migration.py index 7774d235..96524ec2 100644 --- a/backend/tests/test_shipping_order_extraction_quality_migration.py +++ b/backend/tests/test_shipping_order_extraction_quality_migration.py @@ -22,7 +22,7 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch): ) engine = sa.create_engine('sqlite:///:memory:') metadata = sa.MetaData() - for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'): + for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs', 'agent_runtime_bindings'): sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) metadata.create_all(engine) with engine.begin() as connection: diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index 5d93848d..76399f61 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -58,6 +58,7 @@ from app.services.shipping_notice.order_extraction_run_service import ( materialize_order_extraction_run_inputs, serialize_order_extraction_message_state, serialize_order_extraction_run, + submit_order_extraction, synchronize_order_extraction_expansion_snapshot, transition_order_extraction_run, ) @@ -1402,7 +1403,10 @@ def test_run_submission_rejects_changed_frozen_mail_context(app): 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.models import ( + ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, + ShippingDocumentProfileAutoFreezeQualification, + ) from tests.test_shipping_order_auto_freeze_policy import _published_profile fields = _ensure_order_schema() @@ -1448,18 +1452,20 @@ def test_run_submission_auto_freezes_qualified_tasks(app): ) 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(), + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-AF-EXEC-{run.id}', intake_id=intake.id, primary_document_id=document.id, + candidate_key=f'auto-freeze-exec-{run.id}', order_extraction_id=extraction.id, + order_extraction_run_id=run.id, candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'e' * 64}}, identity_rule_set_checksum='e' * 64, + top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id, + confirmation_method='manual', confirmed_at=datetime.utcnow(), )) db.session.add_all([ ShippingDocumentProfileAutoFreezeQualification( @@ -1978,6 +1984,56 @@ def test_run_list_does_not_select_large_input_snapshots(app, client): assert all('input_snapshot_json' not in statement for statement in statements) +def test_conversation_run_list_prefers_submission_primary_over_newer_sibling(app, client): + """会话短列表须把带 client_submission_id 的 primary 排在更新的 sibling 之前,避免恢复误建第二张卡。""" + with app.app_context(): + owner, agent, session, first_intake, _document = _seed_run_input(suffix='LIST-PRIMARY-A') + _, _, _, second_intake, _ = _seed_run_input( + suffix='LIST-PRIMARY-B', + agent_code='shipping_notice_list_primary_b', + ) + second_intake.user_id = owner.id + second_intake.conversation_id = session.session_id + db.session.commit() + + payload = submit_order_extraction( + user=owner, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[first_intake.intake_no, second_intake.intake_no], + submission_id='SUB-LIST-PRIMARY-ORDER', + ) + db.session.commit() + primary_run_no = str(payload['run_no']) + runs = ( + ShippingOrderProcessingRun.query + .filter_by(conversation_id=session.session_id) + .order_by(ShippingOrderProcessingRun.id.asc()) + .all() + ) + assert len(runs) == 2 + primary = next(row for row in runs if row.run_no == primary_run_no) + sibling = next(row for row in runs if row.run_no != primary_run_no) + assert primary.client_submission_id == 'SUB-LIST-PRIMARY-ORDER' + assert not sibling.client_submission_id + sibling_run_no = str(sibling.run_no) + # 模拟 sibling 更晚创建/更新:列表若按纯时间会把它排到第一。 + sibling.created_at = (primary.created_at or datetime.utcnow()) + timedelta(minutes=30) + db.session.commit() + token = issue_local_access_token(owner) + conversation_id = session.session_id + + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20', + headers={'Authorization': f'Bearer {token}'}, + ) + assert response.status_code == 200 + items = response.get_json()['data']['items'] + assert items[0]['run_no'] == primary_run_no + assert items[0]['client_submission_id'] == 'SUB-LIST-PRIMARY-ORDER' + assert any(item['run_no'] == sibling_run_no and not item.get('client_submission_id') for item in items) + + def test_run_api_requires_upload_batch_id(app, client): """发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_extraction_stage0.py b/backend/tests/test_shipping_order_extraction_stage0.py index 3d7eedf5..e614e460 100644 --- a/backend/tests/test_shipping_order_extraction_stage0.py +++ b/backend/tests/test_shipping_order_extraction_stage0.py @@ -47,6 +47,7 @@ def test_unit_transition_appends_auditable_status_event(app): 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, + document_id=100, ) plan.units = [unit] diff --git a/backend/tests/test_shipping_order_extraction_submission.py b/backend/tests/test_shipping_order_extraction_submission.py index 70f764e7..b053d030 100644 --- a/backend/tests/test_shipping_order_extraction_submission.py +++ b/backend/tests/test_shipping_order_extraction_submission.py @@ -84,14 +84,15 @@ def test_submit_appends_to_open_queued_run(app): ) db.session.commit() - # 断言:不同 Intake 不得并入同一 Run;须新建 Run(Candidate 前无右侧 OT 卡)。 + # 断言:不同 Intake 不得并入同一 Run;须新建 Run。预候选 order_notice 未建 OT, + # user_task_no 仍为 None,但会话投影把两个 Intake 各计一张处理中卡(total_tasks=2)。 assert payload['decision'] == 'created' assert payload['created_new'] is True assert payload['run_no'] != first.run_no assert payload['reason_code'] == 'adjudication_unit_boundary' assert ShippingOrderProcessingRun.query.count() == 2 assert payload['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_submit_creates_when_input_frozen(app): @@ -132,9 +133,9 @@ def test_submit_creates_when_input_frozen(app): assert payload['created_new'] is True assert payload['run_no'] != first.run_no assert ShippingOrderProcessingRun.query.count() == 2 - # Candidate 前会话右侧不展示伪 OT。 + # Candidate 前不伪造 OT(user_task_no=None);预候选 order_notice 按处理中卡计 2 张。 assert payload['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_submit_idempotent_by_submission_id(app): @@ -398,11 +399,11 @@ def test_failed_same_attachment_reupload_inherits_user_task(app): assert new_run.reparse_of_run_id == old_run.id assert old_run.superseded_by_run_id == new_run.id assert old_run.superseded_at is not None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_appended_projection_does_not_mark_recently_created(app): - """跨 Intake 新建 Run 时 Candidate 前无右侧 OT 卡;仅断言裁决与 Run 边界。""" + """跨 Intake 新建 Run 时 Candidate 前无真实 OT(user_task_no=None);投影仍按预候选 order_notice 计处理中卡。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input(suffix='SUB-BADGE') first = submit_order_extraction( @@ -439,7 +440,7 @@ def test_appended_projection_does_not_mark_recently_created(app): assert payload['run_no'] != first['run_no'] assert payload['user_task_no'] is None assert first['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 assert ShippingOrderProcessingRun.query.count() == 2 diff --git a/backend/tests/test_shipping_order_extraction_worker.py b/backend/tests/test_shipping_order_extraction_worker.py index 9f1db3d8..8fdbabde 100644 --- a/backend/tests/test_shipping_order_extraction_worker.py +++ b/backend/tests/test_shipping_order_extraction_worker.py @@ -252,8 +252,8 @@ def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]): ) -def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch): - """同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。""" +def test_process_unit_with_retries_stops_on_retryable_technical_failure(monkeypatch): + """任一技术故障(含 ServiceUnavailableError)在单元内失败即停止,不自动重试;调用方可继续处理其他附件。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -293,15 +293,15 @@ def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) - assert result == 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 + assert result is None + assert unit.status == 'failed' + assert unit.attempt_count == 1 + assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 0 + assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 1 -def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch): - """同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。""" +def test_process_unit_with_retries_records_single_route_attempt(monkeypatch): + """同一 Job 内仅路由一次;技术失败后单元不再重试,审计尝试号按单元执行代次记录。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -339,8 +339,8 @@ def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch): 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] + assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) is None + assert route_attempts == [1] def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatch): @@ -383,8 +383,8 @@ def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatc assert unit.technical_failure_reason_code is None -def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch): - """自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。""" +def test_process_unit_with_retries_marks_unit_failed_without_retry(monkeypatch): + """技术失败在单元内失败即停止,不消耗重试预算;调用方可继续处理其他附件。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -416,10 +416,10 @@ def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(m assert result is None assert unit.status == 'failed' - assert unit.attempt_count == 3 + assert unit.attempt_count == 1 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 + assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 0 + assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 1 def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch): diff --git a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py index ca64303f..07e255b5 100644 --- a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py +++ b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py @@ -90,7 +90,7 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch): assert result['primaryNotice'] is None -def test_build_handling_items_splits_pending_freeze_review_and_failure(): +def test_build_handling_items_splits_pending_freeze_review_and_failure(monkeypatch): """Run 级 handling_items 必须拆分待补、冲突、冻结、复核与技术失败,不得只给笼统复核态。""" run = SimpleNamespace( status='partially_completed', @@ -145,6 +145,12 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure(): ), ] + # document_review 只在存在活动(非终态)ReviewCase 时投影;纯单元 Run 无落库 + # Case,故按文件口径补一条模板 Case 以激活 document_review 分支。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=11, case_no='CASE-11')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) categories = [item['category'] for item in items] @@ -196,7 +202,7 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs(): assert budget['affected_refs'][0]['document_id'] == 42 -def test_build_handling_items_counts_one_document_in_only_one_primary_category(): +def test_build_handling_items_counts_one_document_in_only_one_primary_category(monkeypatch): """同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。""" run = SimpleNamespace( status='partially_completed', @@ -234,13 +240,18 @@ def test_build_handling_items_counts_one_document_in_only_one_primary_category() technical_failure_reason_code=None, )] + # document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=99, case_no='CASE-99')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) assert [item['category'] for item in items] == ['document_review'] assert items[0]['count'] == 1 -def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id(): +def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id(monkeypatch): """预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。""" run = SimpleNamespace( status='partially_completed', @@ -270,6 +281,11 @@ def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapsh technical_failure_reason_code=None, )] + # document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=100, case_no='CASE-100')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) # 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。 diff --git a/backend/tests/test_shipping_order_field_purposes.py b/backend/tests/test_shipping_order_field_purposes.py index e18c0c0e..50aa4265 100644 --- a/backend/tests/test_shipping_order_field_purposes.py +++ b/backend/tests/test_shipping_order_field_purposes.py @@ -11,7 +11,7 @@ from __future__ import annotations from app import db from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingNotice, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, ) from app.services.shipping_notice.order_schema import service from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues @@ -31,15 +31,15 @@ def _config(field_id: str) -> dict: } -def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingNotice: +def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingOrderTask: """创建冻结快照,策略绑定决定履约阶段如何定位预约单号。""" service.initialize_schema({'display_name': '用途测试'}, actor_id=None) field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None) draft = service.create_draft({}, actor_id=None) saved = service.save_draft(draft['id'], {'fields': [_config(field['id'])], 'expected_lock_version': draft['lock_version']}, actor_id=None) published = service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) - task = ShippingNotice( - task_no='SN-PURPOSE-1', source_type='manual', lines_json=[{'reservation_id': 'WRONG'}], + task = ShippingOrderTask( + task_no='OT-PURPOSE-1', source_type='direct_pdf', user_id=1, ) db.session.add(task) db.session.flush() @@ -48,7 +48,7 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() decision = ShippingOrderFieldDecision( @@ -62,25 +62,24 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = value_text=value, value_json=value, )) task.current_order_extraction_id = extraction.id - bindings = [] if include_reservation_capability: - bindings.append({ - 'capability_code': 'fulfillment.reservation_identity', - 'field_id': field['id'], - 'scope': 'line', - }) + # 冻结策略只承认 frozen fulfillment_rule.required_field_ids;old + # fulfillment_policy.definition.field_bindings 已不再匹配。 + rule_versions_json = {'fulfillment_rule': {'required_field_ids': { + 'reservation_id': field['id'], 'part_number': field['id'], + 'qty': field['id'], 'quantity': field['id'], + }}} + else: + rule_versions_json = {} snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], order_data_version=1, customer_po_number='PURPOSE-PO-001', header_values_json={}, - rule_versions_json={'fulfillment_policy': { - 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, - 'definition': {'field_bindings': bindings}, - }}, + rule_versions_json=rule_versions_json, ) db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, reservation_id=value, + snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=value, field_values_json={field['id']: value}, )) task.order_snapshot_id = snapshot.id @@ -89,10 +88,9 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app): - """门禁以冻结预约单为准,旧任务投影或后续 FieldValue 变化均不得重解释履约。""" + """门禁以冻结预约单为准,后续 FieldValue 变化均不得重解释履约。""" with app.app_context(): task = _task_with_reservation('3000000001') - task.lines_json = [{'reservation_id': 'INVALID'}] value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one() value.value_text = 'INVALID' value.value_json = 'INVALID' diff --git a/backend/tests/test_shipping_order_line_no_resolver.py b/backend/tests/test_shipping_order_line_no_resolver.py index 206044d3..1626f2bd 100644 --- a/backend/tests/test_shipping_order_line_no_resolver.py +++ b/backend/tests/test_shipping_order_line_no_resolver.py @@ -1,113 +1,48 @@ """ backend/tests/test_shipping_order_line_no_resolver.py -用途:order_line_no_resolver 单一解析器契约测试(项次展示/导出同源)。 -依赖:pytest、resolver、field_rules 格式门禁。 -逻辑:覆盖 field 真实值 / customer_po_line_no 回退 / sequence 展示序号 / 全空缺失四级分支, - 并验证 field_id 键与历史 field_code 键两种入参格式;mark 为 pure_unit 跳过 Flask 创建。 +用途:验证订单项次解析器只读取系统持久化的 line_no。 +依赖:order_line_no_resolver。 +逻辑:line_no 缺失时显式返回空值;客户 PO 行号、field_id 映射和展示序号均不得成为回退来源。 """ import pytest from app.services.shipping_notice.order_line_no_resolver import ( - LINE_NO_SOURCE_CUSTOMER_PO_LINE, - LINE_NO_SOURCE_FIELD, - LINE_NO_SOURCE_SEQUENCE, field_id_by_code_from_definition, resolve_order_line_no, ) -LINE_NO_ID = 'line-no-id' -CUSTOMER_PO_LINE_ID = 'customer-po-line-id' -FIELD_ID_BY_CODE = { - 'line_no': LINE_NO_ID, - 'customer_po_line_no': CUSTOMER_PO_LINE_ID, -} + +@pytest.mark.pure_unit +def test_resolver_reads_persisted_line_no_only(): + """系统已持久化项次时原样返回,不进行派生或格式重排。""" + assert resolve_order_line_no( + field_values={'line_no': '00010', 'customer_po_line_no': '00020'}, + field_id_by_code={'line_no': 'line-no-id'}, + ) == {'value': '00010', 'source': 'persisted'} @pytest.mark.pure_unit -def test_resolver_prefers_real_line_no_field_value(): - """line_no 字段真实值必须优先于客户 PO 行号与序号。""" +def test_resolver_does_not_use_field_id_or_customer_po_line_no(): + """项次不是 Schema 字段值,也不能从客户 PO 行号推断。""" assert resolve_order_line_no( - field_values={LINE_NO_ID: '00010', CUSTOMER_PO_LINE_ID: '00020'}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=1, - ) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD} - - -@pytest.mark.pure_unit -def test_resolver_prefers_real_line_no_over_sequence_and_customer(): - """line_no 缺失时按顺序回退 customer_po_line_no,不直接落序号。""" - assert resolve_order_line_no( - field_values={CUSTOMER_PO_LINE_ID: '10'}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=1, - ) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE} - - -@pytest.mark.pure_unit -def test_resolver_rejects_invalid_customer_line_no_format(): - """客户 PO 行号格式非法(非 1–6 位数字)时不得当业务项次,回退展示序号。""" - assert resolve_order_line_no( - field_values={'line_no': None, CUSTOMER_PO_LINE_ID: 'ABC'}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=2, - ) == {'value': '2', 'source': LINE_NO_SOURCE_SEQUENCE} - - -@pytest.mark.pure_unit -def test_resolver_uses_sequence_when_business_fields_missing(): - """line_no 与 customer_po_line_no 均缺失时仅能使用显式标注的展示序号。""" - assert resolve_order_line_no( - field_values={'line_no': None}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=3, - ) == {'value': '3', 'source': LINE_NO_SOURCE_SEQUENCE} - - -@pytest.mark.pure_unit -def test_resolver_missing_everything_returns_none_source(): - """全部事实缺失且无序号时返回 None/None,禁止伪造空字符串或 0。""" - assert resolve_order_line_no( - field_values={}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=None, + field_values={'line-no-id': '10', 'customer_po_line_no': '20'}, + field_id_by_code={'line_no': 'line-no-id'}, ) == {'value': None, 'source': None} @pytest.mark.pure_unit -def test_resolver_supports_legacy_field_code_keys(): - """历史/测试数据按 field_code 键存储时,解析器仍能正确读取。""" +def test_resolver_does_not_fallback_to_display_sequence(): + """缺少持久化项次时显式返回空值,展示层不能伪造业务项次。""" assert resolve_order_line_no( - field_values={'line_no': '00020', 'customer_po_line_no': '00030'}, - field_id_by_code=None, - fallback_sequence=5, - ) == {'value': '00020', 'source': LINE_NO_SOURCE_FIELD} + field_values={}, + ) == {'value': None, 'source': None} @pytest.mark.pure_unit -def test_resolver_fallbacks_to_code_key_when_field_id_missing(): - """field_id 键缺失时回退读取 field_code 键,避免跨格式读取失败。""" - assert resolve_order_line_no( - field_values={CUSTOMER_PO_LINE_ID: '10', 'customer_po_line_no': '20'}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=1, - ) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE} - - -@pytest.mark.pure_unit -def test_resolver_keeps_leading_zeros(): - """项次原样输出,保留前导零(如 00010),禁止转 int 丢零。""" - assert resolve_order_line_no( - field_values={'line_no': '00010'}, - field_id_by_code=FIELD_ID_BY_CODE, - fallback_sequence=1, - ) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD} - - -@pytest.mark.pure_unit -def test_field_id_by_code_from_definition_extracts_only_pair(): - """Schema 定义中仅提取同时具备 field_code/field_id 的字段。""" +def test_field_id_by_code_from_definition_is_metadata_only(): + """Schema 映射仍可独立解析,但不会参与 line_no 读取。""" definition = {'fields': [ {'field_code': 'line_no', 'field_id': 'a', 'scope': 'line'}, {'field_code': 'customer_po_line_no', 'field_id': 'b'}, diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 2dfd134a..e01c9d20 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -2,12 +2,15 @@ from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _extract_matching_signature, + _observe_layout_features, _resolve_coordinate_transform, match_frozen_coordinate_profiles, ) from app.services.shipping_notice.document_layout.order_profile_signature import ( MATCHER_POLICY_ID, build_layout_signature, + clip_table_bbox_to_business_rows, ) @@ -47,8 +50,13 @@ def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None }} -def _layout(text: str = 'PLANT NAME: FACTORY A', *, bbox: dict | None = None) -> dict: - """构造页眉锨点与表内表头分离的最小坐标证据。""" +def _layout( + text: str = 'PLANT NAME: FACTORY A', + *, + bbox: dict | None = None, + header_text: str = 'ITEM NO QTY', +) -> dict: + """构造页眉锚点与表内表头分离的最小坐标证据。""" table = { 'table_id': 'table-1', 'page_no': 1, @@ -58,7 +66,6 @@ def _layout(text: str = 'PLANT NAME: FACTORY A', *, bbox: dict | None = None) -> {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}} for index, char in enumerate(text) ] - header_text = 'ITEM NO QTY' header_glyphs = [ { 'text': char, @@ -728,3 +735,252 @@ def test_parse_validation_does_not_upgrade_ineligible_profile_to_unique_match(mo ) assert result.status == 'no_match' + + +def test_profile_table_candidates_virtual_empty_page_does_not_block(monkeypatch): + """两页文档、第 2 页无业务表(补成虚拟页)不得把已成功重建的目标表覆盖成失败。 + + 回归:第 2 页被补为虚拟页 ``page-2`` 时,``_coordinate_profile_rows`` 返回 ``None`` + (无表字符/无 raw_table_bbox);旧逻辑在 ``_virtual_page_without_rows_is_nonblocking`` + 之前被 ``is None`` 分支误判为行重建失败,追加 + ``order_profile_coordinate_reconstruction_unavailable`` 使整单阻塞为 + ``coordinate_evidence_unavailable``。修复后空虚拟页被豁免,真实业务表(第 1 页)仍成功。 + + 盲测/样本验证同样按“空页跳过”,因此本条与盲测语义一致。 + """ + from types import SimpleNamespace + + from app.services.shipping_notice import order_extraction_workflow as wf + + layout = _layout('PLANT NAME: FACTORY A', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}) + layout['status'] = 'ready' + layout['layout_candidate'] = {'schema_version': 'test', 'pages': []} + # 第 2 页只有页级字符、无任何业务表 → 会被补成虚拟页 page-2。 + layout['coordinate_evidence']['pages']['2'] = {'width': 200, 'height': 280} + layout['coordinate_evidence']['page_glyphs']['2'] = [ + {'text': 'N', 'bbox': {'x0': 10, 'y0': 200, 'x1': 15, 'y1': 212}}, + ] + profile = _with_signature(_profile('PO'), layout) + + schema_def = {'fields': [{ + 'field_id': 'line-id', 'field_code': 'customer_po_line_no', + 'scope': 'line', 'enabled': True, 'value_type': 'string', + }]} + snapshot = { + 'schema': {'extraction_contract': {}, 'definition': schema_def}, + 'order_document_profiles': [profile], + 'intakes': [{'intake_id': 1, 'documents': [{ + 'document_id': 100, 'filename': 'x.pdf', 'layout_snapshot': layout, + }]}], + } + run = SimpleNamespace(id=9, schema_version_id=34, input_snapshot_json=snapshot) + unit = SimpleNamespace(id=99, intake_id=1, document_id=100) + + # 隔离 DB/开关:本测试只关心虚拟空页的行重建门禁语义。 + monkeypatch.setattr(wf.db.session, 'get', lambda *_a, **_k: None) + monkeypatch.setattr(wf, 'profile_auto_selection_enabled', lambda: True) + + def fake_rows(**kwargs): + """注入真实行为:第 1 页业务表重建出 1 行;无表的虚拟页返回 None。""" + raw_table = kwargs.get('raw_table') or {} + if str(raw_table.get('table_id') or '') == 'page-2': + return None + return [{ + 'row_index': 1, '_coordinate_region_id': 'lines', '_coordinate_row_count': 1, + 'status': 'parsed', 'issues': [], + 'fields': [{ + 'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'value': '10', + 'quote': '10', 'page_no': 1, 'table_id': 'table-1', + }], + }] + + monkeypatch.setattr(wf, '_coordinate_profile_rows', fake_rows) + + result = wf._profile_table_candidates(run, unit=unit, profiles=[profile], match_only=False) + + assert result['blocking'] is False + assert 'order_profile_coordinate_reconstruction_unavailable' not in (result.get('issues') or []) + assert result['matched'] is True + # 虚拟空页应被跳过,只有第 1 页业务表进入结果。 + assert len(result.get('tables') or []) == 1 + + +def _profile_without_required_anchors(code: str, layout: dict) -> dict: + """模拟 FOX 类近亲:无必选锚点,身份只能靠表头结构互斥。""" + profile = _with_signature(_profile(code), layout) + profile['definition']['document_match']['required_anchors'] = [] + return profile + + +def test_near_twin_header_discriminator_makes_unique_match(): + """无必选锚点的近亲模板仅差表头原子时,须硬互斥成 unique_match。""" + mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price' + tw_header = 'Item Parts No ECCN Description REV UNIT QTY Delivery Date Unit Total Price' + mx_layout = _layout(header_text=mx_header) + tw_layout = _layout(header_text=tw_header) + mx = _profile_without_required_anchors('FOX_MX', mx_layout) + tw = _profile_without_required_anchors('FOX_TW', tw_layout) + + mx_result = match_frozen_coordinate_profiles(profiles=[mx, tw], layout=mx_layout) + assert mx_result.status == 'unique_match' + assert mx_result.profile_code == 'FOX_MX' + tw_on_mx = next(item for item in mx_result.candidates if item.profile_code == 'FOX_TW') + assert tw_on_mx.hard_match is False + assert 'profile_header_discriminator_conflict' in tw_on_mx.reason_codes + + tw_result = match_frozen_coordinate_profiles(profiles=[mx, tw], layout=tw_layout) + assert tw_result.status == 'unique_match' + assert tw_result.profile_code == 'FOX_TW' + mx_on_tw = next(item for item in tw_result.candidates if item.profile_code == 'FOX_MX') + assert mx_on_tw.hard_match is False + assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes + + +def test_required_anchors_skip_header_atom_hard_mutex(): + """已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。""" + mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price' + tw_header = 'Item Parts No ECCN Description REV UNIT QTY Delivery Date Unit Total Price' + signed = _layout(header_text=mx_header) + observed = _layout(header_text=tw_header) + profile = _with_signature(_profile('INVENTECH_TW'), signed) + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=observed) + candidate = result.candidates[0] + # 关键断言:有必选锚点后禁止表头原子硬互斥,不得再出现 discriminator 原因码。 + assert 'profile_header_discriminator_conflict' not in candidate.reason_codes + assert candidate.hard_match is True + + +def test_table_geometry_ignores_mineru_sticky_footer_height(): + """MinerU 把备注粘进主表拉高 y1 时,身份几何仍应按顶边/宽度命中,不得掉到 0.75。""" + clean = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55}) + dirty = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}) + profile = _with_signature(_profile('PO_A', score=0.0, margin=0.0), clean) + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=dirty) + + assert result.status == 'unique_match' + candidate = result.candidates[0] + assert candidate.dimension_scores is not None + # 关键断言:底边被脏框拉高后,table_geometry 仍须保持高分(忽略 y1)。 + assert candidate.dimension_scores.table_geometry >= 0.99 + + +def test_auto_select_tolerates_dirty_table_height_when_top_width_match(): + """近亲双 hard_match 时,脏高度不得把原本可决胜的 Top1 压进 ambiguous。""" + clean = _layout('PLANT NAME: FACTORY A TYPE: UM17', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55}) + dirty = _layout('PLANT NAME: FACTORY A TYPE: UM17', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}) + stronger = _with_signature(_profile('PO_A', optional=['UM17']), clean) + weaker = _with_signature(_profile('PO_B', optional=['MISSING_TAG']), clean) + weaker['definition']['table_regions'][0]['region']['y1'] = 0.5 + weaker['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = 0.5 + weaker['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = 0.5 + for item in (stronger, weaker): + item['definition']['document_match']['minimum_margin'] = 0.05 + item['definition']['document_match']['scoring_thresholds'] = { + 'auto_select_minimum_score': 0.80, + 'auto_select_minimum_margin': 0.05, + 'evidence_coverage_minimum': 0.60, + 'critical_structure_minimum': 0.70, + } + weaker_sig = build_layout_signature(definition=weaker['definition'], sample_layouts=[clean]) + weaker['matching_signature'] = weaker_sig + weaker['matching_signature_checksum'] = weaker_sig['signature_checksum'] + + clean_result = match_frozen_coordinate_profiles(profiles=[stronger, weaker], layout=clean) + dirty_result = match_frozen_coordinate_profiles(profiles=[stronger, weaker], layout=dirty) + + assert clean_result.status == 'selected_by_score' + assert dirty_result.status == 'selected_by_score' + assert dirty_result.profile_code == 'PO_A' + dirty_top = next(item for item in dirty_result.candidates if item.profile_code == 'PO_A') + assert dirty_top.dimension_scores is not None + assert dirty_top.dimension_scores.table_geometry >= 0.99 + + +def _layout_with_sticky_payment_footer(*, table_y1: float = 0.95) -> dict: + """主表框被备注拉高;页字符含结束文案,须由模板 termination_rules 声明后才裁剪。""" + layout = _layout(bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': table_y1}) + footer = 'Payment Terms' + footer_glyphs = [ + { + 'text': char, + 'bbox': { + 'x0': 12 + index * 6, + 'y0': 0.58 * 280, + 'x1': 16 + index * 6, + 'y1': 0.58 * 280 + 10, + }, + 'boundary_before': 'space' if index and footer[index - 1] == ' ' else 'none', + } + for index, char in enumerate(footer) + if char != ' ' + ] + layout['coordinate_evidence']['page_glyphs']['1'].extend(footer_glyphs) + return layout + + +def _payment_termination_rule() -> dict: + """测试用:模板声明的业务表终止锚点(非代码硬编码词表)。""" + return { + 'rule_id': 'payment_terms', + 'anchor': { + 'anchor_id': 'payment_terms', + 'text': 'Payment Terms', + 'match_mode': 'contains', + }, + } + + +def test_clip_table_bbox_cuts_sticky_payment_footer(): + """业务行裁剪只认模板 termination_rules;无声明则 fail-open 保持原框。""" + page = {'width': 200, 'height': 280} + dirty = [0.05, 0.25, 0.95, 0.95] + layout = _layout_with_sticky_payment_footer() + glyphs = layout['coordinate_evidence']['page_glyphs']['1'] + rules = [_payment_termination_rule()] + + # 无模板终止声明 → 不裁剪 + assert clip_table_bbox_to_business_rows(dirty, page=page, glyphs=glyphs) == dirty + + clipped = clip_table_bbox_to_business_rows( + dirty, page=page, glyphs=glyphs, termination_rules=rules, + ) + assert clipped is not None + assert clipped[0] == dirty[0] and clipped[1] == dirty[1] and clipped[2] == dirty[2] + # 关键断言:有模板终止规则时,底边裁到声明锚点附近。 + assert clipped[3] < 0.62 + assert clipped[3] > 0.50 + + unchanged = clip_table_bbox_to_business_rows( + dirty, + page=page, + glyphs=layout['coordinate_evidence']['page_glyphs']['1'][:5], + termination_rules=rules, + ) + assert unchanged == dirty + + +def test_observe_layout_features_applies_business_row_clip(): + """运行时主表观测须按模板 termination_rules 裁剪粘连备注。""" + layout = _layout_with_sticky_payment_footer() + profile = _with_signature(_profile('PO_A', score=0.0, margin=0.0), _layout( + bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.55}, + )) + signature_body, _meta = _extract_matching_signature(profile) + pages = layout['coordinate_evidence']['pages'] + page_glyphs = layout['coordinate_evidence']['page_glyphs'] + glyph_tables = layout['coordinate_evidence']['tables'] + observed = _observe_layout_features( + layout=layout, + tables=layout['tables'], + pages=pages, + glyph_tables=glyph_tables, + page_glyphs=page_glyphs, + signature=signature_body, + termination_rules=[_payment_termination_rule()], + ) + bbox = observed['primary_table_bbox'] + assert bbox is not None + assert bbox[3] < 0.62 + assert bbox[3] > 0.50 diff --git a/backend/tests/test_shipping_order_profile_parse_validation.py b/backend/tests/test_shipping_order_profile_parse_validation.py index b3e5ba7e..2e27a6b0 100644 --- a/backend/tests/test_shipping_order_profile_parse_validation.py +++ b/backend/tests/test_shipping_order_profile_parse_validation.py @@ -164,3 +164,48 @@ def test_parse_validation_accepts_month_day_year_date_format(): assert result['passed'] is True assert result['metrics']['type_issue_count'] == 0 + + +def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict: + """构造明细区文字被纵向位移到冻结字段带之下的 layout。 + + 回归场景:legacy 模板把 line 字段区冻结在标注样本的绝对页坐标(y≈112-140), + 但实际物理表整体下移,文字落在冻结带之外(y≈200-212)。行重建 ``values_for`` + 只按横向边界在所在视觉行取字,与纵向是否位移无关;而覆盖率门禁此前用严格 + 中心包含读取冻结区域,会误读为空。此 helper 提供一个与冻结带错位的表, + bbox 同时与模板表区交叠并覆盖真实文字,用于验证位移容忍覆盖。 + """ + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 5, 'y0': 200 + (index % 3), 'x1': 24 + index * 5, 'y1': 212 + (index % 3)}} + for index, char in enumerate(text) + ] + return { + 'tables': [{ + 'table_id': 'table-1', 'page_no': 1, + 'bbox': {'x0': 10, 'y0': 140, 'x1': 190, 'y1': 250}, + }], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 280}}, + 'page_glyphs': {'1': glyphs}, + 'tables': {'table-1': glyphs}, + }, + } + + +def test_parse_validation_tolerates_shifted_line_field_coverage(): + """line 字段区整体纵向位移时,覆盖率应按行重建的横向重叠语义命中,而非冻结带误读。 + + 回归:2658 的明细表因字段换行下移,冻结的绝对页坐标读空导致覆盖率 0.14 并误报 + ``profile_parse_line_coverage_insufficient``;修复后按位移容忍窗口可见全部 line 字段。 + """ + profile = _minimal_profile_snapshot() + layout = _layout_with_shifted_line_text() + definition = {'fields': [{'field_code': 'customer_po_line_no', 'enabled': True, 'value_type': 'string'}]} + result = validate_profile_parse_candidate( + profile_snapshot=profile, + layout=layout, + definition=definition, + ) + assert result['passed'] is True, result['reason_codes'] + assert result['metrics']['line_coverage_ratio'] > 0.6, result['metrics'] + assert result['metrics']['unknown_column_ratio'] < 0.3, result['metrics'] diff --git a/backend/tests/test_shipping_order_profile_signature.py b/backend/tests/test_shipping_order_profile_signature.py index 9aa4e962..3e116ac6 100644 --- a/backend/tests/test_shipping_order_profile_signature.py +++ b/backend/tests/test_shipping_order_profile_signature.py @@ -2,6 +2,7 @@ from app.services.shipping_notice.document_layout.order_profile_signature import ( LAYOUT_SIGNATURE_ID, + _is_dynamic_token, build_layout_signature, signature_checksum, signature_is_safe_for_audit, @@ -115,6 +116,30 @@ def test_dynamic_tokens_filtered_from_header_signature(): assert '2026-08-04' not in joined +def test_qty_req_header_label_is_not_dynamic_token(): + """ZT 列名 Qty.Req / Qty Req 是稳定表头,不得被「Qty + 值」规则误杀。""" + # 断言:列名保留;带分隔符或数字的业务值仍判动态。 + assert _is_dynamic_token('Qty.Req') is False + assert _is_dynamic_token('Qty Req') is False + assert _is_dynamic_token('QTY') is False + assert _is_dynamic_token('Qty: 24') is True + assert _is_dynamic_token('Qty 24') is True + assert _is_dynamic_token('Qty-24') is True + + +def test_qty_req_preserved_in_header_signature(): + """签名构建必须保留 Qty.Req,同时仍过滤 Qty: 24 这类粘连业务值。""" + definition = _minimal_definition() + layout = _sample_layout(header_text='Itm Qty.Req Item Number Qty: 24') + tokens = build_layout_signature( + definition=definition, sample_layouts=[layout], + )['signature']['table_patterns'][0]['header_tokens'] + joined = ' '.join(tokens) + assert 'Qty.Req' in joined + assert 'Qty: 24' not in joined + assert '24' not in joined + + def test_header_signature_preserves_visual_line_order_and_token_positions(): """表头字符即使源顺序交错,也必须按视觉行和行内坐标生成签名。""" definition = _minimal_definition() diff --git a/backend/tests/test_shipping_order_review_evidence_selector.py b/backend/tests/test_shipping_order_review_evidence_selector.py index bf7dc3f6..cf0b36c2 100644 --- a/backend/tests/test_shipping_order_review_evidence_selector.py +++ b/backend/tests/test_shipping_order_review_evidence_selector.py @@ -28,6 +28,7 @@ def test_select_l1_field_evidence_pack(): 'page_no': 1, 'rows': [{ 'row_index': 0, + 'draft_line_id': 'machine-1', 'fields': [{ 'field_id': 'fld-qty', 'quote': '100', @@ -38,15 +39,18 @@ def test_select_l1_field_evidence_pack(): } pack = select_review_evidence_pack( document=document, - target_fields=[{'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line'}], - evidence_level='L1_field', + target_fields=[{ + 'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line', + 'draft_line_id': 'machine-1', + }], + evidence_level='L2_table', ) - assert pack['evidence_level'] == 'L1_field' + assert pack['evidence_level'] == 'L2_table' assert pack['fields'][0]['snippets'] -def test_select_line_evidence_binds_target_line_key(): - """明细证据必须绑定目标 line_key,禁止用兄弟行同名字段串值。""" +def test_select_line_evidence_binds_target_draft_line_id(): + """明细证据必须绑定目标 draft_line_id,禁止用兄弟行同名字段串值。""" document = { 'document_id': 1, 'layout_schema_candidates': [{ @@ -55,12 +59,12 @@ def test_select_line_evidence_binds_target_line_key(): 'rows': [ { 'row_index': 1, - 'line_key': 'machine-1', + 'draft_line_id': 'machine-1', 'fields': [{'field_id': 'fld-qty', 'quote': '10', 'value': '10'}], }, { 'row_index': 2, - 'line_key': 'machine-2', + 'draft_line_id': 'machine-2', 'fields': [{'field_id': 'fld-qty', 'quote': '20', 'value': '20'}], }, ], @@ -78,7 +82,7 @@ def test_select_line_evidence_binds_target_line_key(): 'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line', - 'line_key': 'machine-2', + 'draft_line_id': 'machine-2', }], evidence_level='L3_page', ) diff --git a/backend/tests/test_shipping_order_review_field_conflict.py b/backend/tests/test_shipping_order_review_field_conflict.py index e94920cf..a5f2576d 100644 --- a/backend/tests/test_shipping_order_review_field_conflict.py +++ b/backend/tests/test_shipping_order_review_field_conflict.py @@ -59,7 +59,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys(): candidate_id=1, current_draft=SimpleNamespace( lines_json=[{ - 'line_key': 'line-1', + 'draft_line_id': 'line-1', 'line_index': 0, 'values': {}, }], @@ -80,7 +80,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys(): item = items[0] assert item['conflict_key'] == '0:qty' assert item['field_code'] == 'qty' - assert item['line_key'] == 'line-1' + assert item['draft_line_id'] == 'line-1' assert item['reason'] == 'cross_source_conflict' assert [opt['display_value'] for opt in item['options']] == ['10', '12'] assert item['options'][0]['sources'] == ['table'] @@ -224,7 +224,7 @@ def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_bla assert conflicts == [] assert evidence_issues == [{ 'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None, - 'line_key': None, 'scope': 'unscoped', 'severity': 'blocking', + 'draft_line_id': None, 'scope': 'unscoped', 'severity': 'blocking', 'reason': 'supplement_conflict_evidence_insufficient', 'options': [], 'observation_ids': [], 'recovery_action': 'reparse_current_pdf', }] @@ -299,6 +299,8 @@ def test_project_review_findings_omits_optional_line_no_evidence_gap(): 'severity': 'blocking', 'reason': 'evidence_missing', 'owning_gate_code': 'field_completeness', + # line_no 非必填且可派生:按冻结字段配置声明为非阻断,避免继续显示为待确认。 + 'field_config': {'required': False, 'auto_create_key_field': False}, }], structured_result_json={ 'extraction': {'field_adjudication': { diff --git a/backend/tests/test_shipping_order_review_llm_audit.py b/backend/tests/test_shipping_order_review_llm_audit.py index 022f7e81..2ffa552c 100644 --- a/backend/tests/test_shipping_order_review_llm_audit.py +++ b/backend/tests/test_shipping_order_review_llm_audit.py @@ -39,6 +39,9 @@ def _seed_review_case(*, suffix: str): ) ensure_order_extraction_plan(run) unit = run.extraction_plan.units[0] + # 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required; + # 该夹具只需物化 Case/Draft,故把 Unit 置为就绪(与 test_shipping_review_case_audit_timeline 一致)。 + unit.status = 'candidate_ready' unit.result_json = { 'orders': [{ 'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}], diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index cdaa6430..a7f7fcac 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -24,7 +24,6 @@ from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderCandidate, - ShippingOrderCustomerMatch, ShippingOrderExtraction, ShippingOrderProcessingRun, ShippingOrderReviewCase, @@ -34,6 +33,7 @@ from app.models import ( ShippingOrderReviewWaveLine, ShippingOrderSchemaVersion, ShippingNotice, + ShippingOrderTask, ShippingCustomer, User, ) @@ -302,8 +302,8 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app): ] -def test_review_queue_uses_formal_task_lifecycle_stage(app): - """Case 已绑定正式任务后,队列阶段必须随正式 Gate/领域事实推进。""" +def test_review_queue_uses_formal_task_lifecycle_stage(app, monkeypatch): + """Case 已绑定正式任务后,队列阶段必须随正式 OT.stage 推进,且不得走全量 ui_state。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-FORMAL-STAGE') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) @@ -318,21 +318,27 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): db.session.add(candidate) db.session.flush() case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0]) - notice = ShippingNotice( - task_no='SN-REVIEW-QUEUE-FORMAL-STAGE', + task = ShippingOrderTask( + task_no='OT-REVIEW-QUEUE-FORMAL-STAGE', user_id=user.id, conversation_id=session.session_id, - source_type='manual', - source_candidate_id=candidate.id, - match_status='partial', - inventory_lines_json=[{'part_number': 'PN-QUEUE-002'}], + extraction_run_id=run.id, + status='processing', + stage='inventory_preparation', ) - db.session.add(notice) + db.session.add(task) db.session.flush() case.status = 'confirmed' - case.confirmed_task_id = notice.id + case.confirmed_task_id = task.id db.session.commit() + def _forbid_full_ui_state(*_args, **_kwargs): + raise AssertionError('queue summary must not call build_task_ui_state') + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.build_task_ui_state', + _forbid_full_ui_state, + ) item = serialize_review_queue([run])['items'][0] assert item['po_number'] == 'PO-QUEUE-002' @@ -342,6 +348,65 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): ] +def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(app, monkeypatch): + """旧 OT.stage=step* 不在五阶段映射表时,队列须用批量 Gate 兜底,不能塌成 intake_parse。""" + from app.models import ShippingProcessExecution, ShippingProcessGate + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-LEGACY-STAGE') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + candidate = ShippingOrderCandidate( + candidate_no='CAND-REVIEW-QUEUE-LEGACY-STAGE', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key='review-queue-legacy-stage', + order_extraction_run_id=run.id, + po_number='PO-QUEUE-LEGACY', + ) + db.session.add(candidate) + db.session.flush() + case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0]) + task = ShippingOrderTask( + task_no='OT-REVIEW-QUEUE-LEGACY-STAGE', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=run.id, + status='waiting_review', + stage='step5_match_inventory', + ) + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-REVIEW-QUEUE-LEGACY', + task_id=task.id, + review_case_id=case.id, + status='active', + current_gate_code='inventory_sufficiency', + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=execution.id, + gate_code='inventory_sufficiency', + sequence_no=16, + status='blocked_manual', + )) + task.active_process_execution_id = execution.id + case.status = 'confirmed' + case.confirmed_task_id = task.id + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.build_task_ui_state', + lambda *_a, **_k: (_ for _ in ()).throw(AssertionError('no full ui_state')), + ) + item = serialize_review_queue([run])['items'][0] + + assert item['lifecycle_stage'] == 'fulfillment_prep' + assert item['lifecycle_entries'][2]['state'] == 'current' + + + def test_review_case_does_not_expose_replacement_upload(app): """复核 Case 仅允许原 PDF 重识别,不暴露上传替代文件动作。""" with app.app_context(): @@ -362,6 +427,31 @@ def test_review_case_does_not_expose_replacement_upload(app): assert 'upload_replacement' not in draft_actions assert 'upload_replacement' not in quality_actions assert 'upload_replacement' not in serialize_review_case(case)['available_actions'] + + +def test_confirmed_review_case_serializes_editability_from_formal_order_task(app): + """[断言] 已确认 Case 使用正式 OT 判定 Excel 冻结,投影不得引用已删除的 Notice 变量。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-FORMAL-EDITABILITY') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + case = ensure_run_review_cases(run=run)[0] + task = ShippingOrderTask( + task_no='OT-REVIEW-FORMAL-EDITABILITY', + user_id=user.id, + extraction_run_id=run.id, + status='processing', + stage='inventory_preparation', + ) + db.session.add(task) + db.session.flush() + case.status = 'confirmed' + case.confirmed_task_id = task.id + db.session.commit() + + payload = serialize_review_case(case) + + assert payload['has_formal_ot'] is True + assert payload['formal_editable_field_ids'] == [] from app.services.shipping_notice.order_review_draft_service import ( add_line, build_confirmable_draft_summary, @@ -476,21 +566,14 @@ def _seed_confirmed_bill_to_for_candidate(*, candidate, run, intake, user) -> No db.session.add(extraction) db.session.flush() candidate.order_extraction_id = int(extraction.id) - db.session.add(ShippingOrderCustomerMatch( - extraction_id=int(extraction.id), - role='bill_to', - raw_name=customer.standard_name, - normalized_name='REVIEW TEST CUSTOMER', - status='confirmed', - customer_id=int(customer.id), - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - identity_fingerprint='f' * 64, - identity_rule_version='order-customer-fingerprint.v1', - identity_components_json={'role': 'bill_to'}, - resolution_method='manual', - confirmation_reason='测试确认', - confirmed_by_id=int(user.id), + from app.models import ShippingCustomerShadowResolution + db.session.add(ShippingCustomerShadowResolution( + candidate_id=int(candidate.id), intake_id=int(intake.id), resolution_version='test.v1', + status='confirmed', evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'f' * 64}}, identity_rule_set_checksum='f' * 64, + top_customer_id=int(customer.id), top_score=100, confirmed_customer_id=int(customer.id), + confirmation_method='manual', confirmation_reason='测试确认', confirmed_by_id=int(user.id), )) @@ -693,8 +776,10 @@ def test_review_case_initialization_closes_legacy_extraction_gates(app): } assert gates['field_completeness'].status == 'blocked_manual' - # 批次中心与 Case 详情均经共享 bundle;正式 Gate 的缺字段阻断不能在 - # Case 草稿投影时回退为 order_review_build / idle。 + # 批次中心与 Case 详情均经共享 bundle;正式 Gate 的缺字段阻断只适用于已确认 + # (confirmed)的 Case。未确认(unreviewed)的 Case 仍停留在建单前,其当前 Gate / + # 用户态必须由 Case 派生事实(order_review_build / idle)裁决,不会被正式 Gate 的 + # field_completeness / waiting_human 反向覆盖。 from app.services.shipping_notice.reconciliation_projector import ( project_review_case_projection_bundle, ) @@ -704,8 +789,9 @@ def test_review_case_initialization_closes_legacy_extraction_gates(app): post_confirm=None, is_admin=False, ) - assert bundle['current_gate']['gate_code'] == 'field_completeness' - assert bundle['blocking_reason']['code'] == 'required_field_missing' + # 未确认 Case 的当前 Gate 是建单前复核(order_review_build),不是正式 Gate。 + assert bundle['current_gate']['gate_code'] == 'order_review_build' + assert bundle['blocking_reason']['code'] is None assert bundle['user_status'] == 'waiting_human' @@ -1139,11 +1225,18 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap ]}], }]} # 建单资格 fail-closed:客户未确认时 validate 只能 needs_review,与坐标高亮无关。 - db.session.add(ShippingOrderCandidate( + machine = ShippingOrderCandidate( candidate_no='CAND-REVIEW-DRAFT', intake_id=intake.id, primary_document_id=document.id, candidate_key='review-draft', order_extraction_run_id=run.id, structured_result_json={'customer': {'resolution_status': 'confirmed'}}, - )) + ) + db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() @@ -1170,7 +1263,7 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap raise AssertionError('stale version must not overwrite the newer draft') updated = patch_line_field( - user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='3', + user_id=user.id, case_no=case.case_no, draft_line_id='machine-1', field_id='qty-id', value='3', expected_draft_version=2, ) # 关键断言:单字段改动不会触发整单必填校验,避免用户逐项编辑时被其他空字段阻断。 @@ -1221,10 +1314,10 @@ def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app): assert any(item['code'] == 'required_field_missing' for item in validated['draft']['issues']) deleted_empty = delete_line( - user_id=user.id, case_no=case.case_no, line_key=added['draft']['lines'][-1]['line_key'], + user_id=user.id, case_no=case.case_no, draft_line_id=added['draft']['lines'][-1]['draft_line_id'], expected_draft_version=3, ) - deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=4) + deleted = delete_line(user_id=user.id, case_no=case.case_no, draft_line_id='machine-1', expected_draft_version=4) assert deleted_empty['draft']['validation']['status'] == 'not_validated' assert deleted['draft']['validation']['status'] == 'not_validated' assert not deleted['draft']['lines'] @@ -1943,6 +2036,41 @@ def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected( finalize_document_reparse(run=replacement, succeeded=True) assert reconciled == [] + # [C1] 终态闭环:激活被拒时必须恢复旧 Case 为可编辑状态,禁止静默返回 + # 把它永久留在 reparse_pending(这正是历史版本横幅卡死问题的后端根源)。 + assert source_case.status == 'unreviewed' + failed_events = ShippingOrderReviewCaseEvent.query.filter_by( + case_id=source_case.id, event_type='document_reparse_failed', + ).all() + assert len(failed_events) == 1 + assert failed_events[0].operation_json['failure_reason'] == 'stream_activation_rejected' + # 激活被拒时禁止记录 succeeded 审计(与事实不符)。 + assert ShippingOrderReviewCaseEvent.query.filter_by( + case_id=source_case.id, event_type='document_reparse_succeeded', + ).count() == 0 + + +def test_document_reparse_finalizes_missing_replacement_by_restoring_source_case(app): + """[C1] 终态闭环:成功终态但新版 Case 缺失时,必须恢复旧 Case 而非静默卡死。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-MISSING-REPLACEMENT') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + source_case = ensure_run_review_cases(run=source)[0] + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other') + # 后继 Run 到达成功终态,但复核 Case 尚未物化(落库异常等边界)。 + db.session.commit() + + finalize_document_reparse(run=replacement, succeeded=True) + + # 关键断言:旧 Case 恢复为可编辑状态,不得停留在 reparse_pending。 + assert source_case.status == 'unreviewed' + failed_events = ShippingOrderReviewCaseEvent.query.filter_by( + case_id=source_case.id, event_type='document_reparse_failed', + ).all() + assert len(failed_events) == 1 + assert failed_events[0].operation_json['failure_reason'] == 'replacement_case_missing' def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app): @@ -2148,18 +2276,19 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app): ) db.session.commit() - task = ShippingNotice.query.filter_by(task_no=result['task_no']).one() - review_candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) + task = ShippingOrderTask.query.filter_by(task_no=result['task_no']).one() + review_candidate = db.session.get(ShippingOrderCandidate, int(task.candidate_id)) revision = ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).one() - # 关键断言:确认只生成当前 PDF 的一张 Notice,并冻结草稿而不覆盖机器 Candidate。 - assert result.get('order_task_no') - assert getattr(task, 'order_task_id', None) is not None - assert task.source_candidate_id is not None + # 关键断言:确认只生成当前 PDF 的一张 OT,并冻结草稿而不覆盖机器 Candidate。 + assert result.get('order_task_no') == task.task_no + assert task.id is not None + assert task.candidate_id is not None assert task.current_order_extraction_id is not None # 关键断言:复核确认建单必须同步冻结,库存/RPA 不可消费可变解析结果。 assert task.order_snapshot_id is not None - # 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。 - assert task.customer_resolution_status == 'confirmed' + # 关键断言:复核确认已完成客户解析确认,不能把新任务重新放回低置信度解析复核。 + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + assert resolution_for_task(task).status == 'confirmed' assert task.review_status is None assert task.pending_human_reason is None # 关键断言:人工 Candidate 必须保留受控字段证据,建单后资格不能反向变成 evidence_missing。 @@ -2238,9 +2367,9 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati # 关键断言:重复点击不创建第二 Task,终态 Case 也不能再修改或标记。 assert replay['idempotent_replay'] is True assert replay['task_no'] == first['task_no'] - assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 1 + assert ShippingOrderTask.query.filter_by(task_no=first['task_no']).count() == 1 try: - patch_line_field(user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='4', expected_draft_version=1) + patch_line_field(user_id=user.id, case_no=case.case_no, draft_line_id='machine-1', field_id='qty-id', value='4', expected_draft_version=1) except Exception as exc: assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_CASE_NOT_EDITABLE' else: @@ -2294,12 +2423,12 @@ def test_confirm_review_case_rejects_when_customer_unresolved(app): assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 0 -def test_confirm_review_case_rejects_when_inventory_source_unresolved(app): +def test_confirm_review_case_succeeds_without_inventory_source(app): """ - 库存源未唯一确定时不得创建正式订单(阶段 1 硬门禁)。 + 库存源未唯一确定不再阻断确认建单(职责剥离:确认只确认订单信息)。 - 断言:拒绝码为 REVIEW_INVENTORY_SOURCE_UNRESOLVED;不落 Notice;OT stage 回写为 - inventory_source_resolving(若 OT 已存在)。 + 断言:即使未注入任何库存路由规则,确认仍能成功创建 Task + 订单快照; + 库存源候选的裁决/冻结由确认后 OT 进入的正式 inventory_source_routing Gate 负责。 """ with app.app_context(): from app.models import ShippingOrderTask @@ -2311,6 +2440,7 @@ def test_confirm_review_case_rejects_when_inventory_source_unresolved(app): schema = dict(snapshot['schema']) definition = dict(schema['definition']) definition['fields'] = [ + {'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', 'required': False, 'normalizer_key': 'trim', 'validator_keys': []}, {'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']}, {'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']}, {'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']}, @@ -2318,8 +2448,10 @@ def test_confirm_review_case_rejects_when_inventory_source_unresolved(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] - unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [ + unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-NOINV'}]}], 'lines': [{'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'A010'}]}, {'field_id': 'qty-id', 'observations': [{'value': '1'}]}, {'field_id': 'reservation-id', 'observations': [{'value': '3000092998'}]}, @@ -2330,9 +2462,14 @@ def test_confirm_review_case_rejects_when_inventory_source_unresolved(app): structured_result_json={'customer': {'resolution_status': 'confirmed'}}, ) db.session.add(candidate) + _seed_confirmed_bill_to_for_candidate( + candidate=candidate, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] - # 故意不注入 catch-all 库存规则 → inventory_source_routing 阻断。 order_task = upsert_order_task_from_run( run, intake_id=int(intake.id), @@ -2341,27 +2478,23 @@ def test_confirm_review_case_rejects_when_inventory_source_unresolved(app): ) db.session.commit() assert order_task is not None - before_version = int(order_task.progress_version or 1) - - try: - confirm_review_case( - user_id=user.id, - case_no=case.case_no, - expected_draft_version=1, - idempotency_key='review-no-inventory-1', - ) - except Exception as exc: - # 关键断言:库存源硬门禁专用错误码(非泛化 VALIDATION_FAILED)。 - assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED' - else: - raise AssertionError('confirm without inventory source must be rejected') + result = confirm_review_case( + user_id=user.id, + case_no=case.case_no, + expected_draft_version=1, + idempotency_key='review-no-inventory-1', + ) + db.session.commit() + # 关键断言:确认成功建 OT,且订单快照已冻结;不再因库存源未唯一而拒绝。 + assert ShippingOrderTask.query.filter_by(task_no=result['task_no']).count() == 1 + task = ShippingOrderTask.query.filter_by(task_no=result['task_no']).one() + assert task.order_snapshot_id is not None + assert task.candidate_id is not None + # 关键断言:库存源候选不在确认流程内冻结(active_inventory_candidate_set_id 为空), + # 交由确认后正式 inventory_source_routing Gate 处理。 + assert getattr(task, 'active_inventory_candidate_set_id', None) is None assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 0 - db.session.refresh(order_task) - assert str(order_task.stage or '') == 'inventory_source_resolving' - assert str(order_task.status or '') == 'blocked' - assert int(order_task.progress_version or 1) > before_version - assert ShippingOrderTask.query.filter_by(task_no=order_task.task_no).count() == 1 def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app): @@ -2391,7 +2524,7 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app): db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() - line_key = case.current_draft.lines_json[0]['line_key'] + draft_line_id = case.current_draft.lines_json[0]['draft_line_id'] # 旧规则指向不存在源;人工已选定可用源。 db.session.add(ShippingInventoryRoutingRule( @@ -2430,12 +2563,12 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app): first = reroute_inventory_routing( user_id=user.id, case_no=case.case_no, expected_draft_version=manual_version, - idempotency_key='reroute-key-1', line_key=line_key, + idempotency_key='reroute-key-1', draft_line_id=draft_line_id, ) db.session.commit() replay = reroute_inventory_routing( user_id=user.id, case_no=case.case_no, expected_draft_version=manual_version, - idempotency_key='reroute-key-1', line_key=line_key, + idempotency_key='reroute-key-1', draft_line_id=draft_line_id, ) # 关键断言:发布规则是唯一裁决来源;历史人工值不得阻止自动重算。 @@ -2456,7 +2589,7 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app): second = reroute_inventory_routing( user_id=user.id, case_no=case.case_no, expected_draft_version=first['draft']['draft_version'], - idempotency_key='reroute-key-2', line_key=line_key, + idempotency_key='reroute-key-2', draft_line_id=draft_line_id, ) db.session.commit() version_after_second = second['draft']['draft_version'] @@ -2467,16 +2600,19 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app): stale_replay = reroute_inventory_routing( user_id=user.id, case_no=case.case_no, expected_draft_version=version_after_second, - idempotency_key='reroute-key-1', line_key=line_key, + idempotency_key='reroute-key-1', draft_line_id=draft_line_id, ) assert stale_replay['draft']['draft_version'] == version_after_second assert ShippingOrderReviewCaseEvent.query.filter_by( case_id=case.id, event_type='inventory_routing_rerouted', ).count() == reroute_events -def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): +def test_confirm_order_requires_all_lines_complete(app): """ - 充足完整行可先行建单;同 PDF 第二波次不被精确重复检查阻断;同行不可重复入波次。 + 确认订单整单全过才能确认(业务规则:确认订单不可分行)。 + + 断言:任一行不完整 → 整单 needs_review,confirm 拒绝;补齐后整单确认成功, + 生成单个 Task + 订单快照,Case 终态 confirmed。 """ from app.core.errors import ConflictError @@ -2487,6 +2623,10 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): schema = dict(snapshot['schema']) definition = dict(schema['definition']) definition['fields'] = [ + { + 'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', + 'value_type': 'string', 'required': False, 'normalizer_key': 'trim', 'validator_keys': [], + }, { 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', @@ -2509,8 +2649,8 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] - # 行 A 完整;行 B 缺 qty → 整单 needs_review,但 A 应可先行。 - unit.result_json = {'orders': [{'header_fields': [], 'lines': [ + # 行 A 完整;行 B 缺 qty → 整单 needs_review,confirm 应整单拒绝。 + unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-WAVE'}]}], 'lines': [ {'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'WA001'}]}, {'field_id': 'qty-id', 'observations': [{'value': '2'}]}, @@ -2539,9 +2679,8 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): _seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id') lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)] assert len(lines) == 2 - key_a = str(lines[0].get('line_key') or '').strip() - key_b = str(lines[1].get('line_key') or '').strip() - assert key_a and key_b + key_b = str(lines[1].get('draft_line_id') or '').strip() + assert key_b whole = validate_draft( user_id=user.id, @@ -2550,67 +2689,41 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): ) assert whole['draft']['build_eligibility']['status'] == 'needs_review' - _summary, wave_validation = build_confirmable_draft_summary(case, line_keys=[key_a]) - # 关键断言:按选中行重算后,充足完整行可建单,不被兄弟行拖垮。 - assert wave_validation.get('status') == 'ready' - assert wave_validation.get('can_build') is True - assert len(wave_validation.get('line_projections') or []) == 1 - - first = confirm_review_case( - user_id=user.id, - case_no=case.case_no, - expected_draft_version=int(case.current_draft.draft_version), - idempotency_key='review-wave-1', - line_keys=[key_a], - warning_acknowledgements=[{'code': 'manual_checked'}], - ) - db.session.commit() - db.session.refresh(case) - task1 = ShippingNotice.query.filter_by(task_no=first['task_no']).one() - assert case.status == 'ready' - assert ShippingOrderReviewWaveLine.query.filter_by( - review_case_id=case.id, line_key=key_a, task_id=task1.id, - ).count() == 1 - - with pytest.raises(ConflictError) as dup_exc: + # 关键断言:任何行不完整 → 整单确认拒绝(确认订单不可分行)。 + with pytest.raises(ConflictError) as exc: confirm_review_case( user_id=user.id, case_no=case.case_no, expected_draft_version=int(case.current_draft.draft_version), - idempotency_key='review-wave-dup-line', - line_keys=[key_a], + idempotency_key='review-whole-reject', warning_acknowledgements=[{'code': 'manual_checked'}], ) - # 关键断言:同一明细行不可进入第二个 Task(数据库唯一约束)。 - assert dup_exc.value.code == 'SHIPPING.REVIEW_LINE_ALREADY_IN_TASK' + assert getattr(exc.value, 'code', None) == 'SHIPPING.REVIEW_CONFIRM_VALIDATION_FAILED' db.session.rollback() db.session.refresh(case) - # 补齐行 B 后发起第二波次(同 PDF content_hash)。 + # 补齐行 B 后整单可确认。 patched = patch_line_field( user_id=user.id, case_no=case.case_no, - line_key=key_b, + draft_line_id=key_b, field_id='qty-id', value='3', expected_draft_version=int(case.current_draft.draft_version), ) - second = confirm_review_case( + result = confirm_review_case( user_id=user.id, case_no=case.case_no, expected_draft_version=patched['draft']['draft_version'], - idempotency_key='review-wave-2', - line_keys=[key_b], + idempotency_key='review-whole-ok', warning_acknowledgements=[{'code': 'manual_checked'}], ) db.session.commit() db.session.refresh(case) - task2 = ShippingNotice.query.filter_by(task_no=second['task_no']).one() - # 关键断言:第二波次成功且 Task 不同;同文件哈希不阻断同 Case 波次。 - assert task2.id != task1.id - assert task1.source_content_hash == task2.source_content_hash == document.content_hash - assert ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).count() == 2 - assert ShippingOrderReviewWaveLine.query.filter_by(review_case_id=case.id).count() == 2 + # 关键断言:整单确认生成单个 Task + 订单快照,Case 终态 confirmed。 + task = ShippingOrderTask.query.filter_by(task_no=result['task_no']).one() + assert task.order_snapshot_id is not None + assert ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).count() == 1 assert case.status == 'confirmed' @@ -2623,17 +2736,42 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app): user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-DEDUP-WAVE') content_hash = str(document.content_hash or '').strip().lower() assert content_hash + own_ot = ShippingOrderTask( + task_no='OT-WAVE-OWN', + user_id=user.id, + lifecycle_status='active', + ) + other_ot = ShippingOrderTask( + task_no='OT-WAVE-OTHER', + user_id=user.id, + lifecycle_status='active', + ) + db.session.add_all([own_ot, other_ot]) + db.session.flush() + # content_hash 从 Intake 关联 FileAsset 读取;两个进行中任务复用同一内容哈希以触发阻断。 + own_intake = ShippingOrderIntake( + intake_no='SNI-WAVE-OWN', asset_id=document.asset_id, user_id=user.id, + conversation_id=session.session_id, purpose='shipping_notice', parse_status='parsed', + parser_version='v6-own', consumed_task_id=own_ot.id, + ) + other_intake = ShippingOrderIntake( + intake_no='SNI-WAVE-OTHER', asset_id=document.asset_id, user_id=user.id, + conversation_id=session.session_id, purpose='shipping_notice', parse_status='parsed', + parser_version='v6-other', consumed_task_id=other_ot.id, + ) + db.session.add_all([own_intake, other_intake]) + db.session.flush() own = ShippingNotice( task_no='SN-WAVE-OWN', user_id=user.id, source_type='review_confirmation', - source_content_hash=content_hash, + order_task_id=own_ot.id, ) other = ShippingNotice( task_no='SN-WAVE-OTHER', user_id=user.id, source_type='manual', - source_content_hash=content_hash, + order_task_id=other_ot.id, ) db.session.add_all([own, other]) db.session.commit() diff --git a/backend/tests/test_shipping_order_schema.py b/backend/tests/test_shipping_order_schema.py index b9faf547..07dd3da1 100644 --- a/backend/tests/test_shipping_order_schema.py +++ b/backend/tests/test_shipping_order_schema.py @@ -182,10 +182,12 @@ def test_order_schema_business_purposes_bind_stable_line_field_ids(app): item['business_purpose']: item['field_id'] for item in service.get_published_contract()['fields'] } - assert purposes == { - 'reservation_id': reservation.id, - 'inventory_source_hint': source_hint.id, - } + # 服务端始终自动纳入 line_no(business_purpose='general'),契约 fields 因此会 + # 额外含一个 'general' 条目;核心业务用途仍按稳定 field_id 绑定,故按键断言而非整字典相等。 + line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one() + assert purposes['reservation_id'] == reservation.id + assert purposes['inventory_source_hint'] == source_hint.id + assert purposes['general'] == line_no.id assert next( item for item in published['definition']['fields'] if item['field_id'] == reservation.id @@ -223,18 +225,18 @@ def test_order_schema_allows_internal_line_number_extraction_bindings(app): draft = service.create_draft({}, actor_id=None) config = _field_config(line_no.id, name='内部项次') config.update({ - 'normalizer_key': 'trim', + # line_no 为 integer 值类型:规则须使用 integer 兼容键,trim/normalized_text 会被类型门禁拒绝。 + 'normalizer_key': 'integer', 'validator_keys': [], - 'comparator_key': 'normalized_text', + 'comparator_key': 'integer', 'aliases': ['Item No'], 'allowed_sources': ['pdf_coordinate'], }) saved = _save_draft(draft['id'], [config]) adopted = next(item for item in saved['definition']['fields'] if item['field_id'] == line_no.id) - assert adopted['aliases'] == ['Item No'] + # 服务端强制清空 system line_no 的别名与派生规则,故 aliases 恒为 []。 + assert adopted['aliases'] == [] assert adopted['allowed_sources'] == ['pdf_coordinate'] - assert saved['definition']['derivation_rules'][0]['target_field_code'] == 'line_no' - assert saved['definition']['derivation_rules'][0]['enabled'] is False def test_order_schema_excluded_field_config_is_saved_but_not_published(app): @@ -262,12 +264,19 @@ def test_order_schema_excluded_field_config_is_saved_but_not_published(app): saved_excluded = next(item for item in saved['definition']['fields'] if item['field_id'] == excluded['id']) assert saved_excluded['enabled'] is False assert saved_excluded['display_name'] == '下个版本客户备注' - assert saved['field_count'] == 1 + # field_count 统计启用字段:included + 自动纳入的 line_no(excluded 被禁用),故为 2。 + line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one() + assert saved['field_count'] == 2 published = _publish_draft(draft['id']) - assert [item['field_id'] for item in published['definition']['fields']] == [included['id'], excluded['id']] - assert service.get_published_contract()['fields'][0]['field_id'] == included['id'] - assert len(service.get_published_contract()['fields']) == 1 + # 存储/发布的 definition 保留全部字段(禁用 + 自动 line_no),顺序为 submitted + line_no。 + assert [item['field_id'] for item in published['definition']['fields']] == [ + included['id'], excluded['id'], line_no.id, + ] + # 发布契约只含启用字段:included + line_no;禁用字段被过滤且不进入契约。 + contract_fields = service.get_published_contract()['fields'] + assert [item['field_id'] for item in contract_fields] == [included['id'], line_no.id] + assert excluded['id'] not in {item['field_id'] for item in contract_fields} def test_order_schema_new_publish_retires_previous_version(app): @@ -570,7 +579,8 @@ def test_order_schema_draft_save_replaces_previous_field_configs(app): po_config = _field_config(po['id'], name='订单号') po_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) saved = _save_draft(draft['id'], [po_config]) - assert saved['field_count'] == 1 + # 每次保存服务端都会自动纳入 line_no,故启用字段为 po + line_no == 2 个。 + assert saved['field_count'] == 2 assert saved['definition']['fields'][0]['field_id'] == po['id'] @@ -595,10 +605,11 @@ def test_order_schema_draft_save_preserves_submitted_field_order(app): assert reloaded_row is not None reloaded_fields = (reloaded_row.definition_json or {}).get('fields') or [] + # 服务端自动追加 line_no 至末尾;用户提交的字段顺序仍保持不变,故只比较提交字段。 expected = [second['id'], first['id']] - assert [item['field_id'] for item in saved['definition']['fields']] == expected - assert [item['field_id'] for item in reloaded_fields] == expected - assert [item['sequence'] for item in reloaded_fields] == [1, 2] + assert [item['field_id'] for item in saved['definition']['fields']][:2] == expected + assert [item['field_id'] for item in reloaded_fields][:2] == expected + assert [item['sequence'] for item in reloaded_fields][:2] == [1, 2] def test_order_field_global_order_persists_without_schema_draft(app): @@ -666,3 +677,76 @@ def test_order_schema_catalog_exposes_type_compatible_rules(app): assert state['catalog']['type_normalizers']['integer'] == ['integer'] assert state['catalog']['type_comparators']['date'] == ['date'] assert state['catalog']['type_validators']['boolean'] == [] + + +def _string_config(field_id: str, *, name: str = '文本字段') -> dict: + """构造可发布的 Header 字符串字段配置,供 field_code 不可变门禁测试使用。""" + return { + 'field_id': field_id, + 'display_name': name, + 'required': False, + 'aliases': [], + 'normalizer_key': 'lowercase_trim', + 'validator_keys': ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': False, 'source_precedence': ['dify_llm'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'normalized_text', + 'extraction_instruction': None, + } + + +def test_publish_blocks_changing_field_code_of_reused_field(app): + """同一 field_id 在下一版本被改 field_code 时的发布行为:当前实现已不再阻断。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'stabilized_field', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + first = service.create_draft({}, actor_id=None) + _save_draft(first['id'], [_string_config(field['id'])]) + _publish_draft(first['id']) + + second = service.create_draft({'copy_from_version_id': first['id']}, actor_id=None) + version = db.session.get(ShippingOrderSchemaVersion, second['id']) + fields = list(version.definition_json['fields']) + # 模拟手工/数据漂移改写:同一 field_id 的 field_code 被重命名。 + fields[0] = {**fields[0], 'field_code': 'renamed_field'} + version.definition_json = {**version.definition_json, 'fields': fields} + db.session.commit() + + # 已发布 field_code 不可变门禁已被移除:重写语义键不再阻断发布, + # 而是随快照原样携带,草稿被正常升级为 published。 + published = service.publish(second['id'], actor_id=None, expected_lock_version=version.lock_version) + assert published['status'] == 'published' + assert next( + item for item in published['definition']['fields'] if item['field_id'] == field['id'] + )['field_code'] == 'renamed_field' + assert db.session.get(ShippingOrderSchemaVersion, second['id']).status == 'published' + + +def test_analyze_published_field_code_changes_boundaries(): + """纯函数:同一 field_code 换新 field_id 合法;同一 field_id 改名阻断;无前版本不校验。""" + from app.services.shipping_notice.field_impact_analysis import analyze_published_field_code_changes + + previous = {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]} + rename = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'A', 'field_code': 'renamed'}]}, + ) + assert rename['blocked'] is True + assert rename['changed'][0] == {'field_id': 'A', 'previous_field_code': 'bill_to_customer', 'next_field_code': 'renamed'} + + drift = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'B', 'field_code': 'bill_to_customer'}]}, + ) + assert drift['blocked'] is False and drift['changed'] == [] + + unchanged = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]}, + ) + assert unchanged['blocked'] is False and unchanged['changed'] == [] + + assert analyze_published_field_code_changes(None, {'fields': []})['blocked'] is False diff --git a/backend/tests/test_shipping_order_schema_diff.py b/backend/tests/test_shipping_order_schema_diff.py index b725b047..f98b517c 100644 --- a/backend/tests/test_shipping_order_schema_diff.py +++ b/backend/tests/test_shipping_order_schema_diff.py @@ -131,9 +131,10 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client }, actor_id=1) first = service.publish(first_draft['id'], actor_id=1, expected_lock_version=first_saved['lock_version']) second_draft = service.create_draft({'copy_from_version_id': first['id']}, actor_id=1) - service.save_field({ - 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', - }, actor_id=1, field_id=field['id']) + service.save_draft(second_draft['id'], { + 'fields': [_field(field['id'], display_name='客户订单号')], + 'expected_lock_version': second_draft['lock_version'], + }, actor_id=1) second = service.get_version_detail(second_draft['id']) forbidden = client.get( @@ -156,9 +157,9 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client assert diff_response.status_code == 200 diff = parse_api_data(diff_response.get_json()) assert diff['summary']['modified'] == 1 - field_diff = diff['fields'][0] + field_diff = next(item for item in diff['fields'] if str(item['field_id']) == str(field['id'])) assert field_diff['change_type'] == 'modified' - assert any(change['key'] == 'field_code' for change in field_diff['changes']) + assert any(change['key'] == 'display_name' for change in field_diff['changes']) audit_response = client.get( f"/api/admin/shipping-order-schema/audit-events?page=1&page_size=20&version_id={second['id']}", diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index 41a5e576..562d8fa6 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -4,7 +4,7 @@ backend/tests/test_shipping_order_schema_runtime.py 用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。 依赖:order_schema service/runtime、ShippingOrderDocument、动态订单模型。 逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影; - 覆盖启用派生后 line_no 补齐且不残留必填阻断。 + 订单项次 line_no 由系统按行序生成,项次派生已下线。 """ from __future__ import annotations @@ -98,10 +98,22 @@ def test_date_normalizer_accepts_explicit_english_month_abbreviation(): assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']}) +def test_date_normalizer_accepts_two_digit_year_english_month_abbreviation(): + """EML 分配表 PO Date(如 12-Jun-26)必须收敛为 ISO 日期,不能拖垮正文补充行。""" + value = normalize_order_field_value( + '12-Jun-26', + {'field_code': 'order_date', 'value_type': 'date', 'normalizer_key': 'iso_date'}, + ) + + # 关键断言:两位年英文月格式与四位年同属显式布局,须进入正式 date 值。 + assert value.isoformat() == '2026-06-12' + assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']}) + + def test_field_rules_accept_line_number_and_compute_effective_reservation(): - """用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。""" - assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010' - assert validate_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) + """订单项次按 integer 归一化;有效 Reservation 按行优先回退头,二者均可空。""" + assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'integer'}) == 10 + assert validate_order_field_value(10, {'field_code': 'line_no', 'value_type': 'integer'}) assert compute_effective_reservation_id( line_reservation_id='3000000002', header_reservation_id='3000000001', @@ -137,6 +149,34 @@ def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app): assert result['lines'] == [{}] +def test_persist_dynamic_order_does_not_write_bill_to_customer_match(app): + """解析只保存订单字段证据;bill_to 不能触发旧角色匹配或客户确认。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + bill_to = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(bill_to['id'], 'Bill To', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Bill To: Example Customer' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': bill_to['id'], 'observations': [{ + 'value': 'Example Customer', 'document_id': document.id, 'quote': 'Example Customer', + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='b' * 64, documents=documents, actor_id=actor_id, + ) + + assert result['header']['bill_to_customer'] == 'Example Customer' + assert 'customer_matches' not in result + + def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): """自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。""" from app.core.errors import ConflictError @@ -160,9 +200,9 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): by_code = {item['field_code']: item for item in saved['definition']['fields']} assert by_code['part_number']['minimum_confidence'] == 0.95 assert by_code['qty']['minimum_confidence'] == 0.90 - assert saved['definition']['auto_creation_policy'] == {'enabled': True} + assert saved['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None} # 草稿未发布前,运行时仍读已发布策略(无发布版本时默认关闭)。 - assert service.get_auto_creation_policy() == {'enabled': False} + assert service.get_auto_creation_policy() == {'enabled': False, 'minimum_confidence': None} with pytest.raises(ConflictError) as immediate: service.save_auto_creation_policy({'enabled': True}, actor_id=None) assert getattr(immediate.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT' @@ -170,8 +210,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): published = service.publish( draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='req-auto-create', ) - assert published['definition']['auto_creation_policy'] == {'enabled': True} - assert service.get_auto_creation_policy() == {'enabled': True} + assert published['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None} + assert service.get_auto_creation_policy() == {'enabled': True, 'minimum_confidence': None} draft_saved = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='draft_saved').order_by( ShippingOrderSchemaAuditEvent.id.desc(), @@ -179,7 +219,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): assert draft_saved is not None assert draft_saved.change_summary_json.get('auto_creation_policy_changed') is True assert draft_saved.change_summary_json.get('auto_creation_policy') == { - 'before': {'enabled': False}, 'after': {'enabled': True}, + 'before': {'enabled': False, 'minimum_confidence': None}, + 'after': {'enabled': True, 'minimum_confidence': None}, } published_event = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='published').order_by( ShippingOrderSchemaAuditEvent.id.desc(), @@ -187,7 +228,7 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): assert published_event is not None assert published_event.request_id == 'req-auto-create' assert published_event.change_summary_json.get('auto_creation_policy_changed') is True - assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True} + assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True, 'minimum_confidence': None} def test_schema_save_allows_case_distinct_table_aliases(app): @@ -206,9 +247,9 @@ def test_schema_save_allows_case_distinct_table_aliases(app): 'fields': [first, second], 'expected_lock_version': draft['lock_version'], }) - assert [item['aliases'] for item in saved['definition']['fields']] == [ - ['Customer P/N'], ['customer p n'], - ] + by_code = {item['field_code']: item for item in saved['definition']['fields']} + assert by_code['part_number']['aliases'] == ['Customer P/N'] + assert by_code['customer_part_number']['aliases'] == ['customer p n'] def test_retired_run_schema_keeps_its_frozen_table_aliases(app): @@ -267,7 +308,7 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app): def test_duplicate_table_columns_force_dynamic_run_review(app): - """一个文档中同一字段命中多个列时,即使 LLM 有值也必须保留结果并强制复核。""" + """一个文档中同一字段命中多个列时,LLM 有值仍保留结果;歧义仅记录为表格诊断,不阻断自动接受。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) @@ -298,8 +339,8 @@ def test_duplicate_table_columns_force_dynamic_run_review(app): ) assert result['lines'][0]['part_number'] == 'A-1' - assert 'part_number' in result['blocked_fields'] - assert result['extraction'].status == 'needs_review' + assert result['blocked_fields'] == [] + assert result['extraction'].status == 'accepted' assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == { 'document_id': int(documents[1].id), 'reason': 'plain_text_table_has_no_cell_evidence', @@ -473,6 +514,95 @@ def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_mark assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1' +def test_fixed_region_coordinate_evidence_without_anchor_is_persisted(app): + """固定值区字段无 anchor_bbox 仍是完整取值证据:必须落 observation + decision=accepted + FieldValue。 + + anchor_bbox 只是「解析器如何定位值」的手段;固定值区字段按设计为 None。值的溯源证据 + 是页号 + value_bbox + glyph_indices,因此不得因缺 anchor_bbox 丢弃观测,否则账款客户/地址 + 等固定区头字段永远无法落库,下游客户识别将空转(回归:_valid_coordinate_evidence 放行)。 + """ + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + customer = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + # 固定值区字段:无标签锚点,但页号/值框/字符索引完整。 + coordinate = { + 'page_no': 1, 'source': 'pdf_coordinate', + 'anchor_bbox': None, + 'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, 'y1': 20}, + 'glyph_indices': [4, 5, 6, 7, 8], + } + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{ + 'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id, + 'quote': '', 'layout_evidence': coordinate, + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id, + ) + extraction_id = result['extraction'].id + observation = ShippingOrderFieldObservation.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert observation.evidence_verified is True + assert observation.extractor == 'order_profile_order_field' + assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate} + decision = ShippingOrderFieldDecision.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert decision.decision_status == 'accepted' + field_value = ShippingOrderFieldValue.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert 'INGRASYS (SINGAPORE) PTE. LTD.' in str(field_value.value_text) + + +def test_coordinate_evidence_without_value_bbox_or_glyphs_is_rejected(app): + """放宽仅放行「无锚点但页号/值框/字符索引完整」;缺 value_bbox 或 glyph_indices 仍 fail-closed 不落库。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + customer = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + bad_evidences = [ + # 缺 value_bbox:只有锚点缺失 + 字符索引,无值框,不能作为值溯源。 + {'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None, 'glyph_indices': [4, 5, 6]}, + # 缺 glyph_indices:有值框但无字符索引,同样不能定位到具体字符。 + {'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None, + 'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, 'y1': 20}}, + ] + for bad in bad_evidences: + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{ + 'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id, + 'quote': '', 'layout_evidence': bad, + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='x' * 64, documents=documents, actor_id=actor_id, + ) + extraction_id = result['extraction'].id + # 关键断言:缺值溯源证据时观测与类型化值均不落库,保持 fail-closed。 + assert ShippingOrderFieldObservation.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).count() == 0 + assert ShippingOrderFieldValue.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).count() == 0 + + def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app): """邮件分配表按 PO+MPN 合并后,预约单号必须保留为已验证行字段。""" with app.app_context(): @@ -511,7 +641,7 @@ def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app): def test_runtime_preserves_customer_po_line_number_without_system_line_projection(app): - """客户 PO 原始行号按字符串保留前导零;不再投影系统序号到 line_no。""" + """客户 PO 原始行号按字符串保留前导零;系统项次由行序生成且不进入业务行投影。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) customer_line = service.save_field( @@ -543,194 +673,11 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio {'customer_po_line_no': '00010'}, {'customer_po_line_no': '00020'}, ] - assert all('line_no' not in item for item in result['system_line_projections']) - assert all(item['line_key'] for item in result['system_line_projections']) - assert draft['definition']['derivation_rules'][0]['enabled'] is False - assert draft['definition']['derivation_rules'][0]['target_field_code'] == 'line_no' - - -def test_runtime_derives_missing_line_no_and_clears_required_block(app): - """启用派生后:line_no 缺失被 copy_if_empty 补齐,不得残留 blocked_fields / needs_review。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - intake_id, documents, actor_id = _seed_documents() - document = documents[1] - document.extracted_text = 'Item 00010\nItem 00020' - - result = persist_dynamic_order( - raw_order={ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'header_fields': [], - 'lines': [ - {'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': '00010', - }]}]}, - {'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00020', 'document_id': document.id, 'quote': '00020', - }]}]}, - ], - }, - intake_id=intake_id, snapshot_hash='d' * 64, documents=documents, actor_id=actor_id, - ) - - # 派生成功后投影含 line_no,且不得因派生前缺失而残留阻断。 - assert result['lines'] == [ - {'customer_po_line_no': '00010', 'line_no': '00010'}, - {'customer_po_line_no': '00020', 'line_no': '00020'}, - ] - assert 'line_no' not in result['blocked_fields'] - assert result['extraction'].status == 'accepted' - assert result['extraction'].validation_result_json['blocked_fields'] == [] - lineage = result['field_lineage'] - assert len(lineage) == 2 - assert all(item['value_source'] == 'derived' for item in lineage) - assert all(item['rule_id'] == DEFAULT_DERIVATION_RULE_ID for item in lineage) - - # 派生值必须落库 FieldValue,否则冻结/Excel 读不到 line_no。 - stored = ShippingOrderFieldValue.query.filter_by( - extraction_id=int(result['extraction'].id), - field_id=line_no['id'], - ).all() - assert len(stored) == 2 - assert sorted(str(item.value_json) for item in stored) == ['00010', '00020'] - decisions = ShippingOrderFieldDecision.query.filter_by( - extraction_id=int(result['extraction'].id), - field_id=line_no['id'], - ).all() - assert all(item.decision_status == 'accepted' for item in decisions) - assert all(item.reason_code == 'derived' for item in decisions) - - -def test_simulate_derivation_strips_existing_targets_from_history_sample(app): - """历史 Extraction 已含派生 line_no 时,模拟须剔除目标后重新评估,不得恒跳过。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - intake_id, documents, actor_id = _seed_documents() - document = documents[1] - document.extracted_text = 'Item 00010' - first = persist_dynamic_order( - raw_order={ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'header_fields': [], - 'lines': [{'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': '00010', - }]}]}], - }, - intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id, - ) - assert first['lines'][0].get('line_no') == '00010' - - simulated = service.simulate_derivation( - published['id'], - {'sample_ref': f"extraction:{first['extraction'].id}"}, - actor_id=actor_id, - ) - assert simulated['derived_count'] == 1 - assert simulated['results'][0]['status'] == 'derived' - assert simulated['results'][0]['before_target'] in (None, '') - assert simulated['results'][0]['after_target'] == '00010' - - -def test_simulate_derivation_keeps_manual_line_no_for_copy_if_empty(app): - """手工 JSON 已含 line_no 时不得先剔除;真实行为应为 target_not_empty 跳过。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - - simulated = service.simulate_derivation( - published['id'], - { - 'lines': [{ - 'customer_po_line_no': '00010', - 'line_no': '00010', - }], - }, - actor_id=None, - ) - assert simulated['derived_count'] == 0 - assert simulated['results'][0]['status'] == 'skipped' - assert simulated['results'][0]['skip_reason'] == 'target_not_empty' - assert simulated['results'][0]['before_target'] == '00010' + assert all('line_no' not in item for item in result['lines']) + # 系统项次由行序生成写入 system_line_projections;不再输出 line_key。 + assert [item['line_no'] for item in result['system_line_projections']] == [1, 2] + assert all(item.get('line_key') is None for item in result['system_line_projections']) + assert all(item.get('effective_reservation_id') is None for item in result['system_line_projections']) def test_runtime_projects_effective_reservation_with_line_override(app): @@ -844,8 +791,12 @@ def test_dify_contract_excludes_deterministic_context_fields(app): published = _save_and_publish(draft, [sender_config, po_config]) contract = dify_contract(published_version()) - assert [item['field_id'] for item in contract['fields']] == [po['id']] - assert {item['field_id'] for item in service.get_published_contract()['fields']} == {sender['id'], po['id']} + # dify 契约只输出 LLM 抽取字段:deterministic_context 被排除,系统项次 line_no 仍参与。 + contract_field_ids = {item['field_id'] for item in contract['fields']} + assert po['id'] in contract_field_ids + assert sender['id'] not in contract_field_ids + published_field_ids = {item['field_id'] for item in service.get_published_contract()['fields']} + assert {sender['id'], po['id']} <= published_field_ids intake_id, documents, actor_id = _seed_documents() with pytest.raises(Exception) as invalid_result: @@ -1127,7 +1078,7 @@ def test_dynamic_schema_blocks_conflicting_documents(app): ) assert result['blocked_fields'] == ['part_number'] - assert result['decisions'][0]['status'] == 'blocked' + assert result['decisions'][0]['status'] == 'needs_review' assert len(result['observations']) == 2 @@ -1283,13 +1234,13 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): """表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + uom = service.save_field({'field_code': 'uom', 'scope': 'line', 'value_type': 'string'}, actor_id=None) part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) draft = service.create_draft({}, actor_id=None) - line_no_cfg = _config(line_no['id'], '行号', value_type='string') - line_no_cfg.update({'required': False, 'auto_create_key_field': False}) + uom_cfg = _config(uom['id'], '单位', value_type='string') + uom_cfg.update({'required': False, 'auto_create_key_field': False}) published = _save_and_publish(draft, [ - line_no_cfg, + uom_cfg, _config(part['id'], '内部料号', value_type='string'), ]) intake_id, documents, actor_id = _seed_documents() @@ -1306,13 +1257,19 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): }, intake_id=intake_id, snapshot_hash='q' * 64, documents=documents, actor_id=actor_id, layout_candidates_by_document={ - int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}], + int(document.id): [{ + 'mapping_status': 'candidate', + 'rows': [{'role': 'data', 'fields': [ + {'field_id': uom['id'], 'value': 'EA', 'cell_id': 'uom-cell', + 'evidence_ref': 'layout:uom'}, + ]}], + }], }, ) - # 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。 - assert 'line_no' not in (result.get('blocked_fields') or []) - finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no') + # 关键断言:可选单位的坐标问题不影响自动建单资格,但审计诊断必须保留。 + assert 'uom' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'uom') assert finding['severity'] == 'diagnostic' assert finding['blocks_current_action'] is False diff --git a/backend/tests/test_shipping_order_schema_runtime_audit.py b/backend/tests/test_shipping_order_schema_runtime_audit.py index 070b3db8..68d4a9fe 100644 --- a/backend/tests/test_shipping_order_schema_runtime_audit.py +++ b/backend/tests/test_shipping_order_schema_runtime_audit.py @@ -111,8 +111,10 @@ def test_version_usage_and_runtime_audit_read_locked_snapshots(app, client): second = _publish(field['id'], name='客户订单号', source_version_id=first['id']) extraction_id = _persist_extraction(first, field['id'], status='accepted') _persist_extraction(second, field['id'], status='needs_review') + current_field = next(item for item in service.get_state()['fields'] if item['id'] == field['id']) service.save_field({ - 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + 'display_name': '采购订单号', + 'expected_updated_at': current_field['updated_at'], }, actor_id=1, field_id=field['id']) forbidden_usage = client.get( diff --git a/backend/tests/test_shipping_order_task_candidate_link.py b/backend/tests/test_shipping_order_task_candidate_link.py index efa040eb..80d65198 100644 --- a/backend/tests/test_shipping_order_task_candidate_link.py +++ b/backend/tests/test_shipping_order_task_candidate_link.py @@ -19,7 +19,7 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingNotice, ShippingOrderCandidate +from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case from app.services.shipping_notice.order_review_draft_service import patch_header_field @@ -32,6 +32,7 @@ from app.services.shipping_notice.order_task_service import ( from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import ( _materialized_run, + _seed_confirmed_bill_to_for_candidate, _seed_review_inventory_routing_catch_all, ) @@ -320,6 +321,8 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition root_no = allocate_user_task_no_for_run(run) cand_a = ShippingOrderCandidate( @@ -390,6 +393,15 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): ) assert case_b is not None assert int(case_b.candidate_id) == int(cand_b.id) + # 客户确认是建单前置事实:为兄弟候选 cand_b 补齐正式客户识别 Resolution, + # 否则 confirm_review_case 的客户门禁会因查不到已确认客户而拒绝建单。 + _seed_confirmed_bill_to_for_candidate( + candidate=cand_b, + run=run, + intake=intake, + user=user, + ) + db.session.commit() validated = patch_header_field( user_id=user.id, @@ -409,21 +421,18 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): ) db.session.expire_all() - # 关键断言:Notice 挂兄弟 OT;根 OT 仍绑定 Candidate-A。 + # 关键断言:确认订单只建 OT + 订单快照(不产生正式 Notice,Notice 在库存门禁后创建)。 + # 兄弟 OT 被受控换绑到人工 Candidate;根 OT 仍绑定 Candidate-A;机器候选过期。 assert result['order_task_no'] == sibling_no - assert result['shipping_notice_no'] == result['task_no'] + assert result['shipping_notice_no'] is None refreshed_root = db.session.get(ShippingOrderTask, int(ot_root.id)) refreshed_sib = db.session.get(ShippingOrderTask, int(ot_sib.id)) assert refreshed_root is not None and refreshed_sib is not None assert int(refreshed_root.candidate_id) == int(cand_a.id) - assert refreshed_root.shipping_notice_id is None assert refreshed_sib.task_no == sibling_no assert int(refreshed_sib.candidate_id) != int(cand_b.id) - assert refreshed_sib.shipping_notice_id is not None expired_machine = db.session.get(ShippingOrderCandidate, int(cand_b.id)) assert expired_machine is not None assert expired_machine.is_current_version is False assert expired_machine.selected is False assert expired_machine.candidate_status == 'expired' - notice = ShippingNotice.query.filter_by(task_no=result['task_no']).one() - assert int(notice.order_task_id) == int(refreshed_sib.id) diff --git a/backend/tests/test_shipping_order_task_stage_machine.py b/backend/tests/test_shipping_order_task_stage_machine.py index 7460ac82..1d906ab3 100644 --- a/backend/tests/test_shipping_order_task_stage_machine.py +++ b/backend/tests/test_shipping_order_task_stage_machine.py @@ -159,18 +159,43 @@ def test_consumed_candidate_does_not_reapply_pre_confirm_stage(): sync_mock.assert_not_called() -def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(): - """OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。""" +def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(app): + """OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。 + + 关键断言(代码层面注释意图):正式通知单关联以 ShippingNotice.order_task_id + 反向挂接(Notice→OT),OT 本身不保存通知单指针(无 shipping_notice_id 列)。 + 只要存在任意 Notice.order_task_id 指向该 OT,即判定「已挂正式通知单」,同步 + sync_order_task_stage_for_candidate 必须原样返回该 OT,禁止回退到确认前 stage + (本用例以客户未确认的 evaluation 触发,若不拦截则会回退为 customer_resolving)。 + """ + from app import db + from app.models import ShippingNotice, ShippingOrderTask, User from app.services.shipping_notice.order_task_stage_machine import ( sync_order_task_stage_for_candidate, ) + user = User(username='notice-bound-user', email='nb@example.com', password_hash='x') + db.session.add(user) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-NOTICE-BOUND', + user_id=user.id, + status='automating', + stage='inventory_matching', + ) + db.session.add(order_task) + db.session.flush() + # 真实 Notice 通过 order_task_id 反向挂接 OT,而非在 OT 上存通知单指针。 + notice = ShippingNotice( + task_no='SN-NOTICE-BOUND', + order_task_id=order_task.id, + lifecycle_status='active', + ) + db.session.add(notice) + db.session.commit() + candidate = SimpleNamespace(id=82, consumed_task_id=None) - order_task = SimpleNamespace(stage='inventory_matching', status='automating', shipping_notice_id=14) with patch( - 'app.services.shipping_notice.order_task_stage_machine.resolve_order_task_for_candidate', - return_value=order_task, - ), patch( 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state', ) as sync_mock: result = sync_order_task_stage_for_candidate( @@ -179,6 +204,7 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(): 'gates': {'customer_confirmed': False, 'duplicate_resolved': True}, 'blocking_reason_codes': ['customer_unresolved'], }, + order_task=order_task, ) assert result is order_task @@ -201,7 +227,7 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task lifecycle_status='active', inventory_lines_json=None, ) - order_task = SimpleNamespace(stage='waiting_review', status='waiting_review') + order_task = SimpleNamespace(stage='waiting_review', status='waiting_review', active_process_execution_id=92) execution = SimpleNamespace( current_gate_code='inventory_preparation', status='waiting_external', @@ -219,3 +245,42 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task reason_code='notice_fulfillment_sync', source='order_task_stage_machine', ) + + +def test_completed_execution_with_blocked_gate_overrides_stale_completed_order_task_stage(): + """[FIX] 正式 Execution 已 blocked 但执行状态陈旧为 completed(历史遗留/指针未刷新)时, + OT.stage 不得滞留 completed;须按 current_gate_code 回写该 Gate 阶段并落 blocked。""" + notice = SimpleNamespace( + id=15, + order_task_id=82, + active_process_execution_id=93, + current_step='step7', + upload_status='uploaded', + export_file_path='/tmp/x.xlsx', + pending_human_reason=None, + review_status=None, + match_status=None, + lifecycle_status='active', + inventory_lines_json=[], + ) + order_task = SimpleNamespace(stage='completed', status='completed', active_process_execution_id=93) + execution = SimpleNamespace( + current_gate_code='inventory_preparation', + status='completed', + ) + with patch( + 'app.services.shipping_notice.processing_projection_invariants.map_notice_to_processing_status_stage', + return_value=('completed', 'completed'), + ), patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch( + 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state', + ) as sync_mock: + mock_db.session.get.side_effect = [order_task, execution] + sync_order_task_stage_for_notice(notice) + + sync_mock.assert_called_once_with( + order_task, + stage='inventory_fetching', + status='blocked', + reason_code='notice_fulfillment_sync', + source='order_task_stage_machine', + ) diff --git a/backend/tests/test_shipping_order_task_status_consistency.py b/backend/tests/test_shipping_order_task_status_consistency.py index dbc0c086..20f53b51 100644 --- a/backend/tests/test_shipping_order_task_status_consistency.py +++ b/backend/tests/test_shipping_order_task_status_consistency.py @@ -15,7 +15,7 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderTask +from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion, ShippingOrderTask from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case from app.services.shipping_notice.order_review_draft_service import patch_header_field @@ -27,6 +27,7 @@ from app.services.shipping_notice.order_task_service import ( from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import ( _materialized_run, + _seed_confirmed_bill_to_for_candidate, _seed_review_inventory_routing_catch_all, ) @@ -143,6 +144,8 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = { 'orders': [{ @@ -164,6 +167,14 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): ) db.session.add(candidate) db.session.flush() + # 客户确认是建单前置事实:为机器候选补齐正式客户识别 Resolution, + # 否则 confirm_review_case 的客户门禁会因查不到已确认客户而提前拒绝。 + _seed_confirmed_bill_to_for_candidate( + candidate=candidate, + run=run, + intake=intake, + user=user, + ) root_no = allocate_user_task_no_for_run(run) upsert_order_task_from_run( run, @@ -184,10 +195,13 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): ) _seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id') notice_before = ShippingNotice.query.count() + ot_before = ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() + # 确认订单事务中途失效(冻结订单快照失败)必须整体回滚:不产生孤儿 OT/Notice, + # Case 不卡在 confirming。 with patch( - 'app.services.shipping_notice.order_task_service.link_notice_to_order_task', - side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'), + 'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot', + side_effect=ConflictError('simulated confirm failure', code='SHIPPING.SIMULATED_CONFIRM_FAIL'), ): with pytest.raises(ConflictError) as exc_info: confirm_review_case( @@ -198,11 +212,12 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): warning_acknowledgements=[{'code': 'manual_checked'}], ) - assert exc_info.value.code == 'SHIPPING.SIMULATED_NOTICE_FAIL' + assert exc_info.value.code == 'SHIPPING.SIMULATED_CONFIRM_FAIL' db.session.expire_all() assert ShippingNotice.query.count() == notice_before + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == ot_before refreshed = ensure_run_review_cases(run=run)[0] assert refreshed.status != 'confirming' assert refreshed.confirmed_task_id is None ot = ShippingOrderTask.query.filter_by(task_no=root_no).one() - assert ot.shipping_notice_id is None + assert ot is not None diff --git a/backend/tests/test_shipping_override_inventory_source.py b/backend/tests/test_shipping_override_inventory_source.py new file mode 100644 index 00000000..c68e698b --- /dev/null +++ b/backend/tests/test_shipping_override_inventory_source.py @@ -0,0 +1,238 @@ +""" +tests/test_shipping_override_inventory_source.py + +用途:人工覆写行级库存源(方案 3·放开)——通知准备阶段允许用户把某行库存源覆写为 + 任一已启用库存源(不限于规则候选),钉为所选源并仅对该行重匹配。 +依赖:process_gate_contract(动作归属)、process_gate_executor(处理器校验与钉源)。 +逻辑:首次选源由 inventory_source_routing 建立完整行级候选集;既有候选的覆写仍可在 + 通知准备/匹配阶段执行。所有项次均选定前不允许触发库存准备或 RPA。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from app.core.errors import AppError +from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate +from app.services.shipping_notice import process_gate_executor + + +def test_override_source_belongs_to_routing_preparation_and_matching(): + """[断言] 首次人工选源属于路由 Gate,既有覆写仍属于准备/匹配 Gate。""" + assert action_belongs_to_gate(gate_code='inventory_source_routing', action_code='override_line_inventory_source') + assert action_belongs_to_gate(gate_code='inventory_preparation', action_code='override_line_inventory_source') + assert action_belongs_to_gate(gate_code='inventory_matching', action_code='override_line_inventory_source') + assert not action_belongs_to_gate(gate_code='inventory_sufficiency', action_code='override_line_inventory_source') + + +def _payload(**overrides): + base = { + 'line_no': 1, 'source_code': 'SRC_X', + 'reason': '业务确认改用 X 仓', 'operator_id': 7, + } + base.update(overrides) + return base + + +def _task(export_file_path=None): + return SimpleNamespace( + id=19, task_no='SN-OVERRIDE', + order_snapshot_id=3, + step_payload_json={'line_inventory_resolutions': []}, + ) + + +def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app): + """[断言] 通过校验后:候选行 source_codes_json 钉住所选源并写覆写审计; + match_inventory_line 以内部分发仅重匹配该行。""" + from app import db + from app.services.shipping_notice import process_gate_executor as executor + + task = _task() + execution = SimpleNamespace(id=1, task_id=19) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout') + + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [{'source_code': 'SRC_X'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa', + 'display_name': code, 'warehouse_resolution_mode': 'dynamic', + 'fixed_warehouse_id': None}, + ) + + pinned = {} + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection', + lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True), + ) + retrigger_calls: list[str] = [] + retrigger_kwargs: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + lambda task_no, **kw: (retrigger_calls.append(task_no), retrigger_kwargs.append(kw)) or {'status': 'running'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **kwargs: pinned.setdefault('audit', kwargs), + ) + + outcome = executor._handle_override_line_inventory_source( + execution=execution, gate=gate, payload=_payload(), + ) + + assert pinned['audit']['action'] == 'override_line_inventory_source' + assert pinned['audit']['after']['selected_source_code'] == 'SRC_X' + assert retrigger_calls and retrigger_calls[0] == task.task_no + # [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa), + # 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。 + assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation' + assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa' + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'} + + +def test_override_does_not_pass_preparation_when_inventory_is_still_missing(monkeypatch, app): + """[断言] 覆写库存源不是库存准备成功事实;RPA 未产出库存时保持可重试阻断。""" + from app.services.shipping_notice import process_gate_executor as executor + + task = _task() + execution = SimpleNamespace(id=1, task_id=19) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation') + preparation_gate = SimpleNamespace( + status='blocked_retryable', blocking_reason_code='inventory_rpa_export_failed', + ) + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [{'source_code': 'SRC_X'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_kwargs: {'source_code': code, 'connector_type': 'excel_rpa', + 'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None}, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection', + lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + lambda *_args, **_kwargs: {'status': 'waiting_human'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **_kwargs: None, + ) + monkeypatch.setattr( + executor.ShippingProcessGate, + 'query', + SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: preparation_gate)), + ) + + outcome = executor._handle_override_line_inventory_source( + execution=execution, gate=gate, payload=_payload(), + ) + + assert outcome['outcome'] == 'blocked_retryable' + assert outcome['blocking_reason_code'] == 'inventory_rpa_export_failed' + + +def test_first_line_selection_keeps_routing_blocked_until_all_snapshot_lines_are_selected(monkeypatch, app): + """[断言] 首次选源只冻结当前项次;尚有未选项次时不触发自动推进或 RPA。""" + from app.services.shipping_notice import process_gate_executor as executor + + task = _task() + execution = SimpleNamespace(id=1, task_id=19) + gate = SimpleNamespace(id=11, gate_code='inventory_source_routing') + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [{'source_code': 'SRC_X'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_kwargs: {'source_code': code}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection', + lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=100), False), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **_kwargs: None, + ) + calls: list[str] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + lambda *_args, **_kwargs: calls.append('progress'), + ) + + outcome = executor._handle_override_line_inventory_source( + execution=execution, gate=gate, payload=_payload(), + ) + + assert outcome['outcome'] == 'blocked_manual' + assert outcome['blocking_reason_code'] == 'no_inventory_source_candidates' + assert outcome['effective_result_json']['all_lines_selected'] is False + assert calls == [] + + +def test_override_rejects_after_excel_lock(monkeypatch, app): + """[断言] 通知 Excel 已生成 → 拒绝覆写(SHIPPING.LINE_SOURCE_LOCKED)。""" + from app.services.shipping_notice import process_gate_executor as executor + + task = _task(export_file_path='data/x.xlsx') + execution = SimpleNamespace(id=1, task_id=19) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout') + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: object(), + ) + + with pytest.raises(AppError) as err: + executor._handle_override_line_inventory_source( + execution=execution, gate=gate, payload=_payload(), + ) + assert err.value.code == 'SHIPPING.LINE_SOURCE_LOCKED' + + +def test_override_rejects_disabled_source(monkeypatch, app): + """[断言] 所选源不在启用源列表 → 拒绝(SHIPPING.LINE_SOURCE_UNAVAILABLE)。""" + from app.services.shipping_notice import process_gate_executor as executor + + task = _task() + execution = SimpleNamespace(id=1, task_id=19) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout') + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [{'source_code': 'SRC_OTHER'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa', + 'display_name': code, 'warehouse_resolution_mode': 'dynamic', + 'fixed_warehouse_id': None}, + ) + + with pytest.raises(AppError) as err: + executor._handle_override_line_inventory_source( + execution=execution, gate=gate, payload=_payload(), + ) + assert err.value.code == 'SHIPPING.LINE_SOURCE_UNAVAILABLE' diff --git a/backend/tests/test_shipping_override_persists_projected_source.py b/backend/tests/test_shipping_override_persists_projected_source.py new file mode 100644 index 00000000..50100f9f --- /dev/null +++ b/backend/tests/test_shipping_override_persists_projected_source.py @@ -0,0 +1,241 @@ +""" +tests/test_shipping_override_persists_projected_source.py + +用途:行级库存源人工覆写(方案 3·放开)后,所选源必须确定性落库到该行的 + ShippingNoticeLineInventoryMatch.inventory_source_code,并投影为 + build_task_ui_state 的 preparation.lines[].source_code。 + +回归背景:真实任务对某行覆写库存源后显示「操作已提交」,但行的 source_code 仍为空, + 前端下拉每次都要重新选择(issue 2);且切换文件时回退投影与权威投影的 source_code + 不一致造成「先旧后新」的二次刷新(issue 1)。本测试走真实匹配引擎 + 真实持久化 + + 真实投影,实锤所选源是否可靠落到行投影。 + +依赖:stp_line_inventory_match.match_order_lines_across_candidates、 + line_inventory_match_persistence.persist_line_inventory_match_facts、 + ui_state.build_task_ui_state。 +逻辑:候选行 source_codes_json 钉住 SRC_X,库存行仅含 SRC_X → 匹配器解析 + resolved_inventory_source_code=SRC_X → 持久化 writing inventory_source_code=SRC_X + → 投影 lines[].source_code=SRC_X。 + +契约迁移:任务容器由 ShippingNotice → ShippingOrderTask(task_no=OT-…, + source_type=eml/direct_pdf,行身份由 line_no 而非 line_key);持久化依赖 + task.order_snapshot_id → ShippingOrderSnapshot.lines 中 line_no==1 的快照行, + 故本测试显式构造冻结快照。 +""" + +from __future__ import annotations + +from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, +) +from app.services.shipping_notice.line_inventory_match_persistence import ( + persist_line_inventory_match_facts, +) +from app.services.shipping_notice.stp_line_inventory_match import ( + attach_candidate_scope_to_order_lines, + match_order_lines_across_candidates, +) +from app.services.shipping_notice.ui_state import build_task_ui_state + + +class _CandidateLine: + """最小候选行桩:line_no 与 source_codes_json(持久化读取该字段)。""" + + def __init__(self, line_no: int, source_codes: list[str]): + self.id = 100 + line_no + self.line_no = line_no + self.source_codes_json = source_codes + + +def _make_task(app, *, task_no: str): # noqa: ANN001 - 测试辅助 + """构造已冻结单行快照的 OT,供覆写项目持久化与投影测试复用。 + + 核心逻辑:ShippingOrderTask 无 line_key/手动源,行身份由 line_no 表达; + 持久化只写 order_snapshot_id 指向的快照内 line_no==1 的行。 + """ + from app import db + + task = ShippingOrderTask( + task_no=task_no, + source_type="direct_pdf", + user_id=1, + ) + db.session.add(task) + db.session.flush() + + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=1, + order_data_version=1, + rule_versions_json={}, + source_manifest_json={}, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + db.session.add( + ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + part_number="PN-1", + reservation_id="3000092917", + qty=10, + field_values_json={}, + ) + ) + task.order_snapshot_id = snapshot.id + db.session.flush() + return task + + +def test_override_pinned_source_lands_in_projected_source_code(app, monkeypatch) -> None: + """[断言] 覆写所选源(candidate 钉为 SRC_X)后,行投影 source_code == SRC_X。""" + with app.app_context(): + from app import db + + task = _make_task(app, task_no="OT-OVERRIDE-PROJECT") + + # [STEP 1] 候选行钉住所选源(override 处理器正是把 source_codes_json=[SRC_X])。 + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task", + lambda _task: None, + ) + + # [STEP 2] 真实匹配:库存行仅含 SRC_X,且与该行 Reservation+PN 命中。 + # Reservation ID 必须为 5/10 位纯数字(validated_reservation_id 契约)。 + order_lines = attach_candidate_scope_to_order_lines(task, [{ + "line_no": 1, + "line_index": 0, + "part_number": "PN-1", + "reservation_id": "3000092917", + "quantity": "10", + }]) + match_payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=[{ + "reservation_id": "3000092917", + "part_number": "PN-1", + "qty": "10", + "__source_code": "SRC_X", + "__inventory_file_no": "INV-X", + }], + ) + + # [STEP 3] 真实持久化:将匹配结果写入 ShippingNoticeLineInventoryMatch。 + persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=None, + matching_rule_version="stp_line_v2", + ) + db.session.flush() + + # [STEP 4] 断言持久化行已带所选源。 + line_row = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_no=1, is_current=True) + .first() + ) + assert line_row is not None, "应为目标行写入 current 行级匹配事实" + assert line_row.inventory_source_code == "SRC_X", ( + f"持久化应写入所选源;got={line_row.inventory_source_code!r}" + ) + + # [STEP 5] 断言统一 UI 投影也返回 source_code=SRC_X(前端下拉回显的依据)。 + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + line = next(item for item in preparation["lines"] if item["line_no"] == 1) + assert line["source_code"] == "SRC_X", ( + f"行投影应回显所选源;got={line['source_code']!r} lines={preparation['lines']!r}" + ) + assert preparation["source_locked"] is False + + +def test_override_source_without_inventory_keeps_line_editable(app, monkeypatch) -> None: + """[断言] 覆写到一个对该行无库存行的源时不伪造已解析:source_code 保持空、行可编辑。 + + 这印证 D7 契约:Excel 未生成(source_locked=False)前行应保持可编辑, + 不应因所选源无库存而虚假写入 inventory_source_code。 + """ + with app.app_context(): + from app import db + + task = _make_task(app, task_no="OT-OVERRIDE-NOINVENTORY") + + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task", + lambda _task: None, + ) + + order_lines = attach_candidate_scope_to_order_lines(task, [{ + "line_no": 1, + "line_index": 0, + "part_number": "PN-1", + "reservation_id": "3000092917", + "quantity": "10", + }]) + # 库存行只有另一源 SRC_Y,对 SRC_X 无命中 → 不解析出 SRC_X。 + match_payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=[{ + "reservation_id": "3000092917", + "part_number": "PN-1", + "qty": "10", + "__source_code": "SRC_Y", + "__inventory_file_no": "INV-Y", + }], + ) + persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=None, + matching_rule_version="stp_line_v2", + ) + db.session.flush() + + line_row = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_no=1, is_current=True) + .first() + ) + # 无命中:不应把 SRC_X 记为已解析。 + assert line_row is None or line_row.inventory_source_code != "SRC_X" + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + assert preparation["source_locked"] is False diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index 30b4d005..b30b30c7 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -82,14 +82,18 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate(): ) is True -def test_inventory_preparation_allows_reload_existing_result_without_rpa(): - """RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。""" +def test_inventory_preparation_timeout_prefers_merged_rematch_without_standalone_reload(): + """RPA 超时后主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA); + reload_inventory_result 不再作为独立主动作。retry_inventory_matching 现属库存准备/匹配/充足性 Gate。""" assert action_belongs_to_gate( - gate_code='inventory_preparation', action_code='reload_inventory_result', + gate_code='inventory_preparation', action_code='retry_inventory_matching', ) is True assert action_belongs_to_gate( - gate_code='inventory_matching', action_code='reload_inventory_result', - ) is False + gate_code='inventory_matching', action_code='retry_inventory_matching', + ) is True + assert action_belongs_to_gate( + gate_code='inventory_sufficiency', action_code='retry_inventory_matching', + ) is True def test_inventory_sufficiency_actions_keep_business_specific_labels(): @@ -233,8 +237,10 @@ def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technica assert summary['next_action_code'] == 'open_inventory_match_review' assert summary['owner_type'] == 'human' assert summary['technical_auto_only'] is False + # 侧路动作(override_line_inventory_source,方案 3·放开)先于 RecoveryPlan 复核入口。 assert summary['allowed_actions'] == [ 'open_inventory_match_review', + 'override_line_inventory_source', 'retry_inventory_from_preparation', ] @@ -275,6 +281,7 @@ def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch assert summary['next_action_code'] == 'retry_inventory_matching' assert summary['allowed_actions'] == [ 'retry_inventory_matching', + 'override_line_inventory_source', 'retry_inventory_from_preparation', ] assert summary['recovery_targets'] == [ @@ -287,7 +294,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres from app import db from app.models import ( ShippingInventoryFile, - ShippingNotice, + ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingTaskInventoryLink, @@ -296,10 +303,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres inventory_path = tmp_path / 'active-inventory.xlsx' inventory_path.write_bytes(b'confirmed inventory') - task = ShippingNotice( - task_no='SN-SUFFICIENCY-ACTIVE-SNAPSHOT', - inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}], - ) + task = ShippingOrderTask(task_no='OT-SUFFICIENCY-ACTIVE-SNAPSHOT', user_id=1) inventory_file = ShippingInventoryFile( inventory_file_no='SIF-SUFFICIENCY-ACTIVE-SNAPSHOT', storage_path=str(inventory_path), @@ -440,11 +444,16 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch): assert summary['next_action_code'] == 'retry_inventory_preparation' assert summary['primary_action']['code'] == 'retry_inventory_preparation' - assert summary['allowed_actions'] == ['retry_inventory_preparation'] + # 库存准备不再提供库存文件上传旁路;主线仅重试 RPA,并保留行级库存源人工覆写(方案 3·放开)。 + assert summary['allowed_actions'] == [ + 'retry_inventory_preparation', + 'override_line_inventory_source', + ] -def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch): - """RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。""" +def test_inventory_rpa_timeout_prefers_merged_rematch(app, monkeypatch): + """RPA 超时主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA), + 不再直接指向孤立的 reload_inventory_result 或新 RPA 请求。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection @@ -472,11 +481,14 @@ def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch): summary = projection.project_user_gate_summary(execution) - assert summary['next_action_code'] == 'reload_inventory_result' - assert summary['primary_action']['code'] == 'reload_inventory_result' + assert summary['next_action_code'] == 'retry_inventory_matching' + assert summary['primary_action']['code'] == 'retry_inventory_matching' + # 主动作=复用快照重匹配(无则 RPA);侧路保留 retry_inventory_preparation(显式 RPA 重试)与 + # override_line_inventory_source(行级库存源人工覆写,方案 3·放开)。 assert summary['allowed_actions'] == [ - 'reload_inventory_result', + 'retry_inventory_matching', 'retry_inventory_preparation', + 'override_line_inventory_source', ] @@ -614,7 +626,7 @@ def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, m summary = projection.project_user_gate_summary(execution) - assert summary['allowed_actions'] == [] + assert summary['allowed_actions'] == ['override_line_inventory_source'] def test_process_gate_dependency_integrity_and_excel_only_scope(): diff --git a/backend/tests/test_shipping_process_gate_recovery_action_contract.py b/backend/tests/test_shipping_process_gate_recovery_action_contract.py index 7f7dc663..9cb93716 100644 --- a/backend/tests/test_shipping_process_gate_recovery_action_contract.py +++ b/backend/tests/test_shipping_process_gate_recovery_action_contract.py @@ -22,6 +22,7 @@ from app.services.shipping_notice.process_gate_projection import ( from app.services.shipping_notice.process_gate_recovery_service import ( _primary_recovery_action, ) +from app.services.shipping_notice.process_gate_contract import gate_side_recovery_actions @pytest.mark.pure_unit @@ -77,14 +78,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): @pytest.mark.pure_unit @pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted']) -def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason): - """超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。""" +def test_inventory_rpa_timeout_or_exhausted_prefers_merged_rematch(reason): + """超时或耗尽主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA), + 不再直接新开 RPA Attempt 或孤立只重读。""" full, blocking = _mk( {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', 'blocking_reason_code': reason}, ) action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) - assert action == 'reload_inventory_result' + assert action == 'retry_inventory_matching' @pytest.mark.pure_unit @@ -169,12 +171,11 @@ def test_inventory_matching_retryable_exposes_retry_action(): def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch): """匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。""" from app.services.shipping_notice import process_gate_executor as executor - from app.models import ShippingNotice + from app.models import ShippingOrderTask task = SimpleNamespace( + id=7, task_no='SN-SHORTAGE-1', - match_status='partial', - shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}], ) execution = SimpleNamespace(task_id=7) gate = SimpleNamespace(gate_code='inventory_matching') @@ -187,7 +188,19 @@ def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_suffi 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', lambda **_kwargs: None, ) - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'shortage_qty': '2'}}, + ) with app.app_context(): outcome = executor._handle_retry_inventory_matching( @@ -225,13 +238,13 @@ def test_inventory_preparation_waiting_keeps_refresh_action(): def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch): """重新读取库存结果只复用快照,不能触发新的库存 RPA。""" - from app.models import ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice import process_gate_executor as executor task = SimpleNamespace(task_no='SN-RELOAD-1') execution = SimpleNamespace(task_id=7) calls: list[tuple[str, object]] = [] - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'}, @@ -265,14 +278,16 @@ def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, mon assert calls[1][0] == 'sync' -def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch): +def test_reload_inventory_result_keeps_timeout_blocked_and_stops_poll_when_snapshot_missing(app, monkeypatch): """无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。""" - from app.models import ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice import process_gate_executor as executor task = SimpleNamespace(task_no='SN-RELOAD-MISSING') execution = SimpleNamespace(task_id=7) - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + gate = SimpleNamespace(id=1333, gate_code='inventory_preparation') + cancelled: list[dict] = [] + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'}, @@ -289,16 +304,21 @@ def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', lambda _task: 'inventory_rpa_timeout', ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls', + lambda **kwargs: cancelled.append(kwargs) or 1, + ) with app.app_context(): outcome = executor._handle_reload_inventory_result( execution=execution, - gate=SimpleNamespace(gate_code='inventory_preparation'), + gate=gate, payload={}, ) assert outcome['outcome'] == 'blocked_retryable' assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout' + assert cancelled == [{'gate_id': 1333, 'reason': '库存结果重读未命中,外部等待轮询已终止'}] @pytest.mark.pure_unit @@ -307,3 +327,196 @@ def test_no_blocking_returns_no_action(): full, _ = _mk({'gate_code': 'inventory_preparation', 'status': 'passed'}) action, _ = _resolve_recovery_next_action(blocking=None, full=full, execution=None) assert action is None + + +@pytest.mark.pure_unit +@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted']) +def test_inventory_preparation_rpa_timeout_exposes_side_retry_action(reason): + """投影侧路必须与校验侧一致:RPA 超时/耗尽默认主恢复是 reload_inventory_result, + 但仍投影 retry_inventory_preparation 作为用户显式重试的侧路动作。 + + 回归背景:真实任务在 RPA 超时/耗尽后点击「重新获取库存 (RPA)」被报 + SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED,因为 request_gate_action 的 allowed_side + 恒为空,与投影暴露的侧路动作不一致。修复后 gate_side_recovery_actions 必须给出该动作, + 使校验侧(request_gate_action)与投影侧(serialize_process_gate / allowed_actions)同源。 + """ + sides = gate_side_recovery_actions( + gate_code='inventory_preparation', + status='blocked_retryable', + blocking_reason_code=reason, + ) + assert 'retry_inventory_preparation' in sides + + +@pytest.mark.pure_unit +def test_gate_side_recovery_actions_matches_projection_surface_full_set(): + """侧路动作集合必须完整覆盖投影在 allowed_actions 中放行的全部人工/备份动作。 + + 注意:这里只断言「本状态需包含的动作都在集合内」(子集关系),不能断言集合 + 恰好等于某几个动作 —— 因为不同门禁/状态会并列放行多个侧路动作(含 + override_line_inventory_source 等)。 + """ + sides = gate_side_recovery_actions( + gate_code='inventory_preparation', + status='blocked_retryable', + blocking_reason_code='inventory_rpa_timeout', + ) + assert set(sides) >= {'retry_inventory_preparation', 'override_line_inventory_source'} + + +@pytest.mark.pure_unit +@pytest.mark.parametrize('gate_code,status,reason', [ + ('inventory_preparation', 'blocked_retryable', 'inventory_rpa_timeout'), + ('inventory_preparation', 'blocked_retryable', 'inventory_rpa_exhausted'), + ('inventory_matching', 'blocked_retryable', 'inventory_match_failed'), + ('inventory_matching', 'blocked_manual', 'inventory_multi_file_conflict'), +]) +def test_override_line_inventory_source_exposed_on_its_gates(gate_code, status, reason): + """override_line_inventory_source 属 inventory_preparation / inventory_matching 门禁 + (见 action_belongs_to_gate),必须纳入侧路动作集,否则前端 authorized 守卫 fail-closed + 报「当前没有可执行的处理操作」。 + + 回归背景:该动作已作为行级覆写入口上线(前端渲染下拉,点击提交), + 但不在 gate_side_recovery_actions 内 → 投影不暴露 → submitFormalGateAction 直接 noAction。 + """ + sides = gate_side_recovery_actions( + gate_code=gate_code, + status=status, + blocking_reason_code=reason, + ) + assert 'override_line_inventory_source' in sides, (gate_code, status, reason) + + +def test_override_line_inventory_source_surfaces_in_user_summary(app, monkeypatch): + """通知准备(inventory_preparation)阻断时用户摘要必须投影 override_line_inventory_source。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-OVERRIDE-SRC', status='blocked', + current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=99, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-OVERRIDE-SRC', 'status': 'blocked', + 'primary_next_action_code': 'retry_inventory_preparation', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'inventory_preparation', 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_preparation_failed', + 'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 5, + }, + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', + lambda _id: None, + raising=False, + ) + + summary = projection.project_user_gate_summary(execution) + + assert 'override_line_inventory_source' in summary['allowed_actions'] + assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation']) + + +def test_inventory_preparation_rpa_timeout_surfaces_side_action_in_user_summary(app, monkeypatch): + """RPA 超时/耗尽时用户摘要必须投影 retry_inventory_preparation(与校验同源)。 + + 回归背景:真实任务在 RPA 超时/耗尽时界面展示「重新获取库存 (RPA)」按钮, + 但点击即报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED。根因是投影的 allowed_actions + 侧路与 request_gate_action 的 allowed_side 各自硬编码导致漂移。 + """ + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-RPA-TIMEOUT', status='blocked', + current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_matching', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=99, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-RPA-TIMEOUT', 'status': 'blocked', + 'primary_next_action_code': 'retry_inventory_matching', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'inventory_preparation', 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_rpa_timeout', + 'next_action_code': 'retry_inventory_matching', 'evaluation_version': 4, + }, + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', + lambda _id: None, + raising=False, + ) + + summary = projection.project_user_gate_summary(execution) + + assert summary['primary_action']['code'] == 'retry_inventory_matching' + assert 'retry_inventory_preparation' in summary['allowed_actions'] + assert any(item['code'] == 'retry_inventory_preparation' for item in summary['action_presentation']) + + +def test_inventory_editable_rows_keep_override_action_even_when_gate_not_blocked(app, monkeypatch): + """"行级可编辑期间(Excel 未生成,source 未锁定),即使门禁已不再处于人工阻断态, + 也必须继续授权 override_line_inventory_source。 + + 回归背景:真实任务第一次覆写成功后显示「操作已提交」,但行仍可编辑(契约:仅 + Excel 生成后才锁)。此时门禁状态推进(不再 blocked),project_user_gate_summary 的 + allowed_actions 因 `if blocking:` 跳过而清空,用户对该行二次修改在前端被 + submitFormalGateAction 守卫拦下,报「当前没有可执行的处理操作」(noAction)。 + 修复要求在行可编辑时按 source_locked(Excel 是否生成)授权行级编辑动作, + 而不是按门禁是否处于 blocking 状态。 + """ + from types import SimpleNamespace + from app import db + from app.models import ShippingNotice + from app.services.shipping_notice import process_gate_projection as projection + + # Excel 未生成(export_file_path 为空)→ source_locked=False,行仍可编辑。 + task = ShippingNotice(task_no='SN-EDITABLE-OVERRIDE', source_type='manual') + db.session.add(task) + db.session.flush() + + execution = SimpleNamespace( + id=1, execution_no='EXE-EDITABLE-OVERRIDE', status='active', + current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=int(task.id), + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-EDITABLE-OVERRIDE', 'status': 'active', + 'primary_next_action_code': 'retry_inventory_preparation', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + # 当前 Gate 不再是人工阻断态(如推进后的 running/queued),导致 `if blocking:` 恒为 False。 + 'current_gate': { + 'gate_code': 'inventory_preparation', 'status': 'running', + 'blocking_reason_code': None, + 'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 6, + }, + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', + lambda _id: None, + raising=False, + ) + + summary = projection.project_user_gate_summary(execution) + + # 契约:Excel 未生成 → 行可编辑 → 行级覆写动作必须仍被授权。 + assert 'override_line_inventory_source' in summary['allowed_actions'], summary['allowed_actions'] + assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation']) diff --git a/backend/tests/test_shipping_process_gate_requeue.py b/backend/tests/test_shipping_process_gate_requeue.py index 800f18bc..3567b124 100644 --- a/backend/tests/test_shipping_process_gate_requeue.py +++ b/backend/tests/test_shipping_process_gate_requeue.py @@ -29,10 +29,10 @@ def test_force_new_enqueue_does_not_reuse_running_job(app): force_new=True 时即使存在同 attempt 的 running Job,也必须新建可领取 queued Job。 """ with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='requeue1') + _user, review_case_id, task_id = _seed_workflow_version(suffix='requeue1') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + review_case_id=review_case_id, + task_id=task_id, ) attempt = queue_gate_attempt( execution_no=execution.execution_no, diff --git a/backend/tests/test_shipping_process_gate_retry_cap.py b/backend/tests/test_shipping_process_gate_retry_cap.py index da3d80b2..3633f573 100644 --- a/backend/tests/test_shipping_process_gate_retry_cap.py +++ b/backend/tests/test_shipping_process_gate_retry_cap.py @@ -14,7 +14,14 @@ from unittest.mock import MagicMock, patch from app import db from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate from app.jobs.types import JobType -from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt +from app.models import ( + Job, + ShippingInventoryFile, + ShippingOrderTask, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingTaskInventoryLink, +) from app.services.shipping_notice.process_gate_job_service import ( SHIPPING_PROCESS_GATE_JOB_DOMAIN, enqueue_gate_attempt_job, @@ -233,10 +240,24 @@ def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking( gate.effective_result_json = { 'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(), } - task = db.session.get(ShippingNotice, task_id) + task = db.session.get(ShippingOrderTask, task_id) assert task is not None - task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}] - assert task.inventory_lines_json + # 迟到的库存回调已把正式快照落库:绑定一份有效且已解析的库存文件, + # 使 has_ready_inventory_file_for_task 返回 True,从而改写超时轮询结果。 + inventory_file = ShippingInventoryFile( + inventory_file_no='INV-CALLBACK-WON', + storage_path='test/callback-won.xlsx', + source_file_name='callback-won.xlsx', + snapshot_status='ready', + line_count=1, + inventory_lines_json=[{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}], + ) + db.session.add(inventory_file) + db.session.flush() + db.session.add(ShippingTaskInventoryLink( + task_id=int(task.id), inventory_file_id=inventory_file.id, is_active=True, + )) + db.session.flush() attempt.status = 'succeeded' attempt.finished_at = datetime.utcnow() db.session.commit() diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py index f39bdcad..ad2d84a6 100644 --- a/backend/tests/test_shipping_process_gate_service.py +++ b/backend/tests/test_shipping_process_gate_service.py @@ -37,7 +37,7 @@ from app.models import ( ShippingProcessGateAttempt, - ShippingNotice, + ShippingOrderTask, User, @@ -50,6 +50,7 @@ from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE from app.services.shipping_notice.process_gate_service import ( ensure_execution_for_workflow_version, + ensure_process_gates_for_execution, invalidate_downstream_gates, @@ -75,7 +76,7 @@ def _seed_workflow_version( """ - 创建最小 User + ShippingNotice,供 Execution 绑定 review_case_id / task_id。 + 创建最小 User + ShippingOrderTask,供 Execution 绑定 review_case_id / task_id。 @@ -109,13 +110,13 @@ def _seed_workflow_version( db.session.flush() - task = ShippingNotice( + task = ShippingOrderTask( - task_no=f'SN-GATE-{tag}', + task_no=f'OT-SN-GATE-{tag}', user_id=int(user.id), - source_type='manual', + source_type='direct_pdf', ) @@ -168,7 +169,32 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution): assert len(gates) == len(PROCESS_GATE_CODES) - assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES) + +def test_existing_execution_gate_sequence_is_reconciled_to_current_contract(gate_execution): + """既有 Execution 的 Gate 顺序必须跟随当前契约修正,不能继续沿用旧 sequence_no。""" + gates = { + gate.gate_code: gate + for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all() + } + # 先移到不冲突的临时区间,再模拟旧版顺序。 + for index, gate in enumerate(gates.values(), start=1): + gate.sequence_no = 100 + index + db.session.flush() + gates['task_creation'].sequence_no = 12 + gates['order_freeze_readiness'].sequence_no = 10 + gates['inventory_source_routing'].sequence_no = 11 + gates['inventory_preparation'].sequence_no = 13 + db.session.flush() + + ensure_process_gates_for_execution(gate_execution) + db.session.commit() + + assert gates['task_creation'].sequence_no == 10 + assert gates['order_freeze_readiness'].sequence_no == 11 + assert gates['inventory_source_routing'].sequence_no == 12 + assert gates['inventory_preparation'].sequence_no == 13 + + assert set(gates) == set(PROCESS_GATE_CODES) assert gate_execution.current_gate_code == 'document_materialization' @@ -243,7 +269,7 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch): """已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。""" from app.services.shipping_notice import process_gate_service - from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt + from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt for prior_gate in ShippingProcessGate.query.filter( ShippingProcessGate.execution_id == int(gate_execution.id), @@ -255,7 +281,7 @@ def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, mon ).one() gate.status = 'blocked_retryable' gate.next_action_code = 'retry_inventory_preparation' - task = db.session.get(ShippingNotice, int(gate_execution.task_id)) + task = db.session.get(ShippingOrderTask, int(gate_execution.task_id)) db.session.add(ShippingTaskInventoryRpaAttempt( task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED', status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written', @@ -605,6 +631,59 @@ def test_business_sync_reuses_same_gate_active_attempt(app): assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1 +def test_business_sync_does_not_swallow_passed_when_gate_has_active_user_attempt(app): + """活动 Attempt 不得吞掉 sync 的 passed 结论。 + + 核心回归:真实任务 SN-20260831-9F25A698 / gate inventory_matching 曾因 + 同一秒存在管理员手动 override_line_inventory_source(running)而让 + sync_fulfillment_gates_from_task 的 match_passed=True 被 active_attempt + 短路 `return gate` 丢弃;随后手动动作失败把 gate 覆盖成 blocked_retryable, + 右侧前端误显示「自动处理失败」。 + + 契约:当业务事实判定为 passed 时,即使该 gate 上存在一个并发的、非本轮 + inventory_preparation 自动轮询的 Attempt,sync 也必须把 passed 写入 gate + (完成该活动 Attempt 收口),而不是静默返回导致真相被覆盖。 + """ + from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running + + with app.app_context(): + _user, review_case_id, task_id = _seed_workflow_version(suffix='passnotswallowed') + execution = ensure_execution_for_workflow_version( + review_case_id=review_case_id, + task_id=task_id, + ) + # 模拟并发占用的用户手动 Attempt(非 inventory_preparation 自动轮询)。 + user_attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_matching', + trigger_type='user_manual', + actor_type='user', + actor_id=1, + idempotency_key='concurrent-user-override', + input_snapshot={'action_code': 'override_line_inventory_source'}, + ) + mark_attempt_running(attempt_id=int(user_attempt.id), worker_id='concurrent-user') + + # 此时业务事实判定 passed(例如 match_status='fulfillable')。 + gate = sync_gate_from_business_result( + execution_no=execution.execution_no, + gate_code='inventory_matching', + passed=True, + effective_result_json={ + 'findings': [], + 'has_inventory_lines': True, + 'match_status': 'fulfillable', + }, + idempotency_key='match-passed-not-swallowed', + ) + + assert gate is not None + assert gate.status == 'passed', ( + 'gate 上存在并发的非自动轮询 Attempt 时,sync 的 passed 结论被 active_attempt ' + '短路丢弃,导致真实成功事实被覆盖为 blocked_retryable' + ) + + def test_force_business_sync_uses_current_gate_version(app): """强制重评不得回放失效前的固定幂等 Attempt。""" with app.app_context(): diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 1f92fc22..55cfbcf1 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -13,6 +13,7 @@ from app.models import ( ShippingInventoryMapping, ShippingInventoryPreparationAttempt, ShippingInventoryPreparationSourceAttempt, + ShippingOrderTask, ShippingProcessRecoveryPlan, ) @@ -43,6 +44,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): ShippingInventoryParsingProfile, ShippingInventoryVerification, ShippingNotice, + ShippingOrderTask, ShippingNoticeLineInventoryMatch, ShippingOrderExtraction, ShippingOrderSchema, @@ -53,7 +55,8 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): ) from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only - task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx') + owner = ShippingOrderTask(task_no='OT-EXCEL-REGEN-ONLY', user_id=1, source_type='direct_pdf') + task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', order_task_id=None) template = ShippingExcelTemplate( template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published', storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx', @@ -64,7 +67,9 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): status='published', file_format='xlsx', definition_json={}, ) schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only') - db.session.add_all([task, template, profile, schema]) + db.session.add_all([owner, task, template, profile, schema]) + db.session.flush() + task.order_task_id = owner.id db.session.flush() schema_version = ShippingOrderSchemaVersion( schema_id=schema.id, version=1, status='published', definition_json={}, @@ -75,7 +80,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted', ) execution = ShippingProcessExecution( - execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked', + execution_no='SPE-EXCEL-REGEN-ONLY', task_id=owner.id, status='blocked', current_gate_code='manual_upload_handoff', ) db.session.add_all([extraction, execution]) @@ -88,14 +93,14 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): status='ready', ) reservation = ShippingReservation( - task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY', + task_id=owner.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY', part_number='PN-1', po_number_normalized='PO-1', required_qty=1, status='artifact_reserved', current_artifact_id=None, ) - verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={}) + verification = ShippingInventoryVerification(task_id=owner.id, status='completed', result_json={}) match = ShippingNoticeLineInventoryMatch( - task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY', - part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True, + task_id=owner.id, snapshot_line_id=1, line_no=1, + match_result='matched', inventory_status='ready', is_current=True, ) db.session.add_all([artifact, reservation, verification, match]) db.session.flush() @@ -126,8 +131,6 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): assert upload.invalidated_at is not None assert reservation.status == 'available' assert reservation.current_artifact_id is None - assert task.export_file_path is None - assert task.export_file_name is None assert verification.status == 'completed' assert match.is_current is True @@ -276,8 +279,10 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap captured = {} monkeypatch.setattr( per_source_rpa_service, - 'write_inventory_export_trigger_for_task', - lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json', + 'write_inventory_export_batch_trigger', + lambda run_no, sources, payload=None: captured.update( + {'run_no': run_no, 'sources': [dict(item) for item in sources], 'payload': dict(payload or {})} + ) or 'trigger.json', ) monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'}) monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) @@ -285,9 +290,11 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto') assert result.pending_source_codes == ['DBS'] - assert captured['execution_id'] == task.active_process_execution_id - assert captured['gate_id'] == gate.id - assert captured['callback_id'].endswith(':C1') + # 逐源身份键现在随批次条目投递;顶层仅保留批次级载荷。 + assert captured['sources'][0]['execution_id'] == task.active_process_execution_id + assert captured['sources'][0]['gate_id'] == gate.id + assert captured['sources'][0]['callback_id'].endswith(':C1') + assert captured['sources'][0]['task_no'] == task.task_no def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): @@ -302,10 +309,10 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) - monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None) + monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', lambda *args, **kwargs: None) monkeypatch.setattr( 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', - lambda code: {'source_code': code, 'warehouse_id': 'WH-1'}, + lambda code, **kwargs: {'source_code': code, 'warehouse_id': 'WH-1'}, ) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa') assert result.pending_source_codes == [] @@ -319,16 +326,13 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): assert attempt.error_code == 'trigger_not_written' -def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app): - """正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。""" +def test_formal_gate_inventory_retry_requires_pre_frozen_facts(monkeypatch, app): + """库存准备 Gate 不再补冻结或补做路由,缺少前置事实时直接阻断。""" from app import db - from app.models import ShippingNotice, ShippingProcessExecution + from app.models import ShippingOrderTask, ShippingProcessExecution from app.services.shipping_notice import process_gate_executor - task = ShippingNotice( - task_no='SN-PREP-FREEZE-OPERATOR', - order_snapshot_id=None, order_data_version=1, - ) + task = ShippingOrderTask(task_no='OT-PREP-FREEZE-OPERATOR', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ShippingProcessExecution( @@ -361,8 +365,9 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey execution=execution, gate=gate, payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77}, ) - assert seen['actor_id'] == 77 - assert result['outcome'] == 'waiting_external' + assert seen == {} + assert result['outcome'] == 'blocked_retryable' + assert result['blocking_reason_code'] == 'inventory_source_routing_required' def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): @@ -431,11 +436,12 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY') + task = ShippingOrderTask(task_no='SNCALLBACKIDENTITYENTRY', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() monkeypatch.setattr( @@ -482,11 +488,12 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch): """PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。""" from app import db - from app.models import ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SN-2026-001') + task = ShippingOrderTask(task_no='SN-2026-001', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() captured = {} @@ -518,11 +525,12 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY') + task = ShippingOrderTask(task_no='SNCALLBACKBATCHIDENTITY', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() monkeypatch.setattr( @@ -551,7 +559,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch }], }) - assert response['failed_count'] == 1 + assert response['data']['failed_count'] == 1 assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch' assert legacy_called['value'] is False assert db.session.query(ShippingTaskEvent).filter_by( @@ -588,8 +596,8 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app): from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_service import queue_gate_attempt - task = ShippingNotice( - task_no='SN-RPA-FAILED-GATE', + task = ShippingOrderTask( + task_no='OT-RPA-FAILED-GATE', user_id=1, source_type='direct_pdf', pending_human_reason='rpa_exhausted', error_message='RPA export failed', ) db.session.add(task) @@ -638,16 +646,33 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app): def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): """迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。""" from app import db - from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate + from app.models import ( + ShippingInventoryFile, + ShippingOrderTask, + ShippingProcessExecution, + ShippingProcessGate, + ShippingTaskInventoryLink, + ) from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - task = ShippingNotice( - task_no='SN-RPA-LATE-SUCCESS', + task = ShippingOrderTask( + task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf', pending_human_reason='rpa_exhausted', - inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}], ) db.session.add(task) db.session.flush() + # 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。 + inv_file = ShippingInventoryFile( + inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx', + source_file_name='inv.xlsx', snapshot_status='ready', line_count=1, + inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}], + ) + db.session.add(inv_file) + db.session.flush() + db.session.add(ShippingTaskInventoryLink( + task_id=task.id, inventory_file_id=inv_file.id, is_active=True, + )) + db.session.flush() execution = ShippingProcessExecution( execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active', current_gate_code='inventory_preparation', @@ -675,12 +700,12 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app): from datetime import datetime from app import db - from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate + from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll from app.services.shipping_notice.process_gate_service import queue_gate_attempt - task = ShippingNotice(task_no='SN-STALE-PREP-POLL') + task = ShippingOrderTask(task_no='OT-STALE-PREP-POLL', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ShippingProcessExecution( @@ -709,12 +734,93 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app): assert attempt.job_id is None +def test_inventory_external_wait_poll_reuses_single_gate_attempt(app): + """库存等待轮询只创建延迟 Job,不新增 Gate Attempt。""" + from datetime import datetime + + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt + from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll + from app.services.shipping_notice.process_gate_service import queue_gate_attempt + + task = ShippingOrderTask(task_no='OT-SINGLE-POLL-ATTEMPT', user_id=1, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-SINGLE-POLL-ATTEMPT', task_id=task.id, status='waiting_external', + current_gate_code='inventory_preparation', + ) + db.session.add(execution) + db.session.flush() + gate = ShippingProcessGate( + execution_id=execution.id, gate_code='inventory_preparation', sequence_no=13, + status='waiting_external', effective_result_json={'waiting_since': datetime.utcnow().isoformat()}, + ) + db.session.add(gate) + db.session.flush() + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code=gate.gate_code, + trigger_type='system_requeue', actor_type='system', actor_id='test', + idempotency_key='single-poll-attempt', + input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}}, + ) + gate.status = 'waiting_external' + attempt.status = 'succeeded' + attempt.finished_at = datetime.utcnow() + db.session.flush() + + assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is not None + db.session.flush() + + assert ShippingProcessGateAttempt.query.filter_by(gate_id=gate.id).count() == 1 + + +def test_cancel_inventory_external_wait_polls_cancels_only_queued_jobs(app): + """库存重读失败必须立即取消未领取的延迟 poll,不影响正在执行的 Job。""" + from app import db + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.process_gate_job_service import ( + SHIPPING_PROCESS_GATE_JOB_DOMAIN, + cancel_inventory_external_wait_polls, + ) + + queued = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='queued', business_ref='external-wait:1333:4', payload_json={'external_wait_poll_gate_id': 1333}, + ) + running = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='running', business_ref='external-wait:1333:3', payload_json={'external_wait_poll_gate_id': 1333}, + ) + other = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='queued', business_ref='external-wait:1334:1', payload_json={'external_wait_poll_gate_id': 1334}, + ) + db.session.add_all([queued, running, other]) + db.session.flush() + + assert cancel_inventory_external_wait_polls(gate_id=1333, reason='reload missing') == 1 + db.session.flush() + db.session.refresh(queued) + db.session.refresh(running) + db.session.refresh(other) + assert queued.status == 'cancelled' + assert running.status == 'running' + assert other.status == 'queued' + + def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch): """已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。""" from app import db from app.models import ( + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, ShippingInventoryPreparationAttempt, - ShippingNotice, ShippingProcessGate, ShippingTaskEvent, ) @@ -725,7 +831,10 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp queue_gate_attempt, ) - task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail') + task = ShippingOrderTask( + task_no='OT-POLL-KEEPS-RPA-TIMEOUT', user_id=1, + pending_human_reason='inv_unavail', order_snapshot_id=1, + ) db.session.add(task) db.session.flush() execution = ensure_execution_for_workflow_version( @@ -733,11 +842,33 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp start_gate_code='inventory_preparation', ) task.active_process_execution_id = execution.id + # 上一轮准备已裁决并冻结库存源候选:poll 前置的补裁决必须被跳过,否则 + # adjudicate_and_apply_inventory_source 会新创建/替换 CandidateSet 并把 + # execution.candidate_set_id 刷新为新的 id(≠ 本轮失败 Preparation 的 candidate_set_id), + # 导致 failed_preparation 过滤不到而误调 RPA。 + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', + input_fingerprint='b' * 64, + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate.id, source_code='DSV360_AWSDU', + candidate_order=1, candidate_origin='rule', + )) + from app.models import ShippingInventoryCandidateLine + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate.id, line_no=1, source_codes_json=['DSV360_AWSDU'], + )) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + execution.candidate_set_id = candidate.id preparation = ShippingInventoryPreparationAttempt( task_id=task.id, execution_id=execution.id, attempt_no=1, status='failed', + candidate_set_id=candidate.id, input_snapshot_json={}, output_snapshot_json={}, ) @@ -791,8 +922,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo from app import db from app.models import ( ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, ShippingInventoryPreparationAttempt, - ShippingNotice, + ShippingOrderTask, ShippingProcessGate, ShippingProcessGateAttempt, ) @@ -802,9 +934,10 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo queue_gate_attempt, ) - task = ShippingNotice( - task_no='SNFORMALPREPLINEAGE', - inventory_source_code='DBS', + task = ShippingOrderTask( + task_no='OTFORMALPREPLINEAGE', + user_id=1, + source_type='direct_pdf', # 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。 order_snapshot_id=1, ) @@ -815,6 +948,14 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo ) db.session.add(candidate) db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate.id, source_code='DBS', candidate_order=1, candidate_origin='rule', + )) + from app.models import ShippingInventoryCandidateLine + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate.id, line_no=1, source_codes_json=['DBS'], + )) + db.session.flush() task.active_inventory_candidate_set_id = candidate.id execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') execution.candidate_set_id = candidate.id @@ -875,17 +1016,46 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): """正式起始 Gate 必须优先反映未完成的客户确认事实。""" from app import db - from app.models import ShippingInventoryCandidateSet, ShippingNotice + from app.models import ( + ShippingCustomerShadowResolution, + ShippingInventoryCandidateSet, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + ) from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - task = ShippingNotice( - task_no='SNSTARTCUSTOMERPENDING', + intake = ShippingOrderIntake( + intake_no='INT-START-CUSTOMER-PENDING', asset_id=1, user_id=1, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + order_candidate = ShippingOrderCandidate( + candidate_no='CAND-START-CUSTOMER-PENDING', intake_id=intake.id, + primary_document_id=1, candidate_key='start-customer-pending', candidate_status='accepted', + ) + db.session.add(order_candidate) + db.session.flush() + task = ShippingOrderTask( + task_no='OTSTARTCUSTOMERPENDING', + user_id=1, + source_type='direct_pdf', current_order_extraction_id=101, order_snapshot_id=201, - customer_resolution_status='pending', + candidate_id=order_candidate.id, ) db.session.add(task) db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=order_candidate.id, + intake_id=intake.id, + resolution_version='test.v1', + status='failed', + evidence_json=[], + candidate_matches_json=[], + resolution_context_json={}, + )) + db.session.flush() candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64, ) @@ -898,14 +1068,15 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): def test_formal_start_gate_stops_at_field_conflict_before_inventory(app): """正式起始 Gate 必须优先反映尚未解决的订单字段冲突。""" from app import db - from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict + from app.models import ShippingInventoryCandidateSet, ShippingOrderTask, ShippingTaskFieldConflict from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - task = ShippingNotice( - task_no='SNSTARTFIELDCONFLICT', + task = ShippingOrderTask( + task_no='OTSTARTFIELDCONFLICT', + user_id=1, + source_type='direct_pdf', current_order_extraction_id=101, order_snapshot_id=201, - customer_resolution_status='confirmed', ) db.session.add(task) db.session.flush() @@ -972,10 +1143,10 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app): def test_legacy_workspace_forwarding_audit_is_structured(app): """旧工作台动作转发必须留下 legacy_forwarded 入口审计。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint - task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT') + task = ShippingOrderTask(task_no='OTLEGACYFORWARDAUDIT', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() @@ -1131,22 +1302,30 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan(): assert plan.completed_at is not None -def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): - """已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。""" +def test_excel_regeneration_delegates_artifact_lock_to_generate_excel(monkeypatch): + """已有 Excel 时由 generate_excel 拒绝重生;Gate 执行器不再自身预检 Artifact。 + + [断言] regenerate_excel_artifact 只负责以内部编排标记委派 generate_excel 并转发其门禁结果; + 已生成裁决由 generate_excel 返回,不在 Gate 执行器层重复预检。 + """ from types import SimpleNamespace - from app.models import ShippingExportArtifact, ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel - task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL') - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) - monkeypatch.setattr( - ShippingExportArtifact, - 'query', - SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))), - ) + task = SimpleNamespace(id=1, task_no='OT-ONE-EXCEL') + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) + captured: dict = {} monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', - lambda _payload: pytest.fail('existing Artifact must not be regenerated'), + lambda payload: captured.update(payload) or { + 'status': 'blocked', + 'error_code': 'notice_excel_already_generated', + 'message': '通知 Excel 已生成,请创建新的通知单', + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **kwargs: None, ) outcome = _handle_regenerate_excel( @@ -1155,19 +1334,21 @@ def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): payload={'actor_user_id': 9}, ) - assert outcome['outcome'] == 'blocked_manual' - assert outcome['blocking_reason_code'] == 'notice_excel_already_generated' + # 关键断言:已生成裁决由 generate_excel 表达,执行器携内部编排标记委派并转发结果。 + assert captured['_orchestrator_internal_dispatch'] is True + assert outcome['outcome'] == 'blocked_retryable' + assert outcome['blocking_reason_code'] == 'artifact_generation_failed' def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch): """Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。""" from types import SimpleNamespace - from app.models import ShippingExportArtifact, ShippingNotice + from app.models import ShippingExportArtifact, ShippingOrderTask from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel synced = [] task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL') - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( ShippingExportArtifact, 'query', @@ -1254,11 +1435,12 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching task = SimpleNamespace( + id=13, match_status='partial', shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]}, ) monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( @@ -1273,6 +1455,19 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon 'app.services.shipping_notice.process_gate_executor._task_payload', lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, ) + # 门禁重匹配按当前行级匹配事实推导:匹配完成(有缺口)→ 缺口归属满足性 Gate。 + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'available_qty': 14, 'shortage_qty': 16}}, + ) result = _handle_retry_inventory_matching( execution=SimpleNamespace(task_id=13), @@ -1284,7 +1479,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon # 不能把业务缺口回写成 inventory_matching 的技术失败。 assert result['outcome'] == 'passed' assert 'blocking_reason_code' not in result - assert result['effective_result_json']['shortage']['lines'][0] == { + assert result['effective_result_json']['shortage'][0] == { 'available_qty': 14, 'shortage_qty': 16, } @@ -1355,7 +1550,7 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH') monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) @@ -1370,8 +1565,8 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa assert result['operator_id'] == 9 -def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch): - """旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。""" +def test_inventory_preparation_retry_rejects_legacy_task_without_snapshot(monkeypatch): + """旧 Task 缺订单快照时,库存准备 Gate 必须拒绝执行,不再隐式冻结。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation @@ -1382,7 +1577,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch) ) captured = {} monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( @@ -1420,15 +1615,108 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch) payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5}, ) - # 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。 - assert captured == { - 'target': task, - 'actor_id': 5, - 'expected_order_data_version': 7, - 'freeze_mode': 'manual', - } - assert task.order_snapshot_id == 901 - assert result['outcome'] == 'waiting_external' + # 关键断言:正式 Gate 入口不补冻结,也不进入库存 RPA。 + assert captured == {} + assert task.order_snapshot_id is None + assert result['outcome'] == 'blocked_retryable' + assert result['blocking_reason_code'] == 'inventory_source_routing_required' + + +def test_inventory_preparation_mode_maps_by_action_code(monkeypatch): + """库存准备执行器按已有动作码映射 ensure_inventory mode,禁止人工入口一律 retry_rpa。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-MODE-MAP') + captured: list[dict] = [] + line = SimpleNamespace(source_codes_json=['DBS']) + candidate_set = SimpleNamespace(id=1) + sources = [SimpleNamespace(source_code='DBS')] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: candidate_set, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines', + lambda _task: [line], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources', + lambda _task: sources, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **_: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._task_payload', + lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + # poll 路径会查失败 Attempt;无失败行时继续 ensure_inventory。 + monkeypatch.setattr( + 'app.models.ShippingInventoryPreparationAttempt.query', + SimpleNamespace( + filter_by=lambda **_: SimpleNamespace( + filter=lambda *_a, **_k: SimpleNamespace( + order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None), + ), + order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None), + ), + ), + ) + + execution = SimpleNamespace(task_id=1, id=21, candidate_set_id=None) + gate = SimpleNamespace(gate_code='inventory_preparation') + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5}, + ) + # 显式强制 RPA 码 → mode=retry_rpa。 + assert captured[-1].get('mode') == 'retry_rpa' + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={'action_code': 'poll_inventory_preparation', 'actor_user_id': 5}, + ) + # 只读轮询:默认 auto,禁止自动再试。 + assert captured[-1].get('mode') in (None, 'auto') + assert captured[-1].get('allow_auto_retry') is False + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={ + 'action_code': 'retry_inventory_preparation', + 'trigger': 'gate_attempt_passed', + 'actor_user_id': 5, + }, + ) + # 首次自动投递:不强制 retry_rpa,保留默认 auto(先复用快照)。 + assert captured[-1].get('mode') in (None, 'auto') def test_manual_business_block_is_a_successful_attempt(app): diff --git a/backend/tests/test_shipping_processing_projection.py b/backend/tests/test_shipping_processing_projection.py index f879c397..74a2e52e 100644 --- a/backend/tests/test_shipping_processing_projection.py +++ b/backend/tests/test_shipping_processing_projection.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_processing_projection.py -???????? processing ?????OT ??????PDF ??????? -???Flask/SQLite?create_order_extraction_run?project_conversation_processing? -????? queued / frozen-failed / completed???? PDF ????????hash ????? + processing OT PDF +Flask/SQLite?create_order_extraction_run?project_conversation_processing? + queued / frozen-failed / completed PDF hash """ from __future__ import annotations @@ -29,11 +29,11 @@ from tests.test_shipping_order_extraction_runs import _seed_run_input def _ensure_run_order_task(*, run, intake, document) -> None: """ - ????????? Candidate + OT???? Run.user_task_no? + Candidate + OT Run.user_task_no? - ??????? test_shipping_conversation_processing_api ??? - Candidate ? Run ???? OT ????? order_task ?? - ????? OT ??????? + test_shipping_conversation_processing_api + Candidate ? Run OT order_task + OT """ candidate = ShippingOrderCandidate.query.filter_by( order_extraction_run_id=int(run.id), @@ -63,7 +63,7 @@ def _ensure_run_order_task(*, run, intake, document) -> None: def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): - """???? Run ?????????? OT ??????""" + """ Run OT """ with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A') run_processing, _ = create_order_extraction_run( @@ -135,10 +135,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): completed_nos = {row['user_task_no'] for row in projection.get('completed') or []} assert run_processing.user_task_no in processing_nos assert run_failed.user_task_no in needs_nos - # ???? completed ????????? completed ??? + # completed completed assert run_done.user_task_no in completed_nos - # ????????? OT ?????? + # OT all_nos = list(processing_nos | needs_nos | completed_nos) assert len(all_nos) == len(set(all_nos)) == 3 @@ -150,7 +150,7 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): assert 'view_details' in (failed_task.get('available_actions') or []) primary = failed_task.get('primary_action') assert primary - # ???cancel / view_details ???? CTA?BE-01?? + # cancel / view_details CTA?BE-01 assert primary not in {'cancel_task', 'cancel_run', 'view_details'} done_task = next( @@ -244,7 +244,7 @@ def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app): def test_completed_current_run_hidden_after_viewed(app): - """UI-04??? completed ?????????""" + """UI-04 completed """ with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE') run, _ = create_order_extraction_run( @@ -273,14 +273,14 @@ def test_completed_current_run_hidden_after_viewed(app): ) shown = after['processing'] + after['needs_action'] + list(after.get('completed') or []) assert all(row['user_task_no'] != run.user_task_no for row in shown) - # ?????? completed ?? history????????? + # completed history history_nos = {row['user_task_no'] for row in (after.get('history') or [])} assert run.user_task_no in history_nos assert after['summary']['history'] >= 1 def _set_run_documents(run, documents: list[dict]) -> None: - """?? Run ?? documents????????PDF ?????""" + """ Run documentsPDF """ snapshot = dict(run.input_snapshot_json or {}) intakes = list(snapshot.get('intakes') or []) if not intakes: @@ -293,7 +293,7 @@ def _set_run_documents(run, documents: list[dict]) -> None: def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): - """BE-05?? PDF ?? title ?? None?????? document_names / objects?""" + """BE-05 PDF title None document_names / objects?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF') run, _ = create_order_extraction_run( @@ -321,7 +321,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): row for row in projection['processing'] + projection['needs_action'] if row['user_task_no'] == run.user_task_no ) - # ???????????????????????????? title? + # title? assert task['title'] is None assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' @@ -332,7 +332,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): def test_multi_pdf_task_does_not_use_first_filename_as_title(app): - """? PDF ???title ???file_count=2?objects ????? PDF?""" + """? PDF title file_count=2?objects PDF?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF') run, _ = create_order_extraction_run( @@ -485,7 +485,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): def test_same_filename_different_hash_counts_as_two_pdfs(app): - """???? hash?file_count=2???????????""" + """ hash?file_count=2""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME') run, _ = create_order_extraction_run( @@ -525,7 +525,7 @@ def test_same_filename_different_hash_counts_as_two_pdfs(app): def test_same_hash_different_document_id_counts_as_one_pdf(app): - """? hash ?? document_id?????file_count=1?""" + """? hash document_idfile_count=1?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH') run, _ = create_order_extraction_run( @@ -564,7 +564,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app): ) assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' - # BE-05: title ?? None?? hash ??????????? + # BE-05: title None hash assert task['title'] is None doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document'] assert len(doc_objects) == 1 @@ -572,7 +572,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app): def test_sparse_snapshot_enriched_by_extraction_units(app): - """??? 1 PDF ? Unit ?? 2 ?????? multi + file_count=2?""" + """ 1 PDF ? Unit 2 multi + file_count=2?""" from app.models import ( FileAsset, ShippingOrderDocument, @@ -619,7 +619,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): keep_input_open=True, ) _ensure_run_order_task(run=run, intake=intake, document=document) - # ???? 1 ??????????????????????? + # 1 _set_run_documents(run, [{ 'document_id': int(document.id), 'root_document_id': int(document.id), @@ -660,7 +660,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): @pytest.mark.skip(reason='workflow ledger removed') def test_sparse_snapshot_enriched_by_workflow_items(app): - """??? 1 PDF ?? Run ?? 2 ? WorkflowItem ????? multi?""" + """ 1 PDF Run 2 ? WorkflowItem multi?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W') from app.models import FileAsset, ShippingOrderDocument diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index 4ce0ce9d..807d7a2e 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -225,15 +225,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping(): map_notice_to_processing_status_stage, ) + # [BE-05] Notice 履约态由领域事实(step / 上传 Attempt / 导出 Artifact)派生, + # 不再读取已迁移下线的 Notice.upload_status / export_file_path 聚合字段。无 Attempt + # 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。 uploaded = SimpleNamespace( id=None, - current_step='', upload_status='uploaded', export_file_path=None, + current_step='step7_upload', upload_status='uploaded', export_file_path=None, ) # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( - current_step='', upload_status='pending', export_file_path='/x.xlsx', + current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx', ) assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading') diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 6d7c28ac..d8457239 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -35,6 +35,9 @@ from app.models import ( ) from app.services.file_assets.service import upload_file_asset from app.services.shipping_notice.intake_service import create_shipping_notice_intake +from app.services.shipping_notice.order_extraction_run_service import ( + create_order_extraction_run, +) from app.services.shipping_notice.progress_audit_contract import ( DIRECT_PDF_ALLOWED_STAGES, ) @@ -43,14 +46,18 @@ from app.services.shipping_notice.reconciliation_projector import ( ) from app.services.shipping_notice.shipping_processing_projection import ( _aggregate_eml_order_task_work_items, + _append_unrecognized_plan_attachments, _batch_file_counts, _batch_lifecycle_nodes, _batch_ui_state_from_items, _conversation_processing_from_work_items, + _conversation_submitted_file_count, _display_work_items_from_current_files, _eml_aggregate_document_children, + _eml_leaf_processing_stage, _processing_ui_state_from_item, _project_order_task_work_item, + get_shipping_processing_work_item, map_run_status_to_processing_status, project_conversation_processing_summary, map_run_to_processing_stage, @@ -164,18 +171,19 @@ def test_batch_lifecycle_nodes_maps_formal_gate_stages( @pytest.mark.parametrize( ('item', 'expected_lifecycle_stage'), [ - # 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。 - ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'), - # 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。 + # [B''] 有效处理阶段已是权威:document_parsing 直接归入接收解析, + # 正式 Gate(inventory_matching)不能把它抬升到通知准备。 + ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'intake_parse'), + # 无处理阶段时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段(兜底)。 ({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'), ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ], ) -def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason( +def test_batch_lifecycle_nodes_uses_processing_stage_or_owning_reason( item: dict[str, object], expected_lifecycle_stage: str, ) -> None: - """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" + """[B''] 批次五阶段以处理阶段为权威;无处理阶段时才以阻断原因 owning gate 兜底。""" nodes = _batch_lifecycle_nodes([{ **item, 'status': 'waiting_human', @@ -268,8 +276,9 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N }] -def test_processing_ui_state_exposes_shared_gate_authority() -> None: - """批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。""" +def test_processing_ui_state_exposes_processing_stage_authority() -> None: + """[B''] 批次投影以有效处理阶段为权威:document_parsing 归入接收解析, + 正式库存 Gate(inventory_matching)不能把它升降到通知准备,authority 记为 processing_stage。""" state = _processing_ui_state_from_item({ 'user_status': 'waiting_human', 'user_stage': 'document_parsing', @@ -278,8 +287,8 @@ def test_processing_ui_state_exposes_shared_gate_authority() -> None: 'available_actions': [], }) - assert state['lifecycle_stage'] == 'fulfillment_prep' - assert state['lifecycle_authority'] == 'process_gate' + assert state['lifecycle_stage'] == 'intake_parse' + assert state['lifecycle_authority'] == 'processing_stage' def test_processing_ui_state_without_candidate_does_not_expose_lifecycle_entries() -> None: @@ -499,6 +508,77 @@ def test_order_task_current_gate_ignores_empty_review_case(app) -> None: assert item['current_gate'] is None +def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None: + """ + 无正式 Notice 时仍须读 OT 活跃 Execution,禁止 waiting_review 误合成 open_order_review。 + + 关键断言:库存满足性人工阻断(inventory_sufficiency)发生在 Notice 创建前; + work-item 右卡若回落 order_freeze_readiness,会永久显示「订单复核」而非缺口恢复。 + """ + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + from app.services.shipping_notice.shipping_processing_projection import ( + get_shipping_processing_work_item, + ) + + user, agent, session, intake, _document = _seed_run_input(suffix='OT-EXEC-NO-NOTICE') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + task = ShippingOrderTask( + task_no='OT-EXEC-NO-NOTICE', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=run.id, + owner_agent_id=int(agent.id), + candidate_id=None, + status='waiting_review', + stage='step5_match_inventory', + progress_version=3, + ) + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-OT-EXEC-NO-NOTICE', + task_id=int(task.id), + status='blocked', + current_gate_code='inventory_sufficiency', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + task.active_process_execution_id = int(execution.id) + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='inventory_sufficiency', + sequence_no=16, + status='blocked_manual', + evaluation_version=1, + lock_version=1, + blocking_reason_code='inventory_shortage_review_required', + next_action_code='open_shortage_review', + )) + run.user_task_no = task.task_no + db.session.commit() + + item = get_shipping_processing_work_item( + user_id=user.id, + work_item_type='order_task', + work_item_no=task.task_no, + ) + + assert item['current_gate']['gate_code'] == 'inventory_sufficiency' + assert item['current_gate']['next_action_code'] in { + 'open_shortage_review', + 'retry_inventory_matching', + 'retry_inventory_preparation', + } + assert item['current_gate']['next_action_code'] != 'open_order_review' + assert item['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert item['ui_state']['status'] == 'waiting_human' + primary = (item.get('ui_state') or {}).get('primary_action') or {} + assert str(primary.get('code') or '') != 'open_order_review' + + def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None: """历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。""" with app.app_context(): @@ -757,6 +837,8 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> assert _batch_ui_state_from_items(work_items) == { 'status': 'waiting_human', 'stage': 'inventory_matching', + # 5 业务阶段随批次 ui_state 一并下发,供三面阶段口径同源。 + 'lifecycle_stage': 'fulfillment_prep', 'blocking_reason': {'code': 'inventory_match_failed'}, 'primary_action': {'code': 'open_inventory_match_review'}, 'secondary_actions': [], @@ -987,6 +1069,32 @@ def test_eml_aggregate_projects_every_business_document_when_some_lack_order_tas assert unassigned['available_actions'] == [] +def test_eml_leaf_processing_stage() -> None: + """EML 处理中叶子按真实单元/解析状态推进 15 阶,不再整批折叠为 candidate_creating。""" + assert _eml_leaf_processing_stage( + unit_status='merging_supplement', parse_status='parsed', source_type='eml', + ) == 'email_adjudicating' + assert _eml_leaf_processing_stage( + unit_status='extracting', parse_status='parsed', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='matching_profile', parse_status='parsed', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='candidate_ready', parse_status='parsed', source_type='eml', + ) == 'candidate_creating' + assert _eml_leaf_processing_stage( + unit_status='', parse_status='parsing', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='', parse_status='parsed', source_type='eml', + ) == 'candidate_creating' + # 直接 PDF 永远不出现 EML 专属的交叉裁决阶段。 + assert _eml_leaf_processing_stage( + unit_status='merging_supplement', parse_status='parsed', source_type='direct_pdf', + ) == 'candidate_creating' + + def test_eml_order_intake_projects_business_documents_without_candidates_as_processing(app) -> None: """无 OT/候选的 EML 仍完整展示业务附件;未形成候选不是异常或待人工门禁。""" with app.app_context(): @@ -1100,8 +1208,8 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children']) -def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None: - """未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。""" +def test_summary_displays_selected_supporting_attachment_outside_lifecycle_counts(app) -> None: + """已选未知附件应显示为诊断行,但不得进入已识别数、五阶段或业务动作。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input @@ -1120,6 +1228,26 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count order_extraction_status='completed', ) db.session.add(supporting_document) + run, _ = create_order_extraction_run( + user=user, + agent_id=_agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id)}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': primary_document.attachment_key, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': True}, + # 重解析留下的未选快照不能覆盖此前已选结论。 + {'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': False}, + ], + }, + } + flag_modified(run, 'input_snapshot_json') db.session.commit() payload = project_conversation_processing_summary( @@ -1133,13 +1261,85 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count for child in row.get('aggregate_children', []) ] - # 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。 + # 关键断言:主业务文件与用户已选的未知附件都可见。 assert int(primary_document.id) in { int(child['source_summary']['document_id']) for child in leaves } - assert int(supporting_document.id) not in { - int(child['source_summary']['document_id']) for child in leaves + supporting_leaf = next(child for child in leaves if int( + child['source_summary']['document_id'] + ) == int(supporting_document.id)) + assert supporting_leaf['facts']['recognized'] is False + assert supporting_leaf['available_actions'] == [] + assert payload['conversation_processing']['summary']['total_files'] == 1 + assert payload['conversation_processing']['summary']['submitted_files'] == 2 + assert sum( + node['summary']['total'] + for node in payload['conversation_processing']['lifecycle_nodes'] + ) == 1 + + +def test_summary_emits_selected_pending_leaves_in_empty_materialization_window(app) -> None: + """[回归] 全空窗期:附件已被冻结选择、但尚未物化任何 Document 时,首屏摘要也必须 + 展示 pending(recognized=false)文件名,而不能只有 submitted/total 计数 + 空 status_groups。 + + 对应交互:刚发送批次、尚未识别出文件时,聊天卡显示「共 N 个文件 · 已识别 0/N」, + 若 status_groups 为空前端只能转圈。修复后摘要与详情共用 pending 叶子补齐契约, + 让前端在物化前即可列出这些待识别文件。 + """ + with app.app_context(): + from unittest.mock import patch + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-EMPTY-WINDOW', + ) + intake.source_type = 'eml' + # 模拟「已选但尚未物化」:删除该 intake 下的 Document,只保留冻结计划附件。 + db.session.delete(document) + db.session.flush() + with patch( + 'app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents', + ) as materialize: + run, _ = create_order_extraction_run( + user=user, + agent_id=_agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + materialize.assert_not_called() + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id), 'documents': []}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': 'n1.pdf', 'filename': 'N1.pdf', 'content_hash': 'x' * 64, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': 'n2.pdf', 'filename': 'N2.pdf', 'content_hash': 'y' * 64, 'selected': True}, + ], + }, } + flag_modified(run, 'input_snapshot_json') + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + conv = payload['conversation_processing'] + + # 关键断言:提交基=2、已识别=0;但 status_groups 必须能列出 pending 文件名。 + assert conv['summary']['submitted_files'] == 2 + assert conv['summary']['total_files'] == 0 + leaves = [ + child + for rows in conv['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + pending = [child for child in leaves if (child.get('facts') or {}).get('recognized') is False] + assert len(pending) == 2 + filenames = {str((child.get('source_summary') or {}).get('filename') or '') for child in pending} + assert {'N1.pdf', 'N2.pdf'} <= filenames def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None: @@ -1168,8 +1368,53 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app assert summary['completed_files'] == 0 -def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: - """摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。""" +def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None: + """混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, completed_document = _seed_run_input( + suffix='SUMMARY-MIXED-EML-LEAF-STATUS', + ) + intake.source_type = 'eml' + completed_document.order_extraction_status = 'completed' + processing_document = ShippingOrderDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='still-processing.pdf', + filename='still-processing.pdf', + content_hash='m' * 64, + classification='order_notice', + parse_status='parsed', + order_extraction_status='not_started', + ) + db.session.add(processing_document) + db.session.commit() + + projection = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + )['conversation_processing'] + + # 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。 + processing_rows = projection['status_groups']['processing'] + completed_rows = projection['status_groups']['completed'] + assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [ + processing_document.id, + ] + assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [ + completed_document.id, + ] + assert projection['summary']['processing_files'] == 1 + assert projection['summary']['completed_files'] == 1 + assert projection['summary']['total_files'] == 2 + + +def test_summary_lifecycle_authority_is_processing_stage_for_stale_completed_task(app) -> None: + """[B''] 阶段唯一权威:OT.stage='completed' 属遗留/兼容字段,不推动阶段。投影层已把叶子 + user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation),因此生命周期仍是 + fulfillment_prep,authority 记为 processing_stage。正式 Gate 不再声称阶段裁决; + Gate 阻断仅保留在用户状态与「订单检查」面板,且阶段权威不改变用户状态。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input @@ -1197,12 +1442,12 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: db.session.flush() order_task.shipping_notice_id = notice.id execution = ShippingProcessExecution( - execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked', + execution_no='SPE-SUMMARY-GATE', task_id=order_task.id, status='blocked', current_gate_code='inventory_preparation', lock_version=1, ) db.session.add(execution) db.session.flush() - notice.active_process_execution_id = execution.id + order_task.active_process_execution_id = execution.id db.session.add(ShippingProcessGate( execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11, status='blocked_manual', evaluation_version=1, lock_version=1, @@ -1223,14 +1468,110 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: ] leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id) - # 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。 + # 关键断言(B''):阶段以共享裁判器的 processing_stage 为唯一权威。 + # 投影层已把叶子 user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation), + # 因此生命周期仍是 fulfillment_prep;但 authority 已是 processing_stage, + # 正式 Gate 不再是阶段来源。OT.stage='completed' 属遗留/兼容字段,不推动阶段。 + assert leaf['user_stage'] == 'inventory_preparation' assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert leaf['ui_state']['lifecycle_authority'] == 'processing_stage' + # Gate 阻断事实仍在(用户状态与「订单检查」面板),不因阶段权威变更而消失。 assert leaf['user_status'] == 'waiting_human' assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout' # 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。 assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human' +def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app) -> None: + """首屏摘要必须按 OT.id 批量加载 ProcessExecution,禁止误用 candidate_id。 + + 回归:candidate.id ≠ OT.id 时,若用 tasks_by_candidate_id 的 key 去查 + ShippingProcessExecution.task_id,Gate 整批查空;叶子会退化成遗留 stage + + open_order_review,批次中心同时失去五阶段入口与门禁主按钮。 + """ + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-OT-ID-NOT-CANDIDATE', + ) + # [STEP 1] 垫高 Candidate 序号,强制 candidate.id ≠ OT.id(SQLite 默认同号会掩盖 bug)。 + for idx in range(3): + db.session.add(ShippingOrderCandidate( + candidate_no=f'CAND-PAD-{idx}-{uuid.uuid4().hex[:8]}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'summary-pad-{idx}-{uuid.uuid4().hex[:8]}', + candidate_status='rejected', + is_current_version=False, + po_number=f'PO-PAD-{idx}', + )) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-SUMMARY-OT-ID-{uuid.uuid4().hex[:8]}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'summary-ot-id-{uuid.uuid4().hex[:8]}', + candidate_status='accepted', + is_current_version=True, + po_number='PO-SUMMARY-OT-ID', + ) + db.session.add(candidate) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-SUMMARY-OT-ID', + user_id=user.id, + conversation_id=session.session_id, + intake_id=intake.id, + candidate_id=candidate.id, + status='waiting_review', + stage='step3_inventory_prepare', + ) + db.session.add(order_task) + db.session.flush() + assert int(candidate.id) != int(order_task.id) + execution = ShippingProcessExecution( + execution_no='SPE-SUMMARY-OT-ID', + task_id=int(order_task.id), + status='blocked', + current_gate_code='inventory_preparation', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + order_task.active_process_execution_id = int(execution.id) + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='inventory_preparation', + sequence_no=13, + status='blocked_retryable', + evaluation_version=1, + lock_version=1, + blocking_reason_code='inventory_rpa_export_failed', + next_action_code='retry_inventory_preparation', + )) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + leaf = next( + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + + # 关键断言:Gate 命中后五阶段与库存恢复主操作必须同时存在。 + assert leaf['current_gate']['gate_code'] == 'inventory_preparation' + assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert len(leaf['ui_state']['lifecycle_entries']) == 5 + assert leaf['ui_state']['primary_action']['code'] == 'retry_inventory_preparation' + assert leaf['ui_state']['primary_action']['code'] != 'open_order_review' + + def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None: """接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。""" with app.app_context(): @@ -1285,6 +1626,74 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) - # 首屏摘要不得把阶段导航 open_order_review 冒充为业务主动作; # 否则前端隐藏导航后,用户将失去真实的重解析入口。 assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse' + # 批次进度中心与全生命周期工作台必须共用同一阶段权威:空 Candidate Case + # 只能停在接收解析,不能因 Case 存在就投影成订单复核。 + assert summary_leaf['ui_state']['lifecycle_stage'] == 'intake_parse' + assert summary_leaf['source_summary']['candidate_count'] == 0 + assert summary_leaf['intake_parse_authorized'] is True + assert summary_leaf['ui_state']['lifecycle_entries'][0] == { + 'code': 'intake_parse', + 'state': 'current', + 'target_surface': 'order_lifecycle_workbench', + } + assert summary_leaf['ui_state']['lifecycle_entries'][1]['state'] == 'unavailable' + + +def test_summary_leaf_ignores_unbound_document_candidate_for_empty_case(app) -> None: + """文档上有带 PO 的当前 Candidate,但 Case 未绑定时,摘要不得升到订单复核。 + + 回归:批次进度中心曾用「文档 Candidate / Case 存在」抬升 waiting_review→order_review, + 而 order-review-queue 只认 Case.candidate_id 的可复核 Candidate,导致两侧阶段不一致。 + """ + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit + from app.services.shipping_notice.order_review_projection import _serialize_review_case_summary + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-UNBOUND-CANDIDATE', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + unit = run.extraction_plan.units[0] + unit.status = 'review_required' + unit.reason_code = 'generic_extraction_disabled' + review_case = ensure_review_case_for_unit(run=run, unit=unit) + # 文档已有当前 Candidate+PO,但故意不绑到 Case:模拟摘要误升订单复核的脏数据形态。 + assert review_case.candidate_id is None + db.session.add(ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-UNBOUND', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key='summary-unbound', + order_extraction_run_id=run.id, + is_current_version=True, + candidate_status='provisional', + po_number='4518814494', + )) + db.session.commit() + + summary_payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in summary_payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + queue_item = _serialize_review_case_summary(review_case, run=run) + + # 关键断言:摘要与队列对同一 Case 给出相同生命周期阶段。 + assert summary_leaf['ui_state']['lifecycle_stage'] == 'intake_parse' + assert queue_item['lifecycle_stage'] == 'intake_parse' + assert summary_leaf['intake_parse_authorized'] is True + assert queue_item['intake_parse_authorized'] is True + assert summary_leaf['source_summary']['candidate_count'] == 0 + assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse' def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> None: @@ -1327,6 +1736,9 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No assert summary_leaf['ui_state']['primary_action']['code'] == 'edit_draft' assert 'edit_draft' in summary_leaf['available_actions'] assert 'reparse' not in summary_leaf['available_actions'] + assert summary_leaf['ui_state']['lifecycle_stage'] == 'order_review' + assert summary_leaf['source_summary']['candidate_count'] == 1 + assert summary_leaf['intake_parse_authorized'] is False def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None: @@ -1429,6 +1841,16 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: first_unit.status = 'review_required' first_unit.reason_code = 'business_table_not_found' second_unit.reason_code = 'business_table_not_found' + # [BE-05] 待复核 PDF 必须已有当前有效 Candidate,Review Case 才开放订单复核入口; + # 无候选时后端裁决为接收解析(intake_parse),不能当作订单复核待人工。 + for _doc, _k in ((first_document, 'eml-sibling-1'), (second_document, 'eml-sibling-2')): + db.session.add(ShippingOrderCandidate( + candidate_no=f'CAND-SIBLING-{uuid.uuid4().hex[:8]}', + intake_id=int(intake.id), primary_document_id=int(_doc.id), + candidate_key=_k, order_extraction_run_id=int(run.id), + is_current_version=True, candidate_status='provisional', + )) + db.session.flush() ensure_review_case_for_unit(run=run, unit=first_unit) ensure_review_case_for_unit(run=run, unit=second_unit) run.status = 'partially_completed' @@ -1440,16 +1862,20 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: for document_id in (int(first_document.id), int(second_document.id)): leaf = leaves[document_id] + # [BE-05] 未确认 Candidate Review Case 由后端 bundle 权威裁决为 idle(待用户处置), + # 用户阶段固定在订单复核;建单前 Gate 由 order_review_build / mark_non_order 唯一给出。 assert leaf['user_status'] == 'waiting_human' assert leaf['user_stage'] == 'order_review' - assert leaf['blocking_reason']['code'] == 'business_table_not_found' + assert leaf['current_gate']['gate_code'] == 'order_review_build' + assert leaf['current_gate']['next_action_code'] == 'mark_non_order' + # 同一 Run 的兄弟失败 PDF 只能影响自身;待复核 PDF 仍必须保留其复核业务入口。 assert leaf['ui_state']['primary_action'] is not None, leaf - assert leaf['ui_state']['primary_action']['code'] == 'open_order_review' + assert leaf['ui_state']['primary_action']['code'] == 'edit_draft' failed_leaf = leaves[int(third_document.id)] assert failed_leaf['user_status'] == 'failed' assert failed_leaf['user_stage'] == 'document_parsing' assert failed_leaf['blocking_reason']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE' - assert failed_leaf['ui_state']['primary_action']['code'] == 'retry_order_extraction' + assert failed_leaf['ui_state']['primary_action']['code'] == 'reparse' assert item['aggregate_summary']['needs_action'] == 2 assert item['aggregate_summary']['failed'] == 1 @@ -1500,8 +1926,14 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document # 顶层字段与 ui_state 必须是同一次后端裁决,供批次与工作台共用。 assert candidate_leaf['lifecycle_stage'] == candidate_leaf['ui_state']['lifecycle_stage'] assert candidate_leaf['lifecycle_entries'] == candidate_leaf['ui_state']['lifecycle_entries'] + # 有效 Candidate 的主 PDF 开放订单复核生命周期:当前阶段为 order_review, + # 五个入口按 可用/当前/不可用 几何给出。 + assert candidate_leaf['ui_state']['lifecycle_stage'] == 'order_review' + assert [entry['code'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [ + 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', + ] assert [entry['state'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] assert sibling_leaf['source_summary']['candidate_count'] == 0 assert sibling_leaf['lifecycle_entries'] == sibling_leaf['ui_state']['lifecycle_entries'] @@ -1550,10 +1982,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No projection = _conversation_processing_from_work_items(items) failed = projection['status_groups']['failed'] + processing = projection['status_groups']['processing'] assert len(failed) == 1 assert failed[0]['user_task_no'] == 'INTAKE:SNI-BATCH-1' assert failed[0]['title'] == 'FWD: Shanghai shipping notice' - assert len(failed[0]['aggregate_children']) == 2 + assert [child['source_summary']['filename'] for child in failed[0]['aggregate_children']] == ['a.pdf'] + assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['b.pdf'] assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['summary']['total_files'] == 2 @@ -1570,6 +2004,42 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No } +def test_conversation_projection_repeats_mixed_eml_per_leaf_status(app) -> None: + """混合状态 EML 必须在各 PDF 自身状态分区独立显示,不能混入已完成区。""" + with app.app_context(): + items = _aggregate_eml_order_task_work_items([ + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-DONE', + 'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS', + 'root_order_task_no': 'OT-MIXED-DONE', + 'source_summary': {'document_id': 301, 'filename': 'done.pdf'}, + 'status': 'completed', 'stage': 'completed', + 'user_group': 'completed', 'user_status': 'completed', 'user_stage': 'completed', + 'available_actions': [], 'facts': {'upload_state': 'completed'}, + }, + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-RUNNING', + 'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS', + 'root_order_task_no': 'OT-MIXED-DONE', + 'source_summary': {'document_id': 302, 'filename': 'running.pdf'}, + 'status': 'processing', 'stage': 'freight_upload', + 'user_group': 'processing', 'user_status': 'running', 'user_stage': 'freight_upload', + 'available_actions': [], 'facts': {'upload_state': 'not_created'}, + }, + ]) + + projection = _conversation_processing_from_work_items(items) + + completed = projection['status_groups']['completed'] + processing = projection['status_groups']['processing'] + assert [child['source_summary']['filename'] for child in completed[0]['aggregate_children']] == ['done.pdf'] + assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['running.pdf'] + assert completed[0]['aggregate_summary']['intake_no'] == 'SNI-MIXED-STATUS' + assert completed[0]['aggregate_summary']['total'] == 2 + assert completed[0]['aggregate_summary']['in_group'] == 1 + assert processing[0]['aggregate_summary']['in_group'] == 1 + + def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) -> None: """会话与批次中心均以 Intake 原始 EML 文件名标识同一邮件。""" with app.app_context(): @@ -1585,6 +2055,7 @@ def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) }, 'status': 'processing', 'stage': 'document_parsing', 'user_status': 'processing', 'user_stage': 'document_parsing', + 'user_group': 'processing', 'available_actions': [], 'facts': {'upload_state': 'not_created'}, }]) @@ -1826,7 +2297,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi assert item['current_gate']['attempt_no'] == 2 assert item['source_summary']['failure_reason_code'] == 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' assert item['source_summary']['parse_attempt_count'] == 2 - assert 'retry' in item['available_actions'] + assert 'retry_parse' in item['available_actions'] def test_project_conversation_processing_items_includes_work_items(app, shipping_user): @@ -1887,7 +2358,9 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping assert solo['ui_state']['lifecycle_stage'] == 'intake_parse' assert solo['ui_state']['blocking_reason'] is None assert solo['ui_state']['primary_action'] is None - assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions'] + # [BE-05] 顶层 available_actions 已在 API 边界剥离(旧镜像,动作唯一合同是 ui_state); + # secondary_actions 即为后端裁决的可用动作 DTO。 + assert [action['code'] for action in solo['ui_state']['secondary_actions']] == ['view_result'] assert all(action['enabled'] is True for action in solo['ui_state']['secondary_actions']) conversation_row = next( row @@ -2084,6 +2557,63 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship assert item['source_summary']['filename'] == document.filename +def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(app, shipping_user): + """ + 单工作项读取必须复用统一生命周期 DTO,避免工作台另读 Case/Queue 补阶段。 + + 断言:货代上传阶段的单工作项响应下发 freight_upload 当前入口。 + """ + del shipping_user + with app.app_context(): + from app.models import ShippingNotice, ShippingOrderTask + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, _agent, session, intake, _document = _seed_run_input(suffix='SINGLE-WORK-ITEM-UI') + run = _materialized_run(user=user, agent=_agent, session=session, intake=intake) + # [BE-05] current_step / shipping_notice_id 已从 Notice 侧迁移:current_step 挪到 + # ShippingOrderTask,Notice 通过 order_task_id 反指 OT,进度由 OT.stage 驱动。 + order_task = ShippingOrderTask( + task_no='OT-SINGLE-WORK-ITEM-UI', + user_id=user.id, + conversation_id=session.session_id, + intake_id=int(intake.id), + extraction_run_id=int(run.id), + current_step='step7_upload_freight', + status='automating', + stage='freight_uploading', + progress_version=1, + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-SINGLE-WORK-ITEM-UI', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() + run.user_task_no = order_task.task_no + db.session.commit() + + item = get_shipping_processing_work_item( + user_id=user.id, + work_item_type='order_task', + work_item_no=order_task.task_no, + ) + + assert item['user_stage'] == 'freight_upload' + assert item['ui_state']['lifecycle_stage'] == 'freight_upload' + lifecycle_states = { + entry['code']: entry['state'] + for entry in item['ui_state']['lifecycle_entries'] + } + assert lifecycle_states['fulfillment_prep'] == 'available' + assert lifecycle_states['freight_upload'] == 'current' + + def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user): """同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。""" @@ -2135,7 +2665,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi """候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。""" del shipping_user with app.app_context(): - from app.models import ShippingOrderCandidate + from app.models import ShippingOrderCandidate, ShippingOrderReviewCase from app.services.shipping_notice.order_review_service import ensure_run_review_cases from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import _materialized_run @@ -2147,6 +2677,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi candidate_no=f'OCAND-EML-{uuid.uuid4().hex[:8]}', intake_id=intake.id, primary_document_id=document.id, candidate_key='eml-case-leaf', order_extraction_run_id=run.id, is_current_version=True, + candidate_status='provisional', ) db.session.add(candidate) db.session.flush() @@ -2182,7 +2713,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi assert result[0]['user_status'] == 'waiting_human' assert result[0]['user_stage'] == 'order_review' assert leaf['case_no'] == case.case_no - assert leaf['user_status'] == 'idle' + assert leaf['user_status'] == 'waiting_human' assert leaf['user_stage'] == 'order_review' assert leaf['current_gate']['gate_code'] == 'order_review_build' assert 'edit_draft' in leaf['available_actions'] @@ -2320,26 +2851,29 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u user, agent, session, intake, _document = _seed_run_input(suffix='OT-NOTICE') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) - notice = ShippingNotice( - task_no='SN-NOTICE-PROJ-1', - user_id=user.id, - conversation_id=session.session_id, - source_type='manual', - current_step='step7_upload_freight', - ) - db.session.add(notice) - db.session.flush() + # [BE-05] current_step 已迁移到 ShippingOrderTask;Notice 经 order_task_id 反指 OT, + # 不再使用 shipping_notice_id 反向外键。 order_task = ShippingOrderTask( task_no='OT-NOTICE-PROJ-1', user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), + current_step='step7_upload_freight', status='processing', stage='candidate_creating', progress_version=1, ) db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-NOTICE-PROJ-1', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() run.user_task_no = order_task.task_no db.session.commit() @@ -2355,15 +2889,15 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u assert synced['stage'] == 'freight_uploading' # 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。 - notice.upload_status = 'uploaded' + # [BE-05] upload_status 已迁移到上传 Attempt 表,Notice 上不再读取该字段; + # 无成功 Attempt 时投影保持自动上传中(automating/freight_uploading),绝不进入完成。 order_task.status = 'automating' order_task.stage = 'freight_uploading' db.session.commit() unverified = _project_order_task_work_item(run) - assert unverified['status'] == 'waiting_human' assert unverified['stage'] == 'freight_uploading' - assert unverified['user_status'] == 'waiting_human' assert unverified['verified_upload_success'] is False + assert unverified['status'] != 'completed' def test_conversation_processing_rebuild_prefers_work_item_user_status(app): @@ -2402,6 +2936,142 @@ def test_conversation_processing_rebuild_prefers_work_item_user_status(app): assert item['user_status'] == 'running' rebuilt = _conversation_processing_from_work_items([item]) - row = rebuilt['processing'][0] + row = rebuilt['status_groups']['processing'][0] assert row['status_label'] == 'processing' assert row['group'] == 'processing' + + +def test_submitted_files_is_independent_of_unmaterialized_intake() -> None: + """[回归] 发送后物化前:提交基 submitted_files 应 ≥1,而 total_files(已识别)为 0。 + + 用户刚提交 1 份邮件时,冻结选择计划已能给出 selected_attachment_count=1;但附件 + Document 尚未被 worker 物化,_batch_file_counts 对该 EML(.eml 不计数)返回 0。 + 此前以 total_files 作为主计数导致「共 0 个文件 → 自动变 1」的翻转;引入 + submitted_files 后主计数不再归零,已识别进度由 total_files 单独体现。 + """ + work_items = [{ + 'work_item_type': 'order_intake', + 'work_item_no': 'SNI-EML-UNMATERIALIZED', + 'source_type': 'eml', + 'intake_no': 'SNI-EML-UNMATERIALIZED', + 'user_group': 'processing', + 'user_status': 'running', + 'user_stage': 'intake_parse', + 'status': 'processing', + 'source_summary': { + 'filename': 'order.eml', + 'document_count': 0, + 'document_id': None, + }, + 'aggregate_children': [], + }] + projection = _conversation_processing_from_work_items(work_items, submitted_files=1) + summary = projection['summary'] + # 主计数:提交基,不为 0(用户实际提交了 1 份)。 + assert summary['submitted_files'] == 1 + # 已识别数:物化前为 0,但不再顶替主计数。 + assert summary['total_files'] == 0 + + +def test_conversation_submitted_file_count_reflects_frozen_selection(app) -> None: + """[回归] submitted_files 应等于冻结选择计划已选数 + 直传 PDF 数,且物化与否无关。 + + 直传 PDF Intake 的冻结选择计划不设置 selected_attachment_count(该字段只服务 + EML 附件),此时每个直传 PDF Intake 计 1 个业务文件,保证提交基主计数 ≥1。 + """ + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input( + suffix='SUBMITTED-COUNT', + ) + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + # 直传 PDF Intake 本身即为 1 个业务文件:提交基主计数必须 ≥1(物化与否无关)。 + assert _conversation_submitted_file_count( + user_id=int(user.id), + conversation_id=session.session_id, + ) == 1 + + +def test_conversation_submitted_file_count_deduplicates_reparse_attachment_snapshot(app) -> None: + """重解析快照重复记录同一已选附件时,提交基只能计一次。""" + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='SUBMITTED-DEDUP') + intake.source_type = 'eml' + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], keep_input_open=True, + ) + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id)}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True}, + ], + }, + } + flag_modified(run, 'input_snapshot_json') + db.session.commit() + + assert _conversation_submitted_file_count( + user_id=int(user.id), conversation_id=session.session_id, + ) == 1 + + +def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized() -> None: + """[回归] 已选但尚未物化/未识别的计划附件应出现在列表,但不计入已识别 total_files。 + + 对应交互:批次显示「已识别 1/2」时,EML 列表必须展示全部计划附件(含未识别行), + 否则无法排查「为什么这份没识别」。物化附件按识别状态计数,未识别计划行仅作诊断。 + """ + intake_no = 'SNI-EML-PLAN' + recognized_child = { + 'work_item_type': 'order_intake', + 'work_item_no': 'DOC-10', + 'source_type': 'eml', + 'intake_no': intake_no, + 'user_status': 'waiting_human', + 'user_group': 'waiting_human', + 'user_stage': 'order_review', + 'status': 'waiting_human', + 'source_summary': { + 'filename': 'F91D1.pdf', 'document_id': 10, 'content_hash': 'a' * 64, + }, + 'facts': {}, + } + planned_by_intake_no = { + intake_no: [ + { + 'intake_no': intake_no, 'attachment_key': 'f91.pdf', + 'filename': 'F91D1.pdf', 'content_hash': 'a' * 64, 'selected': True, + }, + { + 'intake_no': intake_no, 'attachment_key': 'f92.pdf', + 'filename': 'F92.pdf', 'content_hash': 'b' * 64, 'selected': True, + }, + ], + } + merged = _append_unrecognized_plan_attachments( + intake=SimpleNamespace(intake_no=intake_no), + aggregate_children=[recognized_child], + planned_by_intake_no=planned_by_intake_no, + ) + # 列表同时包含已识别与未识别计划行。 + filenames = [str((child.get('source_summary') or {}).get('filename') or '') for child in merged] + assert 'F91D1.pdf' in filenames + assert 'F92.pdf' in filenames + unrecognized = [child for child in merged if (child.get('facts') or {}).get('recognized') is False] + assert len(unrecognized) == 1 + assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf' + # 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。 + assert _batch_file_counts(merged)['total_files'] == 1 diff --git a/backend/tests/test_shipping_projection_cross_surface.py b/backend/tests/test_shipping_projection_cross_surface.py index b3573663..7d213f31 100644 --- a/backend/tests/test_shipping_projection_cross_surface.py +++ b/backend/tests/test_shipping_projection_cross_surface.py @@ -16,6 +16,24 @@ from app.services.shipping_notice.progress_audit_contract import ( EML_ONLY_PROCESSING_STAGES, SHIPPING_PROCESSING_STAGES, ) +from app.services.shipping_notice.lifecycle_projection import ( + LIFECYCLE_STAGE_BY_PROCESSING_STAGE, + LIFECYCLE_STAGE_CODES, +) + + +def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage(): + """统一口径:每个 SHIPPING_PROCESSING_STAGES 细粒度阶段都必须映射到一个合法 5 业务阶段。 + + 该映射是「15 阶权威 → 5 阶展示」的唯一桥梁;遗漏任一值会导致工作台/批次中心 + 出现未归类阶段,使前后端阶段口径不一致。此处仅作完整性约束,不改变任何阶段语义。 + """ + for stage in SHIPPING_PROCESSING_STAGES: + mapped = LIFECYCLE_STAGE_BY_PROCESSING_STAGE.get(stage) + assert mapped is not None, f"SHIPPING_PROCESSING_STAGES.{stage!r} 缺少 15->5 映射" + assert mapped in LIFECYCLE_STAGE_CODES, ( + f"映射目标 {mapped!r} 不是合法 5 业务阶段({tuple(LIFECYCLE_STAGE_CODES)})" + ) def test_fifteen_stages_inventory_source_before_review(): @@ -32,24 +50,25 @@ def test_fifteen_stages_inventory_source_before_review(): def test_sync_order_task_stage_must_be_processing_stage(app): """任务工作台与对话投影均读 OT.stage;写入值必须是冻结的 15 阶之一。""" with app.app_context(): - notice = ShippingNotice( - task_no='SN-CROSS-SURFACE-001', - source_type='manual', - po_number='PO-CROSS-001', - order_lines_migration_status='pending', - ) - db.session.add(notice) - db.session.flush() + # [BE-05] 订单数据已迁移到 ShippingOrderTask/Extraction;Notice 不再承载 + # po_number/order_lines_migration_status。OT 是进度写入口,Notice 通过 + # order_task_id 反指 OT,恢复测试原本「通知 + 任务」配对结构。 order_task = ShippingOrderTask( task_no='OT-CROSS-SURFACE-001', user_id=1, - shipping_notice_id=int(notice.id), stage='waiting_review', status='waiting_review', progress_version=1, ) db.session.add(order_task) db.session.flush() + notice = ShippingNotice( + task_no='SN-CROSS-SURFACE-001', + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() sync_order_task_processing_state( order_task, diff --git a/backend/tests/test_shipping_projection_gate_equivalence.py b/backend/tests/test_shipping_projection_gate_equivalence.py new file mode 100644 index 00000000..6dcd4c61 --- /dev/null +++ b/backend/tests/test_shipping_projection_gate_equivalence.py @@ -0,0 +1,467 @@ +""" +backend/tests/test_shipping_projection_gate_equivalence.py + +用途:锁定「展示单源」契约 §2.1 —— 在真实 A 管线(_project_order_task_work_item) +下,A 渲染出的 primary_action / blocking_reason / user_status 必须与 C +(project_user_gate_summary)等价。这是 flatten C→A==B==C 的**前置等价性验证**: +仅当 A==C 才允许删除 A 的 STEP3/6/7 二次推导,否则会改变对话流/批次进度中心/右卡展示。 + +依赖:pytest、app fixture、tests 已有的 _seed_run_input / _materialized_run、 + shipping_processing_projection._project_order_task_work_item、 + process_gate_projection.project_user_gate_summary。 + +逻辑:为每个代表性 Gate 场景构建 OT+Notice+Run+Execution+Gate 持久化事实, + 运行 A 管线拿到渲染 DTO,新调 C 拿到权威摘要;断言 A 的动作码/阻断码与 C 一致。 + 若断言失败,即为「A 与 C 漂移」,必须先修 C 侧语义再 flatten。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ShippingOrderTask + + +@pytest.fixture +def gate_chain(app): + """构造挂接 Notice 的 OT + Run(复用既有 seed),返回主键供测试内重载。 + + 与 test_shipping_workbench_service_chains.workbench_chain_ids 同构,但额外 + 允许测试追加 Execution/Gate 后驱动完整 A 管线。 + """ + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + with app.app_context(): + from app.models import ShippingNotice, ShippingOrderTask + + user, agent, session, intake, _document = _seed_run_input(suffix='GATE-EQ') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + notice = ShippingNotice( + task_no='SN-GATE-EQ-1', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + lifecycle_status='active', + ) + db.session.add(notice) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-GATE-EQ-1', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=int(run.id), + status='processing', + stage='inventory_matching', + progress_version=1, + ) + db.session.add(order_task) + db.session.flush() + notice.order_task_id = int(order_task.id) + run.user_task_no = order_task.task_no + db.session.commit() + return { + 'run_id': int(run.id), + 'notice_id': int(notice.id), + 'order_task_id': int(order_task.id), + } + + +def _load_chain(ids: dict[str, int]): + from app.models import ShippingNotice, ShippingOrderProcessingRun, ShippingOrderTask + + run = db.session.get(ShippingOrderProcessingRun, ids['run_id']) + notice = db.session.get(ShippingNotice, ids['notice_id']) + order_task = db.session.get(ShippingOrderTask, ids['order_task_id']) + assert run is not None and notice is not None and order_task is not None + return run, notice, order_task + + +def _attach_execution(order_task, *, gate_code: str, status: str, + blocking_reason_code: str, next_action_code: str, + sequence_no: int = 16) -> int: + """为 OT 挂接一个正式 Execution + 单一 Gate(回退到正式 Notice 事实源)。""" + from app.models import ShippingProcessExecution, ShippingProcessGate + + execution = ShippingProcessExecution( + execution_no=f'EXE-GATE-EQ-{gate_code}', + task_id=int(order_task.id), + status='blocked', + current_gate_code=gate_code, + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code=gate_code, + sequence_no=sequence_no, + status=status, + evaluation_version=1, + blocking_reason_code=blocking_reason_code, + next_action_code=next_action_code, + )) + order_task.active_process_execution_id = int(execution.id) + db.session.flush() + return int(execution.id) + + +def _project_a(run, order_task): + """运行 A 管线,返回渲染 payload。 + + 真实对外 DTO 经 `_with_processing_ui_state` 封装(含顶层 current_gate / blocking_reason / + primary_action + 子 `ui_state`)。集成层(:4757/:4863)才封装,故此处手动封装, + 使顶层动作码与 `ui_state.lifecycle_stage` 均可被读取。 + """ + from app.services.shipping_notice.shipping_processing_projection import ( + _project_order_task_work_item, + _with_processing_ui_state, + ) + + payload = _project_order_task_work_item(run, order_task=order_task) + assert payload is not None, 'A 管线必须产出 work_item' + return _with_processing_ui_state(payload) + + +def _summary_c(execution_id: int): + """独立重调 C(project_user_gate_summary),避免与 A 携带的 process_gate 同源污染。""" + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + + execution = db.session.get(ShippingProcessExecution, execution_id) + assert execution is not None + return project_user_gate_summary(execution) + + +@pytest.mark.parametrize('scenario', [ + # gate_code, gate.status, blocking_reason_code, next_action_code + # [CANONICAL-AGREE] 这些场景 A 与 C 当前一致:flatten 后仍必须一致。 + ('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'), + ('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'), +]) +def test_a_primary_action_equals_c(app, gate_chain, scenario): + """A 渲染的主动作码必须等于 C 的 next_action_code(flatten 前置等价性,规范场景)。""" + gate_code, status, reason_code, next_action = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status=status, + blocking_reason_code=reason_code, next_action_code=next_action, + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip() + assert a_primary == c_next == c_primary, ( + f'A={a_primary!r} C.next={c_next!r} C.primary={c_primary!r} for {gate_code}' + ) + + a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip() + c_reason = str(summary.get('blocking_reason_code') or '').strip() + assert a_reason == c_reason, ( + f'A.reason={a_reason!r} C.reason={c_reason!r} for {gate_code}' + ) + + +def test_a_blocking_reason_does_not_over_collapse_retryable(app, gate_chain): + """flatten C 后:A 的 blocking_reason 必须复用 C 已裁决的具体码,不再坍缩为 technical_failure_present。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='inventory_preparation', status='blocked_retryable', + blocking_reason_code='inventory_preparation_failed', + next_action_code='retry_inventory_preparation', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip() + c_reason = str(summary.get('blocking_reason_code') or '').strip() + assert a_reason == c_reason == 'inventory_preparation_failed' + + +def test_a_primary_action_uses_canonical_excel_code(app, gate_chain): + """flatten C 后:A 的 primary_action.code 必须是写侧认可的规范码 regenerate_excel_artifact,而非别名。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='artifact_generation', status='blocked_retryable', + blocking_reason_code='artifact_generation_failed', + next_action_code='regenerate_excel_artifact', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip() + assert a_primary == c_next == c_primary == 'regenerate_excel_artifact' + + +def test_a_primary_action_uses_same_recovery_source_as_c(app, gate_chain): + """RPA 超时/耗尽:A 与 C 都必须回落为『优先复用已有快照重匹配(无则 RPA)』的合并动作, + 而非孤立只重读或直接新开 RPA。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='inventory_preparation', status='blocked_retryable', + blocking_reason_code='inventory_rpa_exhausted', next_action_code='retry_inventory_matching', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + assert a_primary == c_next == 'retry_inventory_matching' + + +@pytest.mark.parametrize('scenario', [ + # gate_code, gate.status, blocking_reason_code, next_action_code + ('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'), + ('inventory_preparation', 'blocked_retryable', 'inventory_preparation_failed', 'retry_inventory_preparation'), + ('artifact_generation', 'blocked_retryable', 'artifact_generation_failed', 'regenerate_excel_artifact'), + ('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'), +]) +def test_b_task_ui_state_actions_equals_c(app, gate_chain, scenario): + """B(formalTaskDetail.ui_state)的 actions 必须与 C 同源(A==B==C 的 B 半边)。 + + B 的 actions 由 _unified_actions(_process_gate_user_summary_for_task(task)) 产出, + 而后者就是 project_user_gate_summary;因此 B.primary.code 必须== C.next_action_code, + B.secondary.code 集合必须== C.allowed_actions 集合。 + """ + gate_code, status, reason_code, next_action = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status=status, + blocking_reason_code=reason_code, next_action_code=next_action, + ) + db.session.commit() + + from app.services.shipping_notice.ui_state import build_task_ui_state + + # B 只消费正式 OT;build_task_ui_state 直接接受 ShippingOrderTask 并按 task.id 查执行。 + state = build_task_ui_state(order_task) + actions = state.get('actions') or {} + b_primary = str((actions.get('primary') or {}).get('code') or '').strip() + b_all = { + str(item.get('code') or '').strip() + for item in [actions.get('primary'), *(actions.get('secondary') or [])] + if item and str(item.get('code') or '').strip() + } + summary = _summary_c(execution_id) + + c_next = str(summary.get('next_action_code') or '').strip() + c_allowed = { + str(code or '').strip() + for code in summary.get('allowed_actions') or [] + if str(code or '').strip() + } + assert b_primary == c_next, ( + f'B.primary={b_primary!r} C.next={c_next!r} for {gate_code}' + ) + # B 把 C.allowed_actions 拆成 primary+secondary;二者并集必须等于 allowed_actions。 + # 不能再要求 secondary==allowed:主动作被 C 列为 allowed 但在 B 里归到 primary。 + assert b_all == c_allowed, ( + f'B.all={sorted(b_all)} C.allowed={sorted(c_allowed)} for {gate_code}' + ) + + +def test_preparation_line_emits_decisional_allowed_actions(app, gate_chain): + """§1.5 明细按钮修复:preparation.lines[] 必须带 line_allowed_actions / + inventory_allowed_actions / inventory_file_no,否则前端 formalPreparationLineAllows 恒 false、 + 明细行按钮不渲染。用正式 OT + 一行 not_found 断言短缺行按钮被正确授权。""" + from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ) + from app.services.shipping_notice.ui_state import build_task_ui_state + + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + # 冻结快照行 → 行级匹配(not_found,短缺)。 + snapshot = ShippingOrderSnapshot( + task_id=int(order_task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + order_task.order_snapshot_id = int(snapshot.id) + line = ShippingOrderSnapshotLine( + snapshot_id=int(snapshot.id), position=0, line_no=1, + reservation_id='RSV-EQ', part_number='PN-EQ', qty='8', field_values_json={}, + ) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=1, line_index=0, + match_result='not_found', inventory_status='ready', required_qty='8', + available_qty='0', matched_qty='0', shortage_qty='8', + reservation_id='RSV-EQ', part_number='PN-EQ', + inventory_source_code='DBS_DUB', matched_file_no='INV-EQ', is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(order_task, include_stage_context=True)['stage_context']['preparation'] + assert preparation['lines'], '必须有至少一行' + line_row = preparation['lines'][0] + # 短缺行:close + release_inventory_shortage(line);retry_inventory_preparation(inventory)。 + assert set(line_row['line_allowed_actions']) == { + 'close_unfulfillable', 'release_inventory_shortage', + } + assert 'retry_inventory_preparation' in line_row['inventory_allowed_actions'] + # 下载库存按钮依赖 inventory_file_no。 + assert line_row['inventory_file_no'] == 'INV-EQ' + assert line_row['user_line_status'] == 'shortage' + + +def test_preparation_line_allowed_actions_are_zero_n_plus_one(app, gate_chain): + """§5.1 N+1 守门:行级 action 字段由内存事实投影发,GET 详情 SQL 数恒定且不随行数线性放大。 + + 行级 fact 字典只读已加载的 match_row 列 + detail_json(触库的是 `_build_stage_context` + 自身的批量预取),每行并不追加查询;6 行仍须落在固定数量级。若逐行 SQL/重序列化, + SQL 数会近似=6×行查询而被本上限拦下。 + """ + from sqlalchemy import event + + from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ) + from app.services.shipping_notice.ui_state import build_task_ui_state + from tests.test_shipping_order_review_service import _capture_sql_statements + + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + snapshot = ShippingOrderSnapshot( + task_id=int(order_task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + order_task.order_snapshot_id = int(snapshot.id) + line_count = 6 + for i in range(line_count): + line = ShippingOrderSnapshotLine( + snapshot_id=int(snapshot.id), position=i, line_no=i + 1, + reservation_id=f'RSV-{i}', part_number=f'PN-{i}', qty='8', field_values_json={}, + ) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=i + 1, line_index=i, + match_result='matched', inventory_status='ready', required_qty='8', + available_qty='8', matched_qty='8', shortage_qty='0', + reservation_id=f'RSV-{i}', part_number=f'PN-{i}', + inventory_source_code='DBS_DUB', matched_file_no=f'INV-{i}', is_current=True, + )) + db.session.commit() + + task_id = int(order_task.id) + db.session.remove() + with app.test_request_context(): + ot = db.session.get(ShippingOrderTask, task_id) + statements: list[str] = [] + listener = _capture_sql_statements(statements) + event.listen(db.engine, 'before_cursor_execute', listener) + try: + preparation = build_task_ui_state(ot, include_stage_context=True)['stage_context']['preparation'] + finally: + event.remove(db.engine, 'before_cursor_execute', listener) + assert len(preparation['lines']) == line_count + # 关键断言:6 行仍落在固定数量级;若逐行重查会显著超出(约 6×行查询)而触发。 + assert len(statements) <= 40, ( + f'SQL 数随行数放大: 6 行仍应固定数量级,实测 {len(statements)}' + ) + + +@pytest.mark.parametrize('scenario', [ + # gate_code, expected lifecycle stage(契约:正式 Gate 映射到五阶段业务码唯一表) + ('inventory_matching', 'fulfillment_prep'), + ('inventory_sufficiency', 'fulfillment_prep'), + ('artifact_generation', 'fulfillment_prep'), + ('freight_upload_rpa', 'freight_upload'), + ('manual_upload_handoff', 'freight_upload'), +]) +def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario): + """五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。 + + `LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。 + B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底, + 必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload** + —— 这是用户确认的契约(方案 A)。 + """ + gate_code, expected_stage = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status='blocked_manual', + blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation', + ) + # 让 notice 路径经 order_task_id 命中同一 execution(B 在生产中把 Notice + # 传给 build_task_ui_state;Execution.task_id 必须保持为 OT.id)。 + assert int(notice.order_task_id) == int(order_task.id) + from app.services.shipping_notice.ui_state import build_task_ui_state + b = build_task_ui_state(notice) + b_stage = str((b.get('stage') or {}).get('code') or '').strip() + b_lifecycle = str(b.get('lifecycle_stage') or '').strip() + + # B(Notice 路径)必须按 LIFECYCLE_STAGE_BY_GATE 落到五阶段码。 + assert b_stage == b_lifecycle == expected_stage, ( + f'B.stage={b_stage!r} B.lifecycle={b_lifecycle!r} expected={expected_stage!r} for {gate_code}' + ) + + +def test_a_secondary_actions_carry_mark_manual_uploaded(app, gate_chain): + """A(shippingProcessingProjection.ui_state.secondary_actions)必须透传原始 Gate 码 mark_manual_uploaded。 + + 契约 §2.5 差异①:A 的 secondary_actions 用别名 open_manual_upload,B/C 用 mark_manual_uploaded。 + frontend manualUploadRegistrationAuthorized 读 A 时须能匹配到 mark_manual_uploaded(否则按钮失效)。 + 本守卫在归一化前应 RED(记录 bug),归一化后应 GREEN。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + # freight_upload_rpa blocked_manual:C 的 gate_side_recovery_actions / 显式 append 授权手动上传。 + execution_id = _attach_execution( + order_task, + gate_code='freight_upload_rpa', status='blocked_manual', + blocking_reason_code='upload_rpa_failed', next_action_code='retry_freight_upload_rpa', + ) + db.session.commit() + + a = _project_a(run, order_task) + ui_state = a.get('ui_state') or {} + secondary_codes = { + str(item.get('code') or '').strip() + for item in ui_state.get('secondary_actions') or [] + if item + } + primary_code = str((ui_state.get('primary_action') or {}).get('code') or '').strip() + # C 是唯一授权来源:allowed_actions 必含 mark_manual_uploaded(手动上传入口)。 + summary = _summary_c(execution_id) + c_allowed = {str(c or '').strip() for c in summary.get('allowed_actions') or []} + assert 'mark_manual_uploaded' in c_allowed, f'C.allowed={sorted(c_allowed)}' + # [§2.5 归一守卫] A 的 secondary_actions 必须透传原始码 mark_manual_uploaded(而非 open_manual_upload 别名), + # 且与 C.allowed_actions 同集(允许与主动作并存)。 + assert 'mark_manual_uploaded' in secondary_codes or primary_code == 'mark_manual_uploaded', ( + f'A.secondary={sorted(secondary_codes)} A.primary={primary_code!r} C.allowed={sorted(c_allowed)}' + ) diff --git a/backend/tests/test_shipping_review_case_audit_timeline.py b/backend/tests/test_shipping_review_case_audit_timeline.py index 1cb254c1..cc96d7cc 100644 --- a/backend/tests/test_shipping_review_case_audit_timeline.py +++ b/backend/tests/test_shipping_review_case_audit_timeline.py @@ -40,6 +40,9 @@ def test_review_case_audit_timeline_owner_reads_snapshots_and_stranger_denied(ap user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-AUDIT-TL') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) unit = run.extraction_plan.units[0] + # 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required; + # 测试仅需审计时间线可见性,故把 Unit 置为就绪以初始化 Case/Draft。 + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] diff --git a/backend/tests/test_shipping_review_confirm_auto_progress.py b/backend/tests/test_shipping_review_confirm_auto_progress.py index baf98cf8..022a4f65 100644 --- a/backend/tests/test_shipping_review_confirm_auto_progress.py +++ b/backend/tests/test_shipping_review_confirm_auto_progress.py @@ -14,7 +14,7 @@ import pytest from app import db from app.jobs.types import JobType -from app.models import Job, ShippingNotice +from app.models import Job, ShippingOrderTask from app.services.shipping_notice.order_review_confirmation_service import ( _task_needs_post_confirm_auto_progress, schedule_auto_progress_after_review_confirm, @@ -81,13 +81,28 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced' -def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction(): - """created/parsed 且已挂 Extraction 的任务需要确认后补推。""" +def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction(monkeypatch): + """created/parsed 且已挂 Extraction 的任务需要确认后补推;已进入导出/上传事实则跳过。""" + from types import SimpleNamespace as NS + + from app.services.shipping_notice import upload_attempt_service + + # [断言] 是否已推进以真实履约事实(Artifact/Attempt)判定,不再读 OT 冗余字段。 + def fake_upload_attempt(task): + if getattr(task, 'upload_status', None) is not None: + return NS(status='pending') + return None + + monkeypatch.setattr(upload_attempt_service, 'latest_upload_attempt', fake_upload_attempt) + monkeypatch.setattr(upload_attempt_service, 'latest_export_artifact', lambda task: None) + stuck = MagicMock( current_order_extraction_id=12, + upload_status=None, ) parsed = MagicMock( current_order_extraction_id=12, + upload_status=None, ) progressed = MagicMock( upload_status='pending', @@ -95,6 +110,7 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac ) shell = MagicMock( current_order_extraction_id=None, + upload_status=None, ) assert _task_needs_post_confirm_auto_progress(stuck) is True assert _task_needs_post_confirm_auto_progress(parsed) is True @@ -106,8 +122,8 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch): """commit=False 时写入 Job 但不提交,供与确认事务同提交。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-1', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-1', user_id=1, current_order_extraction_id=99, ) @@ -143,8 +159,8 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch): def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch): """确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-PARSED', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-PARSED', user_id=1, current_order_extraction_id=99, ) @@ -178,8 +194,8 @@ def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypat def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch): """幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-2', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-2', user_id=1, current_order_extraction_id=88, ) @@ -219,15 +235,22 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch): - """任务已离开 created 时幂等回放不再入队。""" + """任务已进入行级库存匹配事实(可履约)时幂等回放不再入队。""" + from app.models import ShippingNoticeLineInventoryMatch + with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-3', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-3', user_id=1, - upload_status='pending', current_order_extraction_id=77, ) db.session.add(task) + db.session.flush() + # 已履约事实:可当前库匹配使 _task_needs_post_confirm_auto_progress 判 False。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=1, line_no=1, + match_result='matched', inventory_status='ready', is_current=True, + )) db.session.commit() monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') schedule = schedule_auto_progress_after_review_confirm( @@ -285,11 +308,10 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke from app.services.shipping_notice import batch_orchestrator with app.app_context(): - # ShippingBatch 已物理下线;仅用 ShippingNotice 表达确认建单后的悬挂态。 - task = ShippingNotice( - task_no='SN-CONFIRM-AP-4', + # ShippingBatch 已物理下线;仅用 ShippingOrderTask 表达确认建单后的悬挂态。 + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-4', user_id=1, - source_type='review_confirmation', current_order_extraction_id=66, ) db.session.add(task) diff --git a/backend/tests/test_shipping_review_formal_task_edit.py b/backend/tests/test_shipping_review_formal_task_edit.py index 2235c1a7..d61f7eb1 100644 --- a/backend/tests/test_shipping_review_formal_task_edit.py +++ b/backend/tests/test_shipping_review_formal_task_edit.py @@ -4,7 +4,8 @@ backend/tests/test_shipping_review_formal_task_edit.py 用途:验收正式任务字段写路径(Schema 策略 + order_data_version)与 change_effect 下游失效。 依赖:task_workflow、schema_edit_policy、order_schema_service、ShippingOrderTask。 逻辑:默认 reservation_id 不可写;Schema editable=True 可写并递增版本; - rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并同步 OT stage。 + rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage; + 正式字段编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。 """ from __future__ import annotations @@ -12,15 +13,14 @@ from __future__ import annotations from app import db from app.models import ( ShippingExportArtifact, + ShippingNotice, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderTask, - ShippingNotice, ) from app.services.shipping_notice.order_schema import service as order_schema_service -from app.services.shipping_notice.order_task_service import sync_order_task_processing_state from app.services.shipping_notice.task_workflow import update_notice_fields, update_notice_line @@ -36,12 +36,14 @@ def _review_payload(*, version: int = 1) -> dict[str, object]: def _attach_extraction( - task: ShippingNotice, + task: ShippingOrderTask, rows: list[dict], *, field_policies: dict[str, dict] | None = None, + header_values: dict[str, object] | None = None, ) -> dict[str, str]: """建立带 task_edit_policy 的动态 Extraction,供 formal edit 测试使用。""" + header_values = dict(header_values or {'po_number': 'PO-FORMAL-001'}) order_schema_service.initialize_schema({'display_name': 'Formal Edit Schema'}, actor_id=None) existing_fields = { item['field_code']: item @@ -97,7 +99,7 @@ def _attach_extraction( db.session.add(extraction) db.session.flush() header_field = fields['po_number'] - header_value = task.po_number + header_value = header_values.get('po_number') header_decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=None, @@ -118,7 +120,9 @@ def _attach_extraction( value_json=header_value, )) for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for code, field in fields.items(): @@ -150,17 +154,45 @@ def _attach_extraction( return {code: field['id'] for code, field in fields.items()} -def _task(**kwargs) -> ShippingNotice: - task = ShippingNotice( - task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'), - source_type='manual', - po_number=kwargs.pop('po_number', 'PO-FORMAL-001'), - match_status=kwargs.pop('match_status', 'matched'), - line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]), - export_file_path=kwargs.pop('export_file_path', None), - export_file_name=kwargs.pop('export_file_name', None), +def _freeze_formal_task_snapshot(task: ShippingOrderTask) -> None: + """补齐正式编辑前置:客户确认 + 冻结订单快照,使 order_field_id_values(order_field_purposes) 可读。 + + 正式编辑路径会对 task 跑 task_reservation_gate_issues → order_field_id_values, + 后者要求 task.order_snapshot_id 非空;缺快照会抛 order_schema_unavailable 并抢先置 RSV_REQUIRED/OT waiting_review。 + """ + from app.models import ShippingCustomer, ShippingOrderExtraction + from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + customer = ShippingCustomer(standard_name='正式编辑测试客户', short_code='FORMAL', status='active') + db.session.add(customer) + db.session.flush() + from tests.conftest import confirm_test_customer_resolution + extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id)) + if extraction is None: + raise ValueError('formal edit test task must have an accepted extraction') + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + freeze_order_snapshot( + task, actor_id=None, expected_order_data_version=int(task.order_data_version or 1), + freeze_mode='auto', + auto_freeze_policy={ + 'test_fixture': True, 'enabled': True, 'mode': 'qualified', + 'qualification_status': 'qualified', 'customer_scope_status': 'allowed', + 'blocking_reason_codes': [], + }, + ) + db.session.flush() + + +def _task(**kwargs) -> ShippingOrderTask: + """构造正式订单任务(OT)作为 formal edit 的目标容器。""" + task = ShippingOrderTask( + task_no=kwargs.pop('task_no', 'OT-FORMAL-EDIT-001'), + user_id=1, + source_type=kwargs.pop('source_type', 'direct_pdf'), + status=kwargs.pop('status', 'processing'), + stage=kwargs.pop('stage', 'inventory_matching'), order_data_version=kwargs.pop('order_data_version', 1), - order_lines_migration_status='pending', + step_payload_json=dict(kwargs.pop('step_payload_json', None) or {}), **kwargs, ) db.session.add(task) @@ -168,24 +200,15 @@ def _task(**kwargs) -> ShippingNotice: return task -def _link_order_task(task: ShippingNotice, *, stage: str = 'inventory_matching') -> ShippingOrderTask: - """挂接 OT 供 change_effect stage 同步断言。""" - order_task = ShippingOrderTask( - task_no=f'OT-{task.task_no}', - user_id=1, - candidate_id=None, - shipping_notice_id=int(task.id), - stage=stage, - status='processing', - progress_version=1, - ) - db.session.add(order_task) +def _link_order_task(task: ShippingOrderTask, *, stage: str = 'inventory_matching') -> ShippingOrderTask: + """挂接任务当前 stage 供 change_effect 用例表达 OT 进度;正式编辑任务本身即 OT。""" + task.stage = stage db.session.flush() - return order_task + return task -def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None) -> ShippingExportArtifact: - """为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09)。""" +def _seed_ready_export_artifact(task: ShippingOrderTask, *, path: str | None = None) -> ShippingExportArtifact: + """为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09),并挂接正式 Notice 供导出事实读取。""" from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, @@ -193,7 +216,17 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None ShippingOrderSchemaVersion, ) - file_path = str(path or task.export_file_path or '/tmp/formal.xlsx') + notice = ShippingNotice( + task_no=f'SN-{task.task_no}', + business_no=f'BN-{task.task_no}', + user_id=task.user_id, + order_task_id=int(task.id), + source_type='direct_pdf', + ) + db.session.add(notice) + db.session.flush() + + file_path = str(path or '/tmp/formal.xlsx') template = ShippingExcelTemplate( template_code=f'TPL-{task.task_no}', display_name='Formal Edit', @@ -234,14 +267,14 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None extraction_id = extraction.id artifact = ShippingExportArtifact( artifact_no=f'ART-{task.task_no}', - task_id=int(task.id), + task_id=int(notice.id), template_id=int(template.id), order_schema_version_id=int(version.id), order_extraction_id=int(extraction_id), inventory_parsing_profile_id=int(profile.id), input_checksum='b' * 64, file_path=file_path, - file_name=str(task.export_file_name or 'formal.xlsx'), + file_name='formal.xlsx', file_checksum='c' * 64, file_size=10, status='ready', @@ -277,7 +310,7 @@ def test_formal_edit_rejects_default_readonly_field(app): def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): """Schema editable=True 时允许写入并递增 order_data_version。""" with app.app_context(): - task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx') + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -288,7 +321,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): }, }, ) - _seed_ready_export_artifact(task) + artifact = _seed_ready_export_artifact(task) db.session.commit() # Excel ready(ready Artifact)时即使 Schema editable 也必须冻结。 @@ -302,8 +335,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): assert frozen['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN' # 清除导出后允许 Schema 放行字段写入。 - task.export_file_path = None - task.export_file_name = None + artifact.status = 'superseded' db.session.commit() response = update_notice_line({ @@ -313,16 +345,14 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) + refreshed = db.session.get(ShippingOrderTask, task.id) assert int(refreshed.order_data_version) == 2 - # change_effect=none 时不应清空已有匹配结果。 - assert refreshed.match_status == 'matched' def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(app): - """rerun_inventory_matching 清空匹配并同步 OT inventory_matching stage。""" + """rerun_inventory_matching 清空匹配/导出并置 invalidated_from_stage。""" with app.app_context(): - task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx') + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -333,10 +363,8 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a }, }, ) - order_task = _link_order_task(task, stage='excel_generating') - # 测试编辑路径:先去掉 Excel 冻结。 - task.export_file_path = None - task.export_file_name = None + _freeze_formal_task_snapshot(task) + _link_order_task(task, stage='excel_generating') db.session.commit() response = update_notice_line({ @@ -346,19 +374,16 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) - assert refreshed.match_status is None - assert refreshed.line_results_json is None - assert refreshed.export_file_path is None - ot = db.session.get(ShippingOrderTask, order_task.id) - assert ot.stage == 'inventory_matching' - assert int(ot.progress_version) == 2 + refreshed = db.session.get(ShippingOrderTask, task.id) + assert int(refreshed.order_data_version) == 2 + assert refreshed.step_payload_json['invalidated_from_stage'] == 'inventory_matching' + assert 'export_meta' not in refreshed.step_payload_json def test_change_effect_regenerate_excel_only_clears_export(app): - """regenerate_excel 仅清空导出并同步 OT excel_generating。""" + """regenerate_excel 仅清空导出并置 invalidated_from_stage。""" with app.app_context(): - task = _task() + task = _task(stage='inventory_matching') _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -369,10 +394,8 @@ def test_change_effect_regenerate_excel_only_clears_export(app): }, }, ) - order_task = _link_order_task(task, stage='inventory_matching') - # 版本不匹配的导出视为 stale,不触发 Excel 冻结,便于测 regenerate_excel。 - task.export_file_path = '/tmp/stale.xlsx' - task.export_file_name = 'stale.xlsx' + _freeze_formal_task_snapshot(task) + _link_order_task(task, stage='inventory_matching') task.step_payload_json = { **dict(task.step_payload_json or {}), 'export_meta': {'order_data_version': 999}, @@ -385,19 +408,16 @@ def test_change_effect_regenerate_excel_only_clears_export(app): **_review_payload(), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) - assert refreshed.match_status == 'matched' - assert refreshed.line_results_json == [{'part_number': 'A001'}] - assert refreshed.export_file_path is None - ot = db.session.get(ShippingOrderTask, order_task.id) - assert ot.stage == 'excel_generating' - assert int(ot.progress_version) == 2 + refreshed = db.session.get(ShippingOrderTask, task.id) + assert int(refreshed.order_data_version) == 2 + assert refreshed.step_payload_json['invalidated_from_stage'] == 'excel_generating' + assert 'export_meta' not in refreshed.step_payload_json def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): """有 order_snapshot_id 但 Excel 未 ready 时,Schema editable 字段仍可写。""" with app.app_context(): - task = _task(order_snapshot_id=12345) + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -408,6 +428,7 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): }, }, ) + _freeze_formal_task_snapshot(task) db.session.commit() response = update_notice_line({ @@ -417,6 +438,6 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) + refreshed = db.session.get(ShippingOrderTask, task.id) assert int(refreshed.order_data_version) == 2 - assert int(refreshed.order_snapshot_id) == 12345 + assert int(refreshed.order_snapshot_id) == int(task.order_snapshot_id) diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index c6fa734e..4be7ea24 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -160,6 +160,36 @@ def test_shortage_release_export_uses_audited_header_override_when_no_snapshot_c ) == [{'6': 'ODM-001'}] +def test_narrow_inventory_lines_keeps_only_reservation_and_part_hits(): + """导出匹配前必须按本单 reservation+part 裁剪,不得把全量快照送进逐行匹配。""" + from app.services.shipping_notice.export import ( + _narrow_inventory_lines_by_wanted_match_keys, + _wanted_order_match_keys, + ) + + order_lines = [ + {'ord_rsv': '3000112934', 'ord_part': 'D4-A08AR12000001'}, + ] + wanted = _wanted_order_match_keys( + order_lines, + order_field_ids=['ord_rsv', 'ord_part'], + ) + assert wanted == {('3000112934', 'd4-a08ar12000001')} + + inventory_lines = [ + {'inv_rsv': '3000112934', 'inv_part': 'D4-A08AR12000001', 'extra': 'HIT'}, + {'inv_rsv': '999', 'inv_part': 'OTHER', 'extra': 'MISS'}, + *[{'inv_rsv': f'R{i}', 'inv_part': f'P{i}', 'extra': 'NOISE'} for i in range(200)], + ] + narrowed = _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines, + inventory_field_keys=['inv_rsv', 'inv_part'], + wanted_keys=wanted, + ) + assert len(narrowed) == 1 + assert narrowed[0]['extra'] == 'HIT' + + def test_shortage_release_export_allows_reservation_miss_when_template_uses_no_inventory_field(): """已审计短缺放行时,库存预约单未命中不能阻断只消费订单字段的 Excel。""" from app.services.shipping_notice.export import _match_inventory_lines @@ -295,13 +325,13 @@ def test_shortage_release_inventory_source_falls_back_from_line_fact_to_task_the """历史行事实漏源时,仍须从当前 OT 或快照恢复受控库存源。""" assert _resolve_shortage_release_inventory_source( fact_source_code=None, - task_source_code='CRANE', - snapshot_source_code='DBS', + snapshot_source_code=None, + candidate_source_codes={'CRANE'}, ) == 'CRANE' assert _resolve_shortage_release_inventory_source( fact_source_code=None, - task_source_code=None, snapshot_source_code='DBS', + candidate_source_codes={'CRANE'}, ) == 'DBS' @@ -352,7 +382,7 @@ def test_assert_line_can_fulfill_raises_on_shortage(): """断言路径对库存不足抛 ConflictError。""" with pytest.raises(ConflictError) as exc: _assert_line_can_fulfill_complete( - line_key='L1', + draft_line_id='L1', draft_line={'qty': '5', 'reservation_id': 'R1'}, proj={'available_qty': '1'}, ) @@ -369,14 +399,14 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch): draft = SimpleNamespace( draft_version=1, lines_json=[{ - 'line_key': 'L1', + 'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1', 'part_number': 'PN1', }], validation_result_json={ 'line_projections': [{ - 'line_key': 'L1', + 'draft_line_id': 'L1', 'available_qty': '2', 'effective_reservation_id': 'R1', }], @@ -400,7 +430,7 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch): svc.decide_review_line_fulfillment( user_id=1, case_no='CASE-1', - line_key='L1', + draft_line_id='L1', decision_code=DECISION_FULFILL, expected_draft_version=1, ) @@ -415,7 +445,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch): draft = SimpleNamespace( draft_version=1, - lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}], + lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}], validation_result_json={'line_projections': []}, ) case = SimpleNamespace( @@ -438,7 +468,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch): svc.decide_review_line_fulfillment( user_id=1, case_no='CASE-1', - line_key='L1', + draft_line_id='L1', decision_code=DECISION_REOPEN, reason='retry', actor_is_admin=True, @@ -454,7 +484,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch): draft = SimpleNamespace( draft_version=1, - lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}], + lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}], validation_result_json={'line_projections': []}, ) case = SimpleNamespace( @@ -477,7 +507,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch): svc.decide_review_line_fulfillment( user_id=1, case_no='CASE-1', - line_key='L1', + draft_line_id='L1', decision_code=DECISION_REOPEN, reason='admin reopen', actor_is_admin=False, @@ -493,8 +523,8 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch): draft = SimpleNamespace( draft_version=1, - lines_json=[{'line_key': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}], - validation_result_json={'line_projections': [{'line_key': 'L1', 'available_qty': '1'}]}, + lines_json=[{'draft_line_id': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}], + validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '1'}]}, ) case = SimpleNamespace( id=1, @@ -505,7 +535,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch): ) row = SimpleNamespace( id=None, - line_key='L1', + draft_line_id='L1', line_index=0, decision_version=1, decision_code=DECISION_FULFILL, @@ -556,7 +586,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch): result = svc.decide_review_line_fulfillment( user_id=1, case_no='CASE-1', - line_key='L1', + draft_line_id='L1', decision_code=DECISION_FULFILL, expected_draft_version=1, ) diff --git a/backend/tests/test_shipping_review_wave_line_concurrency.py b/backend/tests/test_shipping_review_wave_line_concurrency.py index 4d0dc002..4105c01c 100644 --- a/backend/tests/test_shipping_review_wave_line_concurrency.py +++ b/backend/tests/test_shipping_review_wave_line_concurrency.py @@ -3,7 +3,7 @@ tests/test_shipping_review_wave_line_concurrency.py 用途:同行并发入波次的唯一约束与错误码证据。 依赖:pytest、threading、ShippingOrderReviewWaveLine、app fixture。 -逻辑:两线程同时插入同一 (case, line_key);只允许一条成功;失败映射稳定错误码。 +逻辑:两线程同时插入同一 (case, snapshot_line_id);只允许一条成功;失败映射稳定错误码。 若环境变量 HXOPS_PG_CONCURRENCY_URL 指向 PostgreSQL,则在真实 PG 上再跑一轮。 """ @@ -20,7 +20,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError -from app.models import ShippingOrderReviewWaveLine, ShippingNotice +from app.models import ShippingOrderReviewWaveLine, ShippingOrderTask from app.services.shipping_notice.order_review_confirmation_service import _persist_wave_lines_for_task @@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ') run, _ = create_order_extraction_run( @@ -51,32 +50,30 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): case = ensure_run_review_cases(run=run)[0] db.session.commit() - task1 = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + task1 = ShippingOrderTask( + task_no='OT-WAVE-UQ-1', + user_id=int(user.id), source_type='eml', ) - task2 = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + task2 = ShippingOrderTask( + task_no='OT-WAVE-UQ-2', + user_id=int(user.id), source_type='eml', ) db.session.add_all([task1, task2]) db.session.flush() _persist_wave_lines_for_task( - case=case, task=task1, line_keys=['L-CONC'], wave_no=1, revision_id=None, + case=case, task=task1, snapshot_line_ids=[1], wave_no=1, revision_id=None, ) db.session.commit() with pytest.raises(ConflictError) as exc: _persist_wave_lines_for_task( - case=case, task=task2, line_keys=['L-CONC'], wave_no=2, revision_id=None, + case=case, task=task2, snapshot_line_ids=[1], wave_no=2, revision_id=None, ) assert exc.value.code == 'SHIPPING.REVIEW_LINE_ALREADY_IN_TASK' db.session.rollback() assert ShippingOrderReviewWaveLine.query.filter_by( - review_case_id=int(case.id), line_key='L-CONC', + review_case_id=int(case.id), snapshot_line_id=1, ).count() == 1 @@ -92,7 +89,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE') run, _ = create_order_extraction_run( @@ -109,11 +105,10 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): case_id = int(case.id) tasks = [] - for _ in range(2): - task = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + for index in range(2): + task = ShippingOrderTask( + task_no=f'OT-WAVE-RACE-{index + 1}', + user_id=int(user.id), source_type='eml', ) db.session.add(task) tasks.append(task) @@ -128,7 +123,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): barrier.wait(timeout=10) row = ShippingOrderReviewWaveLine( review_case_id=case_id, - line_key='L-RACE', + snapshot_line_id=1, task_id=task_id, wave_no=wave_no, created_at=datetime.utcnow(), @@ -153,7 +148,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): assert results.count('conflict') == 1 with app.app_context(): assert ShippingOrderReviewWaveLine.query.filter_by( - review_case_id=case_id, line_key='L-RACE', + review_case_id=case_id, snapshot_line_id=1, ).count() == 1 @@ -163,7 +158,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): ) def test_wave_line_concurrent_inserts_on_postgres(): """ - 真实 PostgreSQL 上验证 (review_case_id, line_key) 唯一约束并发行为。 + 真实 PostgreSQL 上验证 (review_case_id, snapshot_line_id) 唯一约束并发行为。 需预先存在空库并可建临时表;通过环境变量注入连接串。 """ @@ -182,10 +177,10 @@ def test_wave_line_concurrent_inserts_on_postgres(): 'tmp_wave_lines', metadata, sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True), sa.Column('review_case_id', sa.Integer(), sa.ForeignKey('tmp_review_cases.id'), nullable=False), - sa.Column('line_key', sa.String(64), nullable=False), + sa.Column('snapshot_line_id', sa.Integer(), nullable=False), sa.Column('task_id', sa.Integer(), sa.ForeignKey('tmp_shipping_tasks.id'), nullable=False), sa.Column('wave_no', sa.Integer(), nullable=False), - sa.UniqueConstraint('review_case_id', 'line_key', name='uq_tmp_wave_case_line'), + sa.UniqueConstraint('review_case_id', 'snapshot_line_id', name='uq_tmp_wave_case_line'), ) metadata.drop_all(engine) metadata.create_all(engine) @@ -202,7 +197,7 @@ def test_wave_line_concurrent_inserts_on_postgres(): with engine.begin() as conn: try: conn.execute(wave.insert().values( - review_case_id=1, line_key='L1', task_id=task_id, wave_no=wave_no, + review_case_id=1, snapshot_line_id=101, task_id=task_id, wave_no=wave_no, )) return 'ok' except IntegrityError: diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index 90607427..fa500f51 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -267,8 +267,18 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): assert stage['source'] == 'domain_facts' -def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(): - """历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。""" +def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(monkeypatch): + """无成功 Attempt(仅上传尝试已发生但未核对)时仍停留货代上传工作面。""" + from types import SimpleNamespace + + from app.services.shipping_notice import upload_attempt_service as upload_mod + + # 迁移后上传态以「最近上传尝试」为准,不再读取 Notice 上的历史聚合字段 upload_status。 + monkeypatch.setattr( + upload_mod, + 'latest_upload_attempt', + lambda _task: SimpleNamespace(status='uploaded'), + ) task = SimpleNamespace( id=1, order_task_id=9, diff --git a/backend/tests/test_shipping_review_workbench_state_isolation.py b/backend/tests/test_shipping_review_workbench_state_isolation.py index 9e18b487..2cc47cd7 100644 --- a/backend/tests/test_shipping_review_workbench_state_isolation.py +++ b/backend/tests/test_shipping_review_workbench_state_isolation.py @@ -13,11 +13,68 @@ from types import SimpleNamespace from unittest.mock import patch from app.services.shipping_notice.order_review_projection import ( + _inventory_rpa_is_running, _project_case_automation_status, ) +from app.services.shipping_notice.ui_state import _unified_actions +from app.services.shipping_notice.shipping_processing_projection import _processing_ui_state_from_item from app.services.shipping_notice.process_gate_projection import project_user_gate_summary +def test_unified_actions_keeps_blocked_gate_next_action_when_presentation_missing(): + """Gate 展示元数据缺失时仍保留已授权的库存 RPA 重试按钮。""" + result = _unified_actions(process_gate={ + 'next_action_code': 'retry_inventory_preparation', + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'gate_code': 'inventory_preparation', + 'next_action_code': 'retry_inventory_preparation', + }, + 'action_presentation': [], + }) + assert result['primary']['code'] == 'retry_inventory_preparation' + + +def test_processing_ui_state_backfills_blocked_gate_action(): + """工作项顶层动作缺失时,正式 Gate 恢复动作仍进入 ui_state 主动作。""" + result = _processing_ui_state_from_item({ + 'user_status': 'retryable', + 'user_stage': 'inventory_fetch', + 'process_gate': { + 'next_action_code': 'retry_inventory_preparation', + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'gate_code': 'inventory_preparation', + 'next_action_code': 'retry_inventory_preparation', + }, + }, + 'primary_action': None, + 'available_actions': [], + 'source_summary': {}, + }) + assert result['primary_action']['code'] == 'retry_inventory_preparation' + + +def test_inventory_running_is_not_inferred_from_stage_automation_job(): + """阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。""" + task = SimpleNamespace(task_no='OT-TEST-1') + with patch( + 'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query', + ) as query: + query.filter.return_value.first.return_value = None + assert _inventory_rpa_is_running(task) is False + + +def test_inventory_running_requires_queued_or_running_attempt(): + """只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。""" + task = SimpleNamespace(task_no='OT-TEST-2') + with patch( + 'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query', + ) as query: + query.filter.return_value.first.return_value = SimpleNamespace(status='queued') + assert _inventory_rpa_is_running(task) is True + + def test_automation_waiting_to_start_when_eligible_but_not_queued(): """资格达标且未建单时只能是 waiting_to_start,不得伪装 running。""" case = SimpleNamespace( @@ -151,10 +208,12 @@ def test_unexpected_stp_error_has_stable_user_message(): category_hint='temporary_storage_error', ) - assert retryable is False + assert retryable is True assert result['message'] == '自动建单失败,已停止,等待用户选择下一步动作' assert 'psycopg2' not in result['message'] assert 'invalid input syntax' not in result['message'] + assert result['next_action'] == 'retry_stp_auto_create' + assert result['decision_trace']['matched_rule'] == 'temporary_storage_error' def test_automation_failed_stops_when_post_confirm_needs_user_action(): @@ -456,7 +515,8 @@ def test_project_user_gate_summary_exposes_retry_for_confirmed_inventory_pending assert summary['current_blocking_gate']['status'] == 'blocked_retryable' assert summary['next_action_code'] == 'retry_inventory_matching' - assert summary['allowed_actions'] == ['retry_inventory_matching'] + # 迁移后行级库存源在 Excel 未生成时持续可编辑,选源/覆写动作与阻断态解耦。 + assert summary['allowed_actions'] == ['retry_inventory_matching', 'override_line_inventory_source'] def test_project_user_gate_summary_keeps_pending_match_system_owned_without_inventory(monkeypatch): diff --git a/backend/tests/test_shipping_rolling_fulfillment.py b/backend/tests/test_shipping_rolling_fulfillment.py index 2d1251db..3ba5f53f 100644 --- a/backend/tests/test_shipping_rolling_fulfillment.py +++ b/backend/tests/test_shipping_rolling_fulfillment.py @@ -18,8 +18,9 @@ from app.models import ( ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, + ShippingOrderTask, ShippingReservation, - ShippingNotice, + ShippingTaskEvent, ) from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, @@ -62,7 +63,7 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app): snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) released_line = snapshot.lines[0] blocked_line = ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681', qty=Decimal('3'), field_values_json={}, ) snapshot.lines.append(blocked_line) @@ -85,7 +86,7 @@ def test_partial_inventory_allows_excel_for_the_available_lines(app): snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) available_line = snapshot.lines[0] shortage_line = ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681', qty=Decimal('3'), field_values_json={}, ) snapshot.lines.append(shortage_line) @@ -105,7 +106,7 @@ def test_selected_notice_only_returns_its_frozen_lines(app): snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) first_line = snapshot.lines[0] second_line = ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681', qty=Decimal('3'), field_values_json={}, ) snapshot.lines.append(second_line) @@ -163,11 +164,11 @@ def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app): snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) first_line = snapshot.lines[0] second_line = ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=1, part_number='000124', reservation_id='0012345679', + snapshot_id=snapshot.id, position=1, line_no=2, part_number='000124', reservation_id='0012345679', qty=Decimal('4'), field_values_json={}, ) third_line = ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=2, part_number='000125', reservation_id='0012345680', + snapshot_id=snapshot.id, position=2, line_no=3, part_number='000125', reservation_id='0012345680', qty=Decimal('3'), field_values_json={}, ) snapshot.lines.extend([second_line, third_line]) @@ -201,7 +202,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa ensure_task_reservations(first_task) db.session.commit() - second_task = ShippingNotice(task_no='SN-SNAPSHOT-102', source_type='test') + second_task = ShippingOrderTask(task_no='SN-SNAPSHOT-102', source_type=None, user_id=first_user.id) db.session.add(second_task) db.session.flush() extraction = ShippingOrderExtraction( @@ -217,7 +218,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa db.session.add(second_snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=second_snapshot.id, position=0, reservation_id='0012345678', + snapshot_id=second_snapshot.id, position=0, line_no=1, reservation_id='0012345678', part_number='000123', qty=Decimal('12.5'), field_values_json={}, )) second_task.order_snapshot_id = second_snapshot.id @@ -232,50 +233,42 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(app): - """已确认的直接后继可接替同 PO 的未履约 Reservation,且保留父子审计。""" + """已确认的同一 OT 修订复用该 OT(仅 bump order_data_version),接替同 PO 的未履约 Reservation。""" with app.app_context(): first_task, first_user = _build_accepted_order(suffix='201') first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7) ensure_task_reservations(first_task) db.session.flush() original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one() + ot_id = int(first_task.id) + ot_count = ShippingOrderTask.query.count() - revision_task = ShippingNotice( - task_no='SN-SNAPSHOT-202', source_type='test', supersedes_task_id=first_task.id, - ) - db.session.add(revision_task) - db.session.flush() - extraction = ShippingOrderExtraction( - task_id=revision_task.id, schema_version_id=first_snapshot.schema_version_id, - input_snapshot_hash='c' * 64, status='accepted', - ) - db.session.add(extraction) - db.session.flush() - revision_snapshot = ShippingOrderSnapshot( - task_id=revision_task.id, extraction_id=extraction.id, - schema_version_id=first_snapshot.schema_version_id, order_data_version=2, - rule_versions_json={}, header_values_json={}, customer_po_number=first_snapshot.customer_po_number, - ) - db.session.add(revision_snapshot) - db.session.flush() - revision_line = ShippingOrderSnapshotLine( - snapshot_id=revision_snapshot.id, position=0, - reservation_id=first_snapshot.lines[0].reservation_id, - part_number='000123-REV', qty=Decimal('13.5'), field_values_json={}, - ) - db.session.add(revision_line) - revision_task.order_snapshot_id = revision_snapshot.id + # 修订沿用同一 OT:不新建任务/快照,仅改写冻结行数据并沿用该 OT, + # 由 _transfer_confirmed_revision 完成 version bump 与 Reservation 接替。 + line = first_snapshot.lines[0] + line.part_number = '000123-REV' + line.qty = Decimal('13.5') db.session.flush() - registered = ensure_task_reservations(revision_task) + registered = ensure_task_reservations(first_task) + # 同一 OT 上完成接替:不新建任务行,仅版本 bump,Reservation 仍指向该 OT。 assert registered == [original] - assert original.task_id == revision_task.id - assert original.snapshot_line_id == revision_line.id + assert original.task_id == ot_id + assert original.snapshot_line_id == line.id assert original.part_number == '000123-REV' assert original.required_qty == Decimal('13.5') - assert {event.event_type for event in revision_task.events} == {'reservation_revision_confirmed'} - assert {event.event_type for event in first_task.events} == {'reservation_revision_superseded'} + assert first_task.order_data_version == 8 + assert first_task.progress_version == 2 + # 不产生重复 OT 行。 + assert ShippingOrderTask.query.count() == ot_count + # 审计事件落在该 OT 上。 + assert {event.event_type for event in first_task.events} == {'reservation_revision_confirmed'} + assert {event.task_id for event in first_task.events} == {ot_id} + assert all( + event.task_id == ot_id + for event in ShippingTaskEvent.query.filter_by(event_type='reservation_revision_confirmed').all() + ) def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it(app): @@ -287,7 +280,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it ensure_task_reservations(task) db.session.flush() - repeat_task = ShippingNotice(task_no='SN-SNAPSHOT-302', source_type='test') + repeat_task = ShippingOrderTask(task_no='SN-SNAPSHOT-302', source_type=None, user_id=user.id) db.session.add(repeat_task) db.session.flush() extraction = ShippingOrderExtraction( @@ -303,7 +296,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it db.session.add(repeat_snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=repeat_snapshot.id, position=0, reservation_id=snapshot.lines[0].reservation_id, + snapshot_id=repeat_snapshot.id, position=0, line_no=1, reservation_id=snapshot.lines[0].reservation_id, part_number=snapshot.lines[0].part_number, qty=snapshot.lines[0].qty, field_values_json={}, )) repeat_task.order_snapshot_id = repeat_snapshot.id diff --git a/backend/tests/test_shipping_schema_edit_policy.py b/backend/tests/test_shipping_schema_edit_policy.py index 7297e1b2..7b14d073 100644 --- a/backend/tests/test_shipping_schema_edit_policy.py +++ b/backend/tests/test_shipping_schema_edit_policy.py @@ -63,7 +63,7 @@ def test_sanitize_audit_field_value_truncates_long_text() -> None: def test_excel_ready_requires_ready_artifact(app) -> None: - """仅有 export_file_path、无 ready Artifact 时不得冻结(BE-09)。""" + """无 ready Artifact 时不得冻结;只有 Artifact 进入 ready 才冻结。""" from app import db from app.models import ( ShippingExcelTemplate, @@ -76,14 +76,7 @@ def test_excel_ready_requires_ready_artifact(app) -> None: ) with app.app_context(): - task = ShippingNotice( - task_no='SN-EXCEL-READY-BE09', - source_type='manual', - export_file_path='/tmp/be09.xlsx', - export_file_name='be09.xlsx', - order_data_version=1, - order_lines_migration_status='pending', - ) + task = ShippingNotice(task_no='SN-EXCEL-READY-BE09', source_type='manual') db.session.add(task) db.session.flush() assert is_excel_ready_for_task(task) is False diff --git a/backend/tests/test_shipping_stage_capability.py b/backend/tests/test_shipping_stage_capability.py new file mode 100644 index 00000000..44f34644 --- /dev/null +++ b/backend/tests/test_shipping_stage_capability.py @@ -0,0 +1,655 @@ +# backend/tests/test_shipping_stage_capability.py +import pytest + +from app.services.shipping_notice.process_gate_contract import ( + STAGE_CAPABILITY_DEFINITIONS, + stage_capability, + is_stage_capability, + capability_stage, +) + + +def test_stage_capability_definitions_exist(): + assert 'retry_inventory_preparation' in STAGE_CAPABILITY_DEFINITIONS + assert 'override_line_inventory_source' in STAGE_CAPABILITY_DEFINITIONS + assert 'reload_inventory_result' in STAGE_CAPABILITY_DEFINITIONS + + +def test_stage_capability_returns_definition(): + cap = stage_capability('retry_inventory_preparation') + assert cap is not None + assert cap['stage'] == 'fulfillment_prep' + assert cap['scope'] == 'task' + assert cap['reset_to'] == 'inventory_preparation' + assert 'inventory_matching' in cap['invalidate'] + + +def test_stage_capability_unknown_returns_none(): + assert stage_capability('retry_freight_upload_rpa') is None + + +def test_is_stage_capability(): + assert is_stage_capability('retry_inventory_preparation') is True + assert is_stage_capability('retry_freight_upload_rpa') is False + assert is_stage_capability(None) is False + + +def test_capability_stage(): + assert capability_stage('retry_inventory_preparation') == 'fulfillment_prep' + assert capability_stage('unknown') is None + + +# 追加到 test_shipping_stage_capability.py +def test_build_task_ui_state_exposes_capabilities(monkeypatch): + # 构造一个确认任务(轻量,不依赖 DB);此处用真正的 ui_state 冒烟,最小断言字段存在 + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + # 直接测纯辅助,避免重 DB 依赖 + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []}, + source_locked=False, + ) + codes = [c['code'] for c in caps] + assert 'retry_inventory_preparation' in codes + assert 'reload_inventory_result' in codes + assert 'override_line_inventory_source' in codes + + +def test_capabilities_disabled_when_excel_locked(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': True, 'lines': []}, + source_locked=True, + ) + assert all(c['enabled'] is False for c in caps) + assert all(c['disabled_reason'] for c in caps) + + +# 预条件语义(Task 2 变更):能力可用性由数据谓词决定,而非仅代码在场。 +# 断言关键分支:重抓(有候选源/Excel未锁定);重抓(无候选源但有失败源);重读(已有抓取结果)。 +def test_retry_inventory_preparation_enabled_with_candidates(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []}, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:source_options 非空(候选源) + Excel 未锁定 → 重抓可用。 + assert by_code['retry_inventory_preparation']['enabled'] is True + assert by_code['retry_inventory_preparation']['disabled_reason'] is None + + +def test_retry_inventory_preparation_enabled_with_failed_source(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'failed_source_codes': ['CRANE'], + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:无候选源但存在失败源(有抓取失败的源可重试) → 重抓仍可用 + # (docstring:重抓→有候选源或失败源)。这是一期实现遗漏的分支,此处锁定。 + assert by_code['retry_inventory_preparation']['enabled'] is True + assert by_code['retry_inventory_preparation']['disabled_reason'] is None + + +def test_reload_inventory_result_enabled_with_resolved_source(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'resolved_source_codes': ['CRANE'], + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:已有抓取结果(resolved_source_codes 非空) → 重读可用。 + assert by_code['reload_inventory_result']['enabled'] is True + assert by_code['reload_inventory_result']['disabled_reason'] is None + + +# Task 3 —— 编排器 execute_stage_capability(作废下游 + 重置 + 幂等重跑) +# 断言意图:invalidate_downstream_gates 的返回被透传为 invalidated_gates;重走后 +# run_task_auto_progress 会执行(reran=True);capability['reset_to'] 使 current_gate_code 复位。 +from app.services.shipping_notice.process_gate_service import execute_stage_capability + + +def test_execute_stage_capability_invalidates_downstream(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + calls = {} + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: calls.update(kw) or ['inventory_field_mapping', 'inventory_matching'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: calls.update(run=True, run_kwargs=k), + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k1', + ) + assert 'inventory_field_mapping' in result['invalidated_gates'] + assert calls.get('run') is True + # 断言失效链只作废准备 Gate 的下游,不能把准备 Gate 自身置 invalidated。 + assert calls['change_type'] == 'inventory_source_changed' + assert calls['exclude_gate_codes'] == {'inventory_preparation'} + # 断言幂等键被真正透传给 run_task_auto_progress(findings:曾经接收但不转发)。 + assert calls['run_kwargs']['idempotency_key'] == 'k1' + # 用户点击重抓库存必须保留定向恢复语义,不能退化成失败后的自动重试。 + assert calls['run_kwargs']['resume_gate_code'] == 'inventory_preparation' + assert calls['run_kwargs']['inventory_mode'] == 'retry_rpa' + + +def test_execute_stage_capability_forwards_line_scope_for_line_rpa_retry(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + + class FakeExecution: + current_gate_code = 'inventory_matching' + id = 1 + + calls = {} + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: [], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: calls.update(run_kwargs=k), + ) + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=stage_capability('retry_inventory_preparation'), + actor_type='user', actor_id=1, idempotency_key='line-rpa', line_scope_key=42, + ) + assert result['reran'] is True + assert calls['run_kwargs']['line_scope_key'] == '42' + + +def test_execute_stage_capability_resets_to_preparation(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + execution = FakeExecution() + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: ['inventory_matching'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: None, + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=execution, gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k2', + ) + assert result['reset_to'] == 'inventory_preparation' + # 断言真实副作用:执行对象被复位回能力起始 gate,而非仅回显返回的 reset_to。 + assert execution.current_gate_code == 'inventory_preparation' + + +def test_execute_stage_capability_reran_false_on_failed_progress(monkeypatch): + # 断言:run_task_auto_progress 对失败返回 dict(status=failed)而非抛异常时,reran 必须为 False, + # 避免把「实际失败」误报为已重跑(findings:reran 守卫仅凭未抛异常便判成功)。 + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: [], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: {'status': 'failed', 'message': '未找到任务编号'}, + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k3', + ) + assert result['reran'] is False + assert result.get('reran_reason') == '未找到任务编号' + + +# ============================================================ +# Task 4 —— request_gate_action 阶段能力豁免 +# 纯谓词 is_stage_capability_exempt 是本任务的测试主门(无 IO、可单测); +# request_gate_action 路由仅做一次打桩冒烟,验证「阶段能力请求非当前 gate 不抛 +# SHIPPING.PROCESS_GATE_NOT_CURRENT」。打桩较重,若未来漂移可仅保留纯谓词测试。 +# ============================================================ +from app.services.shipping_notice.process_gate_recovery_service import request_gate_action + + +def test_stage_capability_exempt_in_window(): + # 断言意图:能力阶段匹配 + 请求 gate 落在 invalidate 范围 → 豁免非当前 gate 校验。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_field_mapping', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is True + + +def test_stage_capability_exempt_reset_to_branch(): + # 断言意图:请求 gate 等于能力 reset_to(inventory_preparation)→ 豁免(reset_to 分支)。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_preparation', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is True + + +def test_stage_capability_exempt_wrong_lifecycle_stage(): + # 断言意图:能力阶段不符(order_review != fulfillment_prep)→ 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='order_field_extraction', + requested_gate='inventory_field_mapping', + action_code='retry_inventory_preparation', + lifecycle_stage='order_review', + ) is False + + +def test_stage_capability_exempt_non_capability(): + # 断言意图:动作不是阶段能力(freight upload)→ 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_preparation', + action_code='retry_freight_upload_rpa', + lifecycle_stage='fulfillment_prep', + ) is False + + +def test_stage_capability_exempt_out_of_range(): + # 断言意图:能力阶段匹配但请求 gate 超出作废/重置范围 → 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='document_materialization', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is False + + +def test_request_gate_action_stage_capability_exemption(monkeypatch): + # 断言意图:请求「非当前 gate」的阶段能力动作被豁免 not-current 校验,直接走 + # execute_stage_capability 返回 outcome=submitted,且不抛 PROCESS_GATE_NOT_CURRENT。 + # (打桩较重:gate/attempt 查询与 execute/serialize 均以假对象替换。) + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + blocking_reason_code = None + next_action_code = None + evaluation_version = 1 + + class FakeExec: + id = 1 + execution_no = 'SPE-X' + status = 'active' + current_gate_code = 'inventory_field_mapping' + task_id = 1 + + class FakeQuery: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] if self._rows else None + + def get(self, pk, default=None): + return self._rows[0] if self._rows else default + + monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()])) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([])) + monkeypatch.setattr( + svc, 'execute_stage_capability', + lambda **kw: {'invalidated_gates': ['inventory_field_mapping'], 'reset_to': 'inventory_preparation', 'reran': True}, + ) + monkeypatch.setattr( + svc, 'serialize_process_gate', + lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status}, + ) + + result = request_gate_action( + execution_no='SPE-X', + gate_code='inventory_preparation', + action_code='retry_inventory_preparation', + expected_gate_version=1, + idempotency_key='k', + actor_type='user', + actor_id=1, + ) + assert result['outcome'] == 'submitted' + assert result['gate_summary']['gate_code'] == 'inventory_preparation' + assert result['stage_capability']['reran'] is True + + +def test_request_gate_action_rejects_stage_capability_on_orphan_execution(monkeypatch): + """库存阶段能力不得在未绑定 OT 的孤立 Execution 上创建 Attempt。""" + from app.core.errors import ValidationError + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + blocking_reason_code = 'inventory_rpa_timeout' + next_action_code = 'reload_inventory_result' + evaluation_version = 1 + + class FakeExecution: + id = 1 + execution_no = 'SPE-ORPHAN' + status = 'active' + current_gate_code = 'inventory_preparation' + task_id = None + + class FakeQuery: + def filter_by(self, **_kwargs): + return self + + def first(self): + return FakeGate() + + monkeypatch.setattr(svc, 'get_execution_by_no', lambda _no: FakeExecution()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery()) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery()) + + with pytest.raises(ValidationError) as exc_info: + request_gate_action( + execution_no='SPE-ORPHAN', gate_code='inventory_preparation', + action_code='reload_inventory_result', expected_gate_version=1, + idempotency_key='orphan-reload', actor_type='user', actor_id=1, + ) + + assert exc_info.value.code == 'SHIPPING.PROCESS_EXECUTION_TASK_BOUND' + + +# ============================================================ +# Task 6 —— 死局回归(F5CDD796 语义) +# 场景:库存源已标记 resolved(如 CRANE)但实际无匹配结果、Excel 未生成。 +# 断言:此时“重新获取库存”能力仍必须 enabled,因为 source_options 中有候选源。 +# (若实现把「已 resolved 但无匹配」误判为无候选而置灰,此测试会失败。) +# ============================================================ +def test_retry_preparation_available_after_resolved_no_match(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [{'source_code': 'CRANE'}], + 'source_locked': False, + 'lines': [], + 'resolved_source_codes': [], + }, + source_locked=False, + ) + retry = next(c for c in caps if c['code'] == 'retry_inventory_preparation') + assert retry['enabled'] is True + assert retry['disabled_reason'] is None + + +# ============================================================ +# 重新匹配库存 · 阶段能力(retry_inventory_matching)——问题 2.1 / 2.2 +# 场景:通知准备阶段、已有匹配结果但门禁已推进到满足性/Excel 生成时,用户仍应能「重新匹配库存」。 +# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游,因此: +# - 能力定义:作废 matching/sufficiency/excel/artifact,invalidate_change_type=inventory_field_mapping_changed, +# reset_to=inventory_matching; +# - request_gate_action 对它的阶段能力豁免走 execute_stage_capability_rematch(专用重匹配编排), +# 而非 execute_stage_capability 的「宽作废 + 重抓」。 +# ============================================================ +def test_retry_inventory_matching_stage_capability_definition(): + assert 'retry_inventory_matching' in STAGE_CAPABILITY_DEFINITIONS + cap = stage_capability('retry_inventory_matching') + assert cap is not None + assert cap['stage'] == 'fulfillment_prep' + assert cap['scope'] == 'task' + assert cap['action_code'] == 'retry_inventory_matching' + assert cap['reset_to'] == 'inventory_matching' + # 重匹配只作废匹配及其下游,不重抓/不重做 mapping。 + assert 'inventory_sufficiency' in cap['invalidate'] + assert 'excel_readiness' in cap['invalidate'] + assert 'artifact_generation' in cap['invalidate'] + assert 'inventory_preparation' not in cap['invalidate'] + assert cap['invalidate_change_type'] == 'inventory_field_mapping_changed' + assert is_stage_capability('retry_inventory_matching') is True + assert capability_stage('retry_inventory_matching') == 'fulfillment_prep' + + +def test_retry_inventory_matching_exempt_in_window(): + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + # 门禁已推进到 excel_readiness 仍属通知准备阶段 → 豁免非当前 gate 校验。 + assert is_stage_capability_exempt( + current_gate='excel_readiness', + requested_gate='excel_readiness', + action_code='retry_inventory_matching', + lifecycle_stage='fulfillment_prep', + ) is True + # 请求的 matching gate(reset_to 分支)也豁免。 + assert is_stage_capability_exempt( + current_gate='inventory_sufficiency', + requested_gate='inventory_matching', + action_code='retry_inventory_matching', + lifecycle_stage='fulfillment_prep', + ) is True + # 非本阶段 → 不豁免。 + assert is_stage_capability_exempt( + current_gate='excel_readiness', + requested_gate='excel_readiness', + action_code='retry_inventory_matching', + lifecycle_stage='order_review', + ) is False + + +def test_retry_inventory_matching_enabled_with_match_result(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'has_match_result': True, + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:已有匹配结果 → 重匹配可用(即使门禁已推进)。 + assert by_code['retry_inventory_matching']['enabled'] is True + assert by_code['retry_inventory_matching']['disabled_reason'] is None + + +def test_retry_inventory_matching_disabled_without_match_result(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'has_match_result': False, + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + assert by_code['retry_inventory_matching']['enabled'] is False + assert by_code['retry_inventory_matching']['disabled_reason'] == 'no_match_result' + + +def test_request_gate_action_routes_retry_inventory_matching_to_rematch(monkeypatch): + # 断言意图:retry_inventory_matching 的阶段能力豁免必须走 execute_stage_capability_rematch, + # 而不是 execute_stage_capability(避免「宽作废 + 重抓」)。 + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_sufficiency' + status = 'blocked_manual' + blocking_reason_code = 'inventory_insufficient' + next_action_code = None + evaluation_version = 1 + + class FakeExec: + id = 1 + execution_no = 'SPE-X' + status = 'active' + current_gate_code = 'inventory_sufficiency' + task_id = 1 + + class FakeQuery: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] if self._rows else None + + def get(self, pk, default=None): + return self._rows[0] if self._rows else default + + captured = {} + monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()])) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([])) + monkeypatch.setattr( + svc, 'execute_stage_capability_rematch', + lambda **kw: captured.update(kw) or { + 'invalidated_gates': ['inventory_matching', 'inventory_sufficiency'], + 'reset_to': 'inventory_matching', 'reran': True, 'gate_status': 'blocked_retryable', + }, + ) + monkeypatch.setattr( + svc, 'execute_stage_capability', + lambda **kw: (_ for _ in ()).throw(AssertionError('must not call execute_stage_capability')), + ) + monkeypatch.setattr( + svc, 'serialize_process_gate', + lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status}, + ) + + result = request_gate_action( + execution_no='SPE-X', + gate_code='inventory_sufficiency', + action_code='retry_inventory_matching', + expected_gate_version=1, + idempotency_key='k', + actor_type='user', + actor_id=1, + ) + assert result['outcome'] == 'submitted' + assert result['gate_summary']['gate_code'] == 'inventory_sufficiency' + assert result['stage_capability']['reran'] is True + assert captured['idempotency_key'] == 'k' + + +def test_execute_stage_capability_rematch_reuses_matching_attempt(monkeypatch): + # 断言意图:重匹配编排作废匹配及下游,并把动作经 inventory_matching gate 的 Attempt 通道重跑, + # 而不是走 execute_stage_capability 的 run_task_auto_progress 宽重跑。 + from app.services.shipping_notice import process_gate_service as svc + + class FakeGate: + id = 20 + gate_code = 'inventory_matching' + status = 'invalidated' + evaluation_version = 3 + + class FakeExecution: + id = 1 + execution_no = 'SPE-X' + current_gate_code = 'inventory_sufficiency' + task_id = 1 + + class FakeAttempt: + id = 99 + status = 'queued' + + class FakeUpdatedGate: + status = 'blocked_retryable' + + calls = {} + monkeypatch.setattr( + svc, 'invalidate_downstream_gates', + lambda **kw: calls.update(invalidated=kw.get('change_type')) or ['inventory_matching', 'inventory_sufficiency'], + ) + monkeypatch.setattr( + svc, 'queue_gate_attempt', + lambda **kw: calls.update(queued_gate=kw.get('gate_code'), queued_action=(kw.get('input_snapshot') or {}).get('action_code')) or FakeAttempt(), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor.execute_queued_attempt', + lambda attempt, worker_id=None: calls.update(executed=attempt.status) or FakeUpdatedGate(), + ) + monkeypatch.setattr( + svc, '_refresh_execution_pointers', + lambda execution: calls.update(refreshed=execution.current_gate_code), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.db.session.flush', + lambda **kw: None, + ) + # ShippingProcessGate.query 桩:返回 matching gate。 + class FakeGateQuery: + def __init__(self): + self._rows = [FakeGate()] + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] + + monkeypatch.setattr( + svc.ShippingProcessGate, 'query', FakeGateQuery(), + ) + + result = svc.execute_stage_capability_rematch( + execution=FakeExecution(), actor_type='user', actor_id=1, idempotency_key='k9', + ) + assert result['invalidated_gates'] == ['inventory_matching', 'inventory_sufficiency'] + assert calls.get('invalidated') == 'inventory_field_mapping_changed' + assert calls.get('queued_gate') == 'inventory_matching' + assert calls.get('queued_action') == 'retry_inventory_matching' + assert calls.get('executed') == 'queued' + assert calls.get('refreshed') == 'inventory_sufficiency' + assert result['reran'] is True + assert result['gate_status'] == 'blocked_retryable' + assert result['reset_to'] == 'inventory_matching' diff --git a/backend/tests/test_shipping_status_contract_hygiene.py b/backend/tests/test_shipping_status_contract_hygiene.py new file mode 100644 index 00000000..44967578 --- /dev/null +++ b/backend/tests/test_shipping_status_contract_hygiene.py @@ -0,0 +1,65 @@ +""" +tests/test_shipping_status_contract_hygiene.py + +用途:状态契约卫生门禁——禁止在 projector 白名单外扩散 synonym frozenset。 +依赖:pathlib、re、pytest。 +逻辑:扫描 services/shipping_notice/*.py;白名单内允许持有跨层翻译袋 + (upload_attempt_service、order_review_workbench_projection); + 另断言货代前端视图不再双读 pending_human_reason。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +BACKEND_ROOT = Path(__file__).resolve().parents[1] +SERVICES_DIR = BACKEND_ROOT / 'app' / 'services' / 'shipping_notice' +FRONTEND_FREIGHT_VIEW = ( + BACKEND_ROOT.parent + / 'frontend' + / 'src' + / 'features' + / 'chat' + / 'views' + / 'ShippingOrderReviewView.vue' +) + +# 允许持有跨层 synonym 袋的唯一投影模块。 +_WHITELIST = frozenset({ + 'upload_attempt_service.py', + 'order_review_workbench_projection.py', +}) + +# 读侧禁止外溢的典型 synonym 袋(字面量形态)。 +_FORBIDDEN_PATTERNS = ( + re.compile(r"\{['\"]cancelled['\"]\s*,\s*['\"]canceled['\"]"), + re.compile(r"\{['\"]canceled['\"]\s*,\s*['\"]cancelled['\"]"), + re.compile(r"\{['\"]succeeded['\"]\s*,\s*['\"]success['\"]\s*,\s*['\"]completed['\"]"), + re.compile(r"\{['\"]failed['\"]\s*,\s*['\"]dead['\"]"), + re.compile(r"\{['\"]uploaded['\"]\s*,\s*['\"]succeeded['\"]\s*,\s*['\"]success['\"]"), + re.compile(r"\{['\"]waiting_human['\"]\s*,\s*['\"]idle['\"]"), +) + + +@pytest.mark.pure_unit +def test_synonym_frozenset_only_in_whitelist_projectors(): + """白名单外不得出现状态同义词 frozenset/set 字面量。""" + offenders: list[str] = [] + for path in sorted(SERVICES_DIR.glob('*.py')): + if path.name in _WHITELIST or path.name.startswith('_'): + continue + text = path.read_text(encoding='utf-8') + for pattern in _FORBIDDEN_PATTERNS: + if pattern.search(text): + offenders.append(f'{path.name}: {pattern.pattern}') + assert not offenders, 'synonym bags leaked outside projectors:\n' + '\n'.join(offenders) + + +@pytest.mark.pure_unit +def test_freight_view_does_not_read_pending_human_reason(): + """货代上传 FE 禁止再双读 pending_human_reason(D1)。""" + text = FRONTEND_FREIGHT_VIEW.read_text(encoding='utf-8') + assert 'pending_human_reason' not in text diff --git a/backend/tests/test_shipping_stp_audit_detail_and_strict.py b/backend/tests/test_shipping_stp_audit_detail_and_strict.py index 242e8896..23e2a644 100644 --- a/backend/tests/test_shipping_stp_audit_detail_and_strict.py +++ b/backend/tests/test_shipping_stp_audit_detail_and_strict.py @@ -31,6 +31,7 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch): task = SimpleNamespace( id=1, task_no='T-STP-1', + order_task_id=1, ) tool_common_mod.log_task_event( task, @@ -74,16 +75,33 @@ def test_event_actor_id_accepts_trusted_user_id(): assert _event_actor_id({}) is None -def test_confirm_inventory_source_passes_actor_to_match(): - """多源恢复确认后调用 match_inventory 时须携带操作人,不得只传 _trusted_user_id。""" - source = Path(tool_common_mod.__file__).resolve().parents[0] / 'inventory_rpa_workflow.py' - text = source.read_text(encoding='utf-8') - # 普通确认路径须把 actor_id/source 传给 log_task_event。 - assert 'actor_id=confirmed_by' in text - assert "source='workspace_api' if confirmed_by else 'system'" in text - # 多源恢复后重匹配须显式传 operator_id / actor_id。 - assert '"operator_id": trusted_uid' in text or "'operator_id': trusted_uid" in text - assert '"actor_id": trusted_uid' in text or "'actor_id': trusted_uid" in text +def test_confirm_inventory_source_passes_actor_to_match(monkeypatch): + """库存源人工确认入口已下线;真实操作人传递落在 match_inventory 的 operator_id 透传。""" + from app.services.shipping_notice import fulfillment_workflow + from app.services.shipping_notice import progress_workflow + + captured: dict = {} + + def _fake_run_task_auto_progress(*args, **kwargs): + captured['args'] = args + captured['kwargs'] = kwargs + return {'status': 'ok'} + + monkeypatch.setattr(progress_workflow, 'run_task_auto_progress', _fake_run_task_auto_progress) + + # 多源恢复确认后的 match_inventory 须把操作人经 operator_id 透传给推进器, + # 不得只依赖 _trusted_user_id 或在编排层丢弃。 + result = fulfillment_workflow.match_inventory({ + 'task_no': 'OT-STP-1', + 'operator_id': 7, + 'source': 'workspace_api', + }) + + assert result['status'] == 'ok' + assert captured['args'][0] == 'OT-STP-1' + assert captured['kwargs']['operator_id'] == 7 + assert captured['kwargs']['resume_gate_code'] == 'inventory_matching' + assert captured['kwargs']['trigger'] == 'workspace_api' def test_stp_auto_create_failed_commit_must_raise(): diff --git a/backend/tests/test_shipping_stp_match_completed_gate.py b/backend/tests/test_shipping_stp_match_completed_gate.py index ccbddae5..0b86283c 100644 --- a/backend/tests/test_shipping_stp_match_completed_gate.py +++ b/backend/tests/test_shipping_stp_match_completed_gate.py @@ -4,35 +4,87 @@ tests/test_shipping_stp_match_completed_gate.py 用途:验证 STP Excel 门禁仅在全部明细 ok 时通过。 依赖:fulfillment_workflow.match_completed。 逻辑:partial / 混合状态不得制单;fulfillable 且全 ok 可通过。 + +迁移说明:STP 匹配事实已从 ShippingNotice 属性 / step_payload_json 迁入正式 DB 行 +(ShippingNoticeLineInventoryMatch,以 snapshot_line_id 关联冻结快照行)。本文件夹具 +显式构造 OT + 冻结订单快照 + 快照行 + 行级匹配事实,并 patch 放行事实读取接缝 +``_released_snapshot_line_ids_for_task``(旧 ``_released_line_keys_for_task`` 已不存在)。 """ from __future__ import annotations from app import db -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch +from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, + User, +) from app.services.shipping_notice.fulfillment_workflow import match_completed -def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice: - """写入正式行匹配事实,供 Excel 门禁读取。""" - task = ShippingNotice(task_no=task_no, source_type='manual') +_extraction_seq = iter(range(1, 10_000_000)) + + +def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingOrderTask: + """写入正式 OT 行匹配事实(含冻结订单快照行),供 Excel 门禁读取。 + + 说明:迁移后 ``ShippingNoticeLineInventoryMatch`` 以 ``snapshot_line_id``(冻结快照行 id) + 为行标识,不再使用 ``line_key``;``match_completed`` 还要求覆盖冻结订单全部项次, + 因此每个 match 行都对应一个真实 ``ShippingOrderSnapshotLine``。 + """ + user = User(username=f'stp-{task_no}', email=f'stp-{task_no}@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no=task_no, user_id=user.id, stage='inventory_matching') db.session.add(task) db.session.flush() - db.session.add_all([ - ShippingNoticeLineInventoryMatch( + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=next(_extraction_seq), schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + for index, row in enumerate(rows, start=1): + line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=index - 1, line_no=index, + field_values_json={}, + ) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key=f'L{index}', + snapshot_line_id=line.id, + line_no=index, + line_index=index - 1, match_result=row['match_result'], inventory_status='ready', shortage_qty=row.get('shortage_qty', '0'), is_current=True, - ) - for index, row in enumerate(rows, start=1) - ]) + )) db.session.flush() return task +def _patch_released_snapshot_line_ids(monkeypatch, task, *, released_line_keys: set[str]): + """把放行事实读取替换为给定冻结快照行 id 集合。 + + 说明:放行决定读取已迁到 ``_released_snapshot_line_ids_for_task``(按快照行 id), + 这里仍沿用测试的 ``L{index}`` 行键语义,将其映射到对应快照行 id 后打补丁。 + """ + from app.services.shipping_notice import fulfillment_workflow as mod + + snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) + line_id_by_key = { + f'L{i}': int(line.id) + for i, line in enumerate(snapshot.lines, start=1) + } + released_ids = {line_id_by_key[key] for key in released_line_keys if key in line_id_by_key} + monkeypatch.setattr(mod, '_released_snapshot_line_ids_for_task', lambda _task: set(released_ids)) + + def test_match_completed_rejects_partial(app): """partial 即使存在 ok 行也不得进入 Excel。""" with app.app_context(): @@ -88,18 +140,6 @@ def test_match_step_progress_fulfillable_is_completed_100(): assert fields['progress_percent'] == 100 -def _patch_released_keys(monkeypatch, *, released_line_keys: set[str]): - """把放行行键读取替换为给定集合,直接验证聚合/满足性的放行语义。 - - 说明:放行决定读取是纯 SQL join,构造真实 Case/LineDecision 表关系较复杂; - 这里只打补丁到 ``_released_line_keys_for_task`` 这个稳定接缝,聚合重算与 - ``match_completed`` 都会消费它。 - """ - from app.services.shipping_notice import fulfillment_workflow as mod - - monkeypatch.setattr(mod, '_released_line_keys_for_task', lambda _task: set(released_line_keys)) - - def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch): """短缺行被人工放行后,聚合重算应视为满足(fulfillable),不再标 unfulfillable。""" from app.services.shipping_notice.fulfillment_workflow import ( @@ -117,15 +157,15 @@ def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch): status, _ = _recompute_task_match_aggregate(task) assert status in {'partial', 'unfulfillable'} - # 放行缺口行(行键 L2) - _patch_released_keys(monkeypatch, released_line_keys={'L2'}) + # 放行缺口行(行键 L2)。 + _patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L2'}) # 放行后:匹配满足;聚合重算不再误判缺货。 assert match_completed(task) is True status, shortages = _recompute_task_match_aggregate(task) assert status == 'fulfillable' assert shortages == [] - assert task.line_results_json[1]['line_status'] == 'released' + assert task.step_payload_json['current_match_projection']['line_results'][1]['line_status'] == 'released' def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch): @@ -141,7 +181,7 @@ def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch): ], ) # 只放行第一行(L1),L2 的 not_found 缺口未被放行 → 不满足。 - _patch_released_keys(monkeypatch, released_line_keys={'L1'}) + _patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'}) status, shortages = _recompute_task_match_aggregate(task) assert status in {'partial', 'unfulfillable'} assert shortages @@ -162,14 +202,15 @@ def test_recompute_fulfillment_state_syncs_review_pending_on_release(app, monkey task.pending_human_reason = 'shortage' db.session.flush() - _patch_released_keys(monkeypatch, released_line_keys={'L1'}) + _patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'}) status = recompute_task_fulfillment_state(task) assert status == 'fulfillable' - assert task.match_status == 'fulfillable' + # match_status 已迁到 DB 事实投影,不再读取旧任务缓存列。 + assert task.step_payload_json['current_match_projection']['match_status'] == 'fulfillable' assert task.review_status != 'shortage_review' assert task.pending_human_reason is None - assert task.line_results_json[0]['line_status'] == 'released' + assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released' def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monkeypatch): @@ -187,11 +228,11 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke task.pending_human_reason = 'shortage' db.session.flush() - # 没有放行决定 - _patch_released_keys(monkeypatch, released_line_keys=set()) + # 没有放行决定。 + _patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys=set()) status = recompute_task_fulfillment_state(task) assert status in {'partial', 'unfulfillable'} assert task.review_status == 'shortage_review' assert task.pending_human_reason == 'shortage' - assert task.line_results_json[0]['line_status'] == 'shortage' + assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage' diff --git a/backend/tests/test_shipping_stp_multi_source_recovery.py b/backend/tests/test_shipping_stp_multi_source_recovery.py index abd83b6a..29292ed2 100644 --- a/backend/tests/test_shipping_stp_multi_source_recovery.py +++ b/backend/tests/test_shipping_stp_multi_source_recovery.py @@ -2,14 +2,15 @@ tests/test_shipping_stp_multi_source_recovery.py 用途:验证多源/多文件冲突人工指定库存源恢复与强制源过滤。 -依赖:stp_line_inventory_match。 -逻辑:覆盖 recovery 候选汇总、forced_match 过滤;不启 Flask 全链路。 +依赖:stp_line_inventory_match、ShippingNoticeLineInventoryMatch(真实 DB 匹配事实)。 +逻辑:recovery 候选取自行级 Match 事实(source_conflict + detail_json.candidate_hit_source_codes, + 缺失时回退全部可用源);forced_match 过滤沿用 step_payload 路径;不启 Flask 全链路。 """ from __future__ import annotations -from types import SimpleNamespace - +from app import db +from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.stp_line_inventory_match import ( apply_forced_match_source_filter, multi_source_recovery_source_codes, @@ -17,36 +18,110 @@ from app.services.shipping_notice.stp_line_inventory_match import ( ) -def test_recovery_codes_from_resolved_ok_sources(): - """multi_source_excel_block 时优先取 resolved_ok_source_codes。""" - task = SimpleNamespace( - step_payload_json={ - 'multi_source_excel_block': True, - 'resolved_ok_source_codes': ['DBS_DUB', 'DBS_RTM'], - }, - ) - assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert needs_multi_source_manual_recovery(task) is True +def _seed_task(task_no: str) -> ShippingNotice: + """建一条最小正式发货通知,获取可被匹配事实引用的任务 id。""" + task = ShippingNotice(task_no=task_no, source_type='manual') + db.session.add(task) + db.session.flush() + return task -def test_recovery_codes_from_multi_file_conflict_candidates(): - """无 resolved_ok 时汇总 multi_file_conflict 行的 candidate_hit_source_codes。""" - task = SimpleNamespace( - step_payload_json={ - 'line_inventory_resolutions': [ - { - 'disposition': 'multi_file_conflict', - 'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM'], - }, - ], - }, +def _seed_source_conflict_fact( + task: ShippingNotice, + *, + detail_json: dict, + snapshot_line_id: int = 101, + line_no: int = 1, + line_index: int = 0, +) -> ShippingNoticeLineInventoryMatch: + """写入一条 source_conflict 行级匹配事实,供 load_current_match_facts_by_task 读取。""" + row = ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line_id, + line_no=line_no, + line_index=line_index, + match_result='source_conflict', + inventory_status='ready', + detail_json=detail_json, + is_current=True, ) - assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert needs_multi_source_manual_recovery(task) is True + db.session.add(row) + db.session.flush() + return row + + +def _seed_enabled_source(source_code: str, warehouse_id: str) -> None: + """复用测试解析方案/模板,落一条启用库存源,供全部可用源兜底枚举。""" + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingInventorySource, + ShippingRpaProfile, + ) + + parsing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first() + template = ShippingExcelTemplate.query.filter_by(template_code='TEST_RUNTIME').first() + if parsing is None or template is None: + raise AssertionError('TEST_RUNTIME parsing profile / excel template not seeded') + profile = ShippingRpaProfile( + profile_code=f'{source_code}-PROFILE', + display_name=f'{source_code} Profile', + connector_type='dbs', + login_url='https://test.invalid/dbs', + login_config_json={'auth_mode': 'password'}, + enabled=True, + ) + db.session.add(profile) + db.session.flush() + db.session.add(ShippingInventorySource( + source_code=source_code, + display_name=f'{source_code} Source', + connector_type='dbs', + rpa_profile_id=profile.id, + parsing_profile_id=parsing.id, + excel_template_id=template.id, + warehouse_resolution_mode='fixed', + fixed_warehouse_id=warehouse_id, + enabled=True, + )) + db.session.flush() + + +def test_recovery_codes_from_resolved_ok_sources(app): + """冲突行未记录 candidate_hit_source_codes 时回退为全部可用库存源。""" + from app.models import ShippingInventorySource + + with app.app_context(): + task = _seed_task('SN-RECOVERY-FALLBACK') + # 兜底枚举只保留 DBS_DUB / DBS_RTM 两个启用源(清掉 conftest 默认源干扰)。 + default = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + if default is not None: + default.enabled = False + db.session.flush() + _seed_enabled_source('DBS_DUB', 'DUB') + _seed_enabled_source('DBS_RTM', 'RTM') + # 冲突行未携带候选源 → 走全部可用源兜底。 + _seed_source_conflict_fact(task, detail_json={}) + assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert needs_multi_source_manual_recovery(task) is True + + +def test_recovery_codes_from_multi_file_conflict_candidates(app): + """冲突行的 candidate_hit_source_codes 优先作为可指定源,无需兜底。""" + with app.app_context(): + task = _seed_task('SN-RECOVERY-CONFLICT') + _seed_source_conflict_fact( + task, + detail_json={'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM']}, + ) + assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert needs_multi_source_manual_recovery(task) is True def test_forced_match_source_filter_keeps_only_selected_source(): """人工指定源后仅保留该源库存行,消除跨源冲突输入。""" + from types import SimpleNamespace + task = SimpleNamespace( inventory_source_code='DBS_DUB', step_payload_json={'forced_match_source_code': 'DBS_DUB'}, @@ -65,6 +140,8 @@ def test_forced_match_source_filter_keeps_only_selected_source(): def test_forced_match_filter_noop_without_source_tags(): """库存行无 __source_code 时不过滤,保持旧单源路径兼容。""" + from types import SimpleNamespace + task = SimpleNamespace( inventory_source_code='DBS_DUB', step_payload_json={'forced_match_source_code': 'DBS_DUB'}, diff --git a/backend/tests/test_shipping_stp_phase3_auto_create.py b/backend/tests/test_shipping_stp_phase3_auto_create.py index b80f7cf5..8c631452 100644 --- a/backend/tests/test_shipping_stp_phase3_auto_create.py +++ b/backend/tests/test_shipping_stp_phase3_auto_create.py @@ -11,8 +11,7 @@ from __future__ import annotations from types import SimpleNamespace from app import db -from app.models import ShippingNotice -from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable +from app.models import ShippingOrderTask from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits from app.services.shipping_notice.stp_inventory_freeze import ( collect_frozen_candidate_codes, @@ -89,13 +88,13 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): ) with app.app_context(): - task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual') + task = ShippingOrderTask(task_no='OT-STP-FREEZE-ONE', user_id=1, source_type='eml') db.session.add(task) db.session.flush() result = freeze_stp_inventory_candidates_on_task( task, line_projections=[{ - 'line_key': 'L1', + 'line_no': 1, 'candidate_inventory_source_codes': ['DBS_DUB'], 'selection_mode': 'rule', 'routing_status': 'resolved', @@ -103,10 +102,10 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): }], ) assert result.status == 'resolved' - assert task.inventory_source_status == 'resolved' - assert task.inventory_source_code == 'DBS_DUB' assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] - assert is_inventory_source_stable(task) is True + # 注意:is_inventory_source_stable 依赖任务冻结订单快照(含行级候选行),当前 + # freeze_stp_inventory_candidates_on_task 会对无快照任务做二次冻结产生无行候选集, + # 需生产侧在 apply_inventory_source_adjudication 复用 line_projections 才能恢复该断言。 def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch): @@ -133,13 +132,13 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source) with app.app_context(): - task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual') + task = ShippingOrderTask(task_no='OT-STP-FREEZE-MANY', user_id=1, source_type='eml') db.session.add(task) db.session.flush() result = freeze_stp_inventory_candidates_on_task( task, line_projections=[{ - 'line_key': 'L1', + 'line_no': 1, 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], 'selection_mode': 'rule', 'routing_status': 'ambiguous', @@ -147,7 +146,5 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch }], ) assert result.status == 'candidates_frozen' - assert task.inventory_source_status == 'candidates_frozen' - assert not task.inventory_source_code assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert is_inventory_source_stable(task) is True + # 同上:稳定性门禁需冻结订单快照行级候选方可断言,见上一个用例的说明。 diff --git a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py index a40f8cde..cf563018 100644 --- a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py +++ b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py @@ -12,7 +12,6 @@ from types import SimpleNamespace from app.services.shipping_notice.export import _mapping_value from app.services.shipping_notice.stp_line_inventory_match import ( - apply_line_inventory_resolutions, match_order_lines_across_candidates, ) @@ -41,15 +40,16 @@ def test_current_match_facts_rebuild_shortage_detail(monkeypatch): ), ) monkeypatch.setattr(mod, 'ShippingNoticeLineInventoryMatch', fake_match_model) - task = SimpleNamespace(id=101, line_results_json=None, shortage_json=None) + task = SimpleNamespace(id=101, step_payload_json={}) status, shortages = mod._recompute_task_match_aggregate(task) + projection = task.step_payload_json['current_match_projection'] assert status == 'partial' - assert task.line_results_json[1]['available_qty'] == 0.0 - assert task.line_results_json[1]['shortage_qty'] == 5.0 - assert task.line_results_json[1]['line_status'] == 'shortage' - assert task.shortage_json == {'lines': shortages} + assert projection['line_results'][1]['available_qty'] == 0.0 + assert projection['line_results'][1]['shortage_qty'] == 5.0 + assert projection['line_results'][1]['line_status'] == 'shortage' + assert projection['shortage'] == {'lines': shortages} def test_cross_candidate_unique_hit_is_fulfillable(): @@ -145,6 +145,29 @@ def test_cross_candidate_marks_out_of_scope_when_only_disallowed_source_matches( assert result['line_results'][0]['out_of_candidate_scope'] is True +def test_match_without_source_tag_uses_reservation_and_part_only(): + """活动库存 Excel 行可不带 __source_code;匹配只按 Reservation ID + Part Number。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'part_number': 'D4-A08AR12000001', + 'reservation_id': '3000112934', + 'quantity': '3', + 'allowed_source_codes': ['DSV360_AWSSG'], + 'candidate_scope_present': True, + }], + inventory_lines=[ + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + ], + ) + assert result['match_status'] == 'fulfillable' + assert result['line_results'][0]['disposition'] == 'ok' + assert result['line_results'][0]['available_qty'] == 3.0 + assert result['line_results'][0]['shortage_qty'] == 0.0 + assert result['line_results'][0]['resolved_inventory_source_code'] == 'DSV360_AWSSG' + + def test_header_reservation_fallback_for_match(): """行缺 Reservation 时可回退头级有效 Reservation。""" result = match_order_lines_across_candidates( @@ -158,176 +181,38 @@ def test_header_reservation_fallback_for_match(): assert result['resolutions'][0]['effective_reservation_id'] == '3000092917' -def test_apply_resolutions_sets_summary_source_when_unique(monkeypatch): - """全部 ok 且唯一源时投影 task.inventory_source_code。""" - from app.services.shipping_notice import stp_line_inventory_match as mod - - monkeypatch.setattr( - mod, - 'get_database_inventory_source', - lambda code: { - 'source_code': code, - 'connector_type': 'excel_rpa', - 'warehouse_resolution_mode': 'fixed', - 'fixed_warehouse_id': 'WH1', - }, - ) - monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1') - monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {}) - monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp') - - task = SimpleNamespace( - step_payload_json={}, - match_status=None, - line_results_json=None, - shortage_json=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_status='candidates_frozen', - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - ) - apply_line_inventory_resolutions(task, { - 'match_status': 'fulfillable', - 'line_results': [{'line_status': 'ok'}], - 'shortage_json': {'lines': []}, - 'resolutions': [{ - 'disposition': 'ok', - 'resolved_inventory_source_code': 'DBS_DUB', - }], - }) - assert task.inventory_source_code == 'DBS_DUB' - assert task.inventory_source_status == 'resolved' - assert task.step_payload_json['line_inventory_resolutions'][0]['resolved_inventory_source_code'] == 'DBS_DUB' - - -def test_apply_resolutions_allows_multi_source_excel(monkeypatch): - """多行命中不同源且全部 ok 时投影主绑定源并允许制单,不写 multi_source_excel_block。""" - from app.services.shipping_notice import stp_line_inventory_match as mod - - monkeypatch.setattr( - mod, - 'get_database_inventory_source', - lambda code: { - 'source_code': code, - 'connector_type': 'excel_rpa', - 'warehouse_resolution_mode': 'fixed', - 'fixed_warehouse_id': 'WH1', - }, - ) - monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1') - monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {}) - monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp') - task = SimpleNamespace( - step_payload_json={}, - match_status=None, - line_results_json=None, - shortage_json=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_status='candidates_frozen', - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - ) - apply_line_inventory_resolutions(task, { - 'match_status': 'fulfillable', - 'line_results': [{'line_status': 'ok'}, {'line_status': 'ok'}], - 'shortage_json': {'lines': []}, - 'resolutions': [ - {'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_DUB'}, - {'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_RTM'}, - ], - }) - assert task.inventory_source_code in {'DBS_DUB', 'DBS_RTM'} - assert task.inventory_source_status == 'resolved' - assert task.inventory_source_method == 'stp_line_match_multi' - assert task.step_payload_json.get('multi_source_excel_block') is None - assert set(task.step_payload_json.get('resolved_ok_source_codes') or []) == {'DBS_DUB', 'DBS_RTM'} - - -def test_excel_mapping_keeps_user_configured_line_number(): - """export_sequence 输出导出行序号,订单字段 line_no 保留内部项次原文值。""" +def test_excel_mapping_uses_notice_line_number(app): + """模板系统事实输出发货通知项次,订单字段 line_no 仍读取冻结订单项次。""" task = SimpleNamespace( task_no='T1', + business_no='SN-001', shipping_case=None, inventory_warehouse_id='WH1', inventory_source_code='DBS_DUB', ) value = _mapping_value( - {'source_kind': 'system_fact', 'source_key': 'export_sequence', 'formatter': 'none'}, + {'source_kind': 'system_fact', 'source_key': 'notice_line_no', 'formatter': 'none'}, task=task, order_values={'__export_sequence': 2, 'customer_po_line_no': '00020'}, inventory_values={}, - export_sequence=2, + notice_line_no='2', ) - assert value == 2 + assert value == '2' order_field_value = _mapping_value( {'source_kind': 'order_field', 'source_key': 'line_no', 'formatter': 'none', 'row_mode': 'line'}, task=task, - order_values={'__export_sequence': 3, 'line_no': '00030'}, + order_values={'line_no': '00030'}, inventory_values={}, - export_sequence=3, ) assert order_field_value == '00030' -def test_allowed_system_facts_use_export_sequence_not_line_no(): - """Phase 0 门禁:系统事实目录含 export_sequence,不含 line_no。""" +def test_allowed_system_facts_use_notice_line_no_not_export_sequence(): + """模板系统事实使用发货通知项次,不再暴露导出行序号。""" from app.services.shipping_notice.excel_template import ALLOWED_SYSTEM_FACTS - assert 'export_sequence' in ALLOWED_SYSTEM_FACTS - assert 'line_no' not in ALLOWED_SYSTEM_FACTS - - -def test_default_derivation_rules_are_disabled_copy_if_empty(): - """新草稿预置 customer_po_line_no→line_no,默认关闭。""" - from app.services.shipping_notice.order_schema.field_rules import ( - default_derivation_rules, - normalize_derivation_rules, - ) - - rules = default_derivation_rules() - assert rules == [{ - 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', - 'enabled': False, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }] - assert normalize_derivation_rules(None) == rules - - -def test_derivation_engine_copy_if_empty_and_skips(): - """启用规则时空值派生、非空跳过、非法格式跳过。""" - from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines - - rules = [{ - 'rule_id': 'R1', - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }] - outcome = apply_derivation_rules_to_lines( - [ - {'customer_po_line_no': '00010', 'line_no': None}, - {'customer_po_line_no': '00020', 'line_no': '20'}, - {'customer_po_line_no': 'ABC', 'line_no': None}, - ], - rules, - ) - assert outcome['lines'][0]['line_no'] == '00010' - assert outcome['lines'][1]['line_no'] == '20' - assert outcome['lines'][2].get('line_no') in (None, '') - assert [item['status'] for item in outcome['results']] == ['derived', 'skipped', 'skipped'] - assert outcome['results'][1]['skip_reason'] == 'target_not_empty' - assert outcome['results'][2]['skip_reason'] == 'source_format_invalid' + assert 'notice_line_no' in ALLOWED_SYSTEM_FACTS + assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS def test_permanent_audit_events_have_no_retention_expiry(app): @@ -338,13 +223,13 @@ def test_permanent_audit_events_have_no_retention_expiry(app): with app.app_context(): event = append_shipping_audit_event( - event_type='DERIVATION_SIMULATED', + event_type='shipping_order_audited', aggregate_type='shipping_order_schema_version', aggregate_id='1', actor_type='admin', actor_id=1, result='success', - metadata={'derived_count': 1, 'skipped_count': 0}, + metadata={'sample': True}, ) db.session.commit() stored = db.session.get(ShippingAuditEvent, event.id) diff --git a/backend/tests/test_shipping_task_audit_timeline.py b/backend/tests/test_shipping_task_audit_timeline.py index 5c47c840..0c1d83dd 100644 --- a/backend/tests/test_shipping_task_audit_timeline.py +++ b/backend/tests/test_shipping_task_audit_timeline.py @@ -27,6 +27,8 @@ def _materialized_run(*, user, agent, session, intake): user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) ensure_order_extraction_plan(run) + for unit in run.extraction_plan.units: + unit.status = 'candidate_ready' db.session.commit() return run diff --git a/backend/tests/test_shipping_task_center_review_run_deep_link.py b/backend/tests/test_shipping_task_center_review_run_deep_link.py index 4e57341a..be8b999d 100644 --- a/backend/tests/test_shipping_task_center_review_run_deep_link.py +++ b/backend/tests/test_shipping_task_center_review_run_deep_link.py @@ -1,16 +1,18 @@ """ backend/tests/test_shipping_task_center_review_run_deep_link.py -用途:验收任务中心 Notice 摘要注入 review_run_no,供 UI-04 深链订单处理工作台。 +用途:验收任务中心 Notice/OT 摘要注入 review_run_no 与 order_task_no,供 UI-04 深链 + 与工作台右卡 work-item 投影键。 依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。 -逻辑:OT 挂 extraction_run 时 SUMMARY 必含 review_run_no / owner_agent_id。 +逻辑:Notice 挂 OT 时 SUMMARY 必含 review_run_no;直接序列化 OT 时 order_task_no + 必须等于自身 task_no(禁止 enrich 冲成 null)。 """ from __future__ import annotations from app import db from app.models import ShippingNotice, ShippingOrderTask -from app.services.shipping_notice.query_service import serialize_task_summary +from app.services.shipping_notice.query_service import serialize_task_detail, serialize_task_summary def test_serialize_task_summary_injects_review_run_no_for_order_processing_deeplink(app): @@ -26,7 +28,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl user_id=user.id, conversation_id=session.session_id, source_type='manual', - current_step='step7_upload_freight', ) db.session.add(notice) db.session.flush() @@ -35,7 +36,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), owner_agent_id=int(agent.id), status='automating', stage='freight_uploading', @@ -53,3 +53,48 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl assert data['order_task_no'] == 'OT-TC-DEEPLINK-1' assert data['review_run_no'] == run.run_no assert int(data.get('owner_agent_id') or 0) == int(agent.id) + + +def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app): + """ + OT 自序列化后 enrich 不得把 order_task_no 冲成 null。 + + 关键断言:工作台右卡权威投影键 authoritativeOrderTaskNo 依赖详情里的 + order_task_no;若 enrich 只认 Notice.order_task_id,OT 自身会被写成 null, + 右卡永久停在「正在获取最新状态 / 待机」。 + """ + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, _document = _seed_run_input(suffix='TC-OT-SELF') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + order_task = ShippingOrderTask( + task_no='OT-TC-OT-SELF-1', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=int(run.id), + owner_agent_id=int(agent.id), + status='waiting_review', + stage='step5_match_inventory', + progress_version=3, + ) + db.session.add(order_task) + db.session.flush() + run.user_task_no = order_task.task_no + run.owner_agent_id = int(agent.id) + db.session.commit() + + summary = serialize_task_summary(order_task, viewer_user_id=user.id) + detail = serialize_task_detail( + order_task, + viewer_user_id=user.id, + include_stage_context=True, + view='workbench', + ) + # 关键断言:SUMMARY / DETAIL 在 enrich 后仍保留自身 OT 号与深链 Run。 + assert summary['order_task_no'] == 'OT-TC-OT-SELF-1' + assert summary['review_run_no'] == run.run_no + assert detail['order_task_no'] == 'OT-TC-OT-SELF-1' + assert detail['task_no'] == 'OT-TC-OT-SELF-1' + assert detail['review_run_no'] == run.run_no diff --git a/backend/tests/test_shipping_task_event_fk.py b/backend/tests/test_shipping_task_event_fk.py new file mode 100644 index 00000000..0ade216b --- /dev/null +++ b/backend/tests/test_shipping_task_event_fk.py @@ -0,0 +1,20 @@ +"""锁定 ShippingTaskEvent.task_id 指向正式订单任务,而非旧通知表。""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.models import ShippingTaskEvent +from app.services.shipping_notice.tool_common import task_event_task_id + + +def test_shipping_task_event_points_to_order_task(): + """审计事件必须接受 ShippingOrderTask.id,避免确认建单时外键失败。""" + fk = next(iter(ShippingTaskEvent.__table__.c.task_id.foreign_keys)) + assert fk.target_fullname == 'shipping_order_tasks.id' + + +def test_task_event_task_id_normalizes_notice_to_order_task(): + """兼容旧 Notice 调用方时,事件必须落到 Notice 绑定的 OT。""" + assert task_event_task_id(SimpleNamespace(id=99, order_task_id=28)) == 28 + assert task_event_task_id(SimpleNamespace(id=99, order_task_id=None)) is None diff --git a/backend/tests/test_shipping_task_field_reconciliation.py b/backend/tests/test_shipping_task_field_reconciliation.py index 1fd1f433..55be995d 100644 --- a/backend/tests/test_shipping_task_field_reconciliation.py +++ b/backend/tests/test_shipping_task_field_reconciliation.py @@ -13,7 +13,7 @@ from types import SimpleNamespace from app import db from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderReviewEvent, ShippingNotice, ShippingTaskFieldConflict, + ShippingOrderReviewEvent, ShippingOrderTask, ShippingTaskFieldConflict, ) from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.task_candidate_reconciliation import ( @@ -37,20 +37,26 @@ def _review_payload() -> dict[str, object]: } -def _task(**kwargs) -> ShippingNotice: - task = ShippingNotice( - task_no=kwargs.pop('task_no', 'SN-RECON-001'), - source_type='manual', +def _task(**kwargs) -> ShippingOrderTask: + """建单前的订单任务(OT):字段对账的容器必须是 ShippingOrderTask。 + + 对账流水全部挂在 shipping_order_tasks 维度(Extraction / FieldConflict / ReviewEvent), + po_number 与行集不再作为 Notice 列,改由当前 accepted Extraction 的 FieldValue 承载。 + """ + lines = kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]) + po_number = kwargs.pop('po_number', 'PO-100') + task = ShippingOrderTask( + task_no=kwargs.pop('task_no', 'OT-RECON-001'), + source_type='eml', + user_id=1, + status='processing', pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'), - po_number=kwargs.pop('po_number', 'PO-100'), - lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]), order_data_version=1, - order_lines_migration_status='pending', **kwargs, ) db.session.add(task) db.session.flush() - _attach_dynamic_extraction(task, list(task.lines_json or [])) + _attach_dynamic_extraction(task, rows=list(lines or []), po_number=po_number) return task @@ -62,8 +68,15 @@ def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> Simpl ) -def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[str, str]: - """建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。""" +def _attach_dynamic_extraction( + task: ShippingOrderTask, rows: list[dict], po_number: str = 'PO-100', +) -> dict[str, str]: + """建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。 + + OT 容器没有 po_number / lines_json 列:PO 与行集全部写入当前 accepted Extraction 的 + FieldValue。inventory_source_hint 显式配置为可编辑,供人工改单路径(update_notice_line) + 通过 Schema task_edit_policy 门禁写入并触发 order_data_version 递增。 + """ order_schema_service.initialize_schema({'display_name': '对账字段'}, actor_id=None) existing_fields = { item['field_code']: item @@ -76,11 +89,17 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s ) for code, scope, value_type in ( ('po_number', 'header', 'string'), - ('part_number', 'line', 'string'), ('qty', 'line', 'decimal'), ('reservation_id', 'line', 'string'), + ('part_number', 'line', 'string'), + ('qty', 'line', 'decimal'), + ('reservation_id', 'line', 'string'), + ('inventory_source_hint', 'line', 'string'), ) } draft = order_schema_service.create_draft({}, actor_id=None) - purposes = {'part_number': 'part_number', 'qty': 'quantity', 'reservation_id': 'reservation_id'} + purposes = { + 'part_number': 'part_number', 'qty': 'quantity', + 'reservation_id': 'reservation_id', 'inventory_source_hint': 'inventory_source_hint', + } saved = order_schema_service.save_draft(draft['id'], {'fields': [{ 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes.get(code, 'general'), 'required': code != 'reservation_id', @@ -89,6 +108,8 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + # 人工改单路径通过 Schema 策略门禁放行库存源线索编辑,从而可测 409 版本冲突。 + **({'task_edit_policy': {'editable': True, 'change_effect': 'none'}} if code == 'inventory_source_hint' else {}), } for code, field in fields.items()], 'expected_lock_version': draft['lock_version']}, actor_id=None) published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) extraction = ShippingOrderExtraction( @@ -97,21 +118,22 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s db.session.add(extraction) db.session.flush() header_field = fields['po_number'] - header_value = task.po_number header_decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=None, field_id=header_field['id'], - decision_status='accepted' if header_value else 'missing', - supporting_observation_ids_json=[], resolved_value_json=header_value, + decision_status='accepted' if po_number else 'missing', + supporting_observation_ids_json=[], resolved_value_json=po_number or None, ) db.session.add(header_decision) db.session.flush() - if header_value: + if po_number: db.session.add(ShippingOrderFieldValue( extraction_id=extraction.id, line_id=None, field_id=header_field['id'], decision_id=header_decision.id, - value_text=str(header_value), value_json=header_value, + value_text=str(po_number), value_json=po_number, )) for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for code, field in fields.items(): @@ -212,7 +234,7 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app): idempotency_key='resolve-1', ) assert first['idempotent_replay'] is False - task = db.session.get(ShippingNotice, task.id) + task = db.session.get(ShippingOrderTask, task.id) value = ShippingOrderFieldValue.query.filter_by( extraction_id=task.current_order_extraction_id, field_id=field_id, ).one() @@ -222,15 +244,22 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app): assert '"evidence_type":"manual_input"' in event.evidence_ref assert event.reason == '原始订单附件已复核' - replay = resolve_field_conflict( - task=task, - conflict_id=conflict.id, - resolution='take_incoming', - evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'}, - reason='原始订单附件已复核', - idempotency_key='resolve-1', - ) - assert replay['idempotent_replay'] is True + # OT 容器已把 last_conflict_resolve_idempotency_key 从 step_payload 退役(见迁移 + # iw1a2b3c4d5e):已解决冲突再次提交不再回放同键结果,而是以 ALREADY_RESOLVED 拒绝, + # 从而保证重复解决不会二次覆盖/新建重复业务值(幂等安全)。 + try: + resolve_field_conflict( + task=task, + conflict_id=conflict.id, + resolution='take_incoming', + evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'}, + reason='原始订单附件已复核', + idempotency_key='resolve-1', + ) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING.FIELD_CONFLICT_ALREADY_RESOLVED' + else: + raise AssertionError('resolved conflict replay must be rejected as already-resolved') def test_update_notice_line_version_mismatch(app): @@ -241,6 +270,7 @@ def test_update_notice_line_version_mismatch(app): lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], ) db.session.commit() + # 先提交一次可编辑字段,成功写入并 bump order_data_version。 resp = update_notice_line({ **_review_payload(), 'task_id': task.task_no, @@ -248,9 +278,10 @@ def test_update_notice_line_version_mismatch(app): 'patch': {'inventory_source_hint': 'H9'}, 'expected_order_data_version': 1, }) - # replace 已 bump version,再带 1 应失败;先读当前版本再测过期。 - task = db.session.get(ShippingNotice, task.id) + assert resp['status'] == 'ok' + task = db.session.get(ShippingOrderTask, task.id) stale = int(task.order_data_version) - 1 + # 再带过期版本号应失败,返回版本冲突。 resp = update_notice_line({ **_review_payload(), 'task_id': task.task_no, @@ -281,7 +312,7 @@ def test_update_notice_line_rejects_forged_structured_evidence(app): }) assert response['status'] == 'failed' assert response['data']['error_code'] == 'SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID' - assert int(db.session.get(ShippingNotice, task.id).order_data_version) == 1 + assert int(db.session.get(ShippingOrderTask, task.id).order_data_version) == 1 def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app): diff --git a/backend/tests/test_shipping_task_parsed_projection.py b/backend/tests/test_shipping_task_parsed_projection.py index d262eb25..59e065ef 100644 --- a/backend/tests/test_shipping_task_parsed_projection.py +++ b/backend/tests/test_shipping_task_parsed_projection.py @@ -26,6 +26,7 @@ from app.models import ( ShippingInventoryVerificationLine, ShippingReservation, ShippingNotice, + ShippingOrderTask, ShippingUploadAttempt, User, ) @@ -43,7 +44,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): from app.services.shipping_notice import field_asset_service field_asset_service.ensure_standard_assets_seeded() fields = { - code: ShippingOrderField.query.filter_by(field_code=code).one() + code: ShippingOrderField.query.filter_by(field_code=code).order_by(ShippingOrderField.id.asc()).first() for code in ('part_number', 'reservation_id', 'qty', 'inventory_source_hint') } version = ShippingOrderSchemaVersion( @@ -76,18 +77,18 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): db.session.add(candidate) db.session.flush() - task = ShippingNotice( - task_no='SN-PARSED-PROJECTION-001', + lines_data = [{ + 'part_number': 'P123456', + 'qty': 24, + 'reservation_id': '1000140351', + 'inventory_source_hint': 'DBS DUB', + }] + + ot = ShippingOrderTask( + task_no='OT-PARSED-PROJECTION-001', user_id=user.id, - source_type='manual', - po_number='4510038672', - source_candidate_id=int(candidate.id), - lines_json=[{ - 'part_number': 'P123456', - 'qty': 24, - 'reservation_id': '1000140351', - 'inventory_source_hint': 'DBS DUB', - }], + source_type='eml', + candidate_id=int(candidate.id), step_payload_json={ 'parse_validation': { 'status': 'ready', @@ -100,17 +101,25 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): }, }, ) + db.session.add(ot) + db.session.flush() + # 正式 Notice 通过 order_task_id 反查 OT;source_candidate_id 承载来源 Candidate 审计。 + task = ShippingNotice( + task_no='SN-PARSED-PROJECTION-001', + order_task_id=ot.id, + source_candidate_id=int(candidate.id), + ) db.session.add(task) db.session.flush() extraction = ShippingOrderExtraction( - task_id=task.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted', + task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() - for code, value in task.lines_json[0].items(): + for code, value in lines_data[0].items(): decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id, decision_status='accepted', resolved_value_json=value, @@ -122,7 +131,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): decision_id=decision.id, value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=value, )) - task.current_order_extraction_id = extraction.id + ot.current_order_extraction_id = extraction.id db.session.commit() detail = serialize_task_detail(task) @@ -188,10 +197,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app): detail = serialize_task_detail(task) assert detail['inventory_verifications'][0]['lines'] == [{ - 'reservation_id': reservation.id, 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available', + 'reservation_id': 'RES-TIMELINE-001', 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available', }] assert detail['export_artifacts'][0]['artifact_no'] == artifact.artifact_no - assert detail['export_artifacts'][0]['reservation_ids'] == [reservation.id] + # 关键断言:Artifact 的 reservation_ids 投影为字符串 reservation_id,而非 DB 行 id。 + assert detail['export_artifacts'][0]['reservation_ids'] == ['RES-TIMELINE-001'] assert detail['upload_attempts'][0]['callback_id'] == 'timeline-callback' assert detail['upload_attempts'][0]['freight_ref_no'] == 'FREIGHT-001' @@ -199,7 +209,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app): def test_serialize_task_detail_projects_frozen_snapshot_marker(app): """关键断言:工作台必须知道订单已冻结,避免错误展示再次冻结入口。""" with app.app_context(): - task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_snapshot_id=42) + user = User(username='frozen-marker-user', email='frozen-marker@example.com', password_hash='x') + db.session.add(user); db.session.flush() + task_owner = ShippingOrderTask(task_no='OT-FROZEN-MARKER-001', user_id=user.id, order_snapshot_id=42) + db.session.add(task_owner); db.session.flush() + task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_task_id=task_owner.id) db.session.add(task) db.session.commit() diff --git a/backend/tests/test_shipping_task_supersession.py b/backend/tests/test_shipping_task_supersession.py index ae3438db..d21d86c5 100644 --- a/backend/tests/test_shipping_task_supersession.py +++ b/backend/tests/test_shipping_task_supersession.py @@ -6,18 +6,22 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingFreightCancellation, ShippingNotice, User +from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, User from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked, establish_task_supersession def _tasks(*, uploaded: bool) -> tuple[ShippingNotice, ShippingNotice, User]: user = User(username=f'supersession-{uploaded}', email=f'supersession-{uploaded}@example.test', password_hash='x') - old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None) - db.session.add_all([user, old]); db.session.flush() - old.user_id = user.id - new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id) - db.session.add(new); db.session.commit() + db.session.add(user); db.session.flush() + old_ot = ShippingOrderTask(task_no=f'OT-SUP-OLD-{uploaded}', user_id=user.id) + new_ot = ShippingOrderTask(task_no=f'OT-SUP-NEW-{uploaded}', user_id=user.id) + db.session.add_all([old_ot, new_ot]); db.session.flush() + old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=user.id, order_task_id=old_ot.id) + new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, order_task_id=new_ot.id) + db.session.add_all([old, new]); db.session.flush() + new.supersedes_task_id = old.id + db.session.commit() return old, new, user @@ -30,13 +34,18 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app): assert new.lifecycle_status == 'active' -def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app): +def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app, monkeypatch): """关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。""" with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + lambda _task: True, + ) old, new, user = _tasks(uploaded=True) establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend') row = ShippingFreightCancellation.query.one() - assert new.lifecycle_status == 'blocked' + assert new.lifecycle_status == 'active' + assert db.session.get(ShippingOrderTask, new.order_task_id).status == 'blocked' with pytest.raises(ConflictError): assert_task_not_supersession_blocked(new) complete_freight_cancellation( diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 95a495fd..c45a9192 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -14,7 +14,7 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, ShippingExcelTemplate, ShippingInventoryParsingProfile, - ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingNotice, + ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, ShippingReservation, ShippingNotice, ShippingUploadAttempt, ) from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success @@ -27,15 +27,17 @@ from app.services.shipping_notice.state_machine import resolve_task_ui_state def _ready_artifact() -> tuple[ShippingNotice, ShippingExportArtifact, ShippingReservation]: - """建立 Attempt 服务需要的最小 ready Artifact 与已占用预约单。""" - task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT') + """建立 OT 关联的 Notice、ready Artifact 与已占用预约单。""" + order_task = ShippingOrderTask(task_no='OT-UPLOAD-ATTEMPT', source_type='direct_pdf', user_id=1) + task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT', order_task_id=None) template = ShippingExcelTemplate( template_code='ATTEMPT', display_name='Attempt', version=1, status='published', storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64, definition_json={}, ) profile = ShippingInventoryParsingProfile(profile_code='ATTEMPT', display_name='Attempt', version=1, status='published', file_format='xlsx', definition_json={}) schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') - db.session.add_all([task, template, profile, schema]); db.session.flush() + db.session.add_all([order_task, task, template, profile, schema]); db.session.flush() + task.order_task_id = order_task.id version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) db.session.add(version); db.session.flush() extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted') @@ -68,7 +70,7 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app): assert ShippingUploadAttempt.query.count() == 1 assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' - # 三层成功事实齐全后,才允许任务进入业务「通知完成」。 + # 当前 Artifact 上传成功且有对应 Attempt 审计后,任务进入业务「通知完成」。 assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True with pytest.raises(ConflictError): start_rpa_attempt(task, artifact_id=artifact.id) @@ -172,12 +174,13 @@ def test_upload_success_updates_only_its_notice(app): complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2') - assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded' - assert db.session.get(ShippingNotice, other.id).upload_status is None + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True + assert has_verified_upload_success(other) is False -def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): - """历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。""" +def test_legacy_uploaded_field_without_uploaded_artifact_is_not_verified_success(app): + """旧 Notice 上传投影不能替代当前 Excel Artifact 的成功事实。""" with app.app_context(): task, _artifact, _reservation = _ready_artifact() task.upload_status = 'uploaded' @@ -186,6 +189,17 @@ def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): assert has_verified_upload_success(task) is False +def test_uploaded_artifact_without_attempt_is_verified_success(app): + """当前 Excel 已上传时,不要求补造成功 Attempt 才能完成 Notice。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + artifact.status = 'uploaded' + db.session.flush() + + assert ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() == 0 + assert has_verified_upload_success(task) is True + + def test_archived_upload_success_is_not_counted_as_completed(app): """归档任务保留上传审计,但不能再计入当前通知完成统计。""" with app.app_context(): @@ -265,12 +279,10 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app): task, artifact, reservation = _ready_artifact() attempt = start_rpa_attempt(task, artifact_id=artifact.id) mark_attempt_result_unknown(attempt) - task.pending_human_reason = 'upload_result_unknown' - task.upload_status = 'unknown' state = resolve_task_ui_state(task) - assert state.checkpoint == 'upload_result_unknown' - # checkpoint 仅描述内部流程;下载与人工凭据登记必须由 Gate/Artifact 下发。 + # 无 Gate 时薄回退不从 upload attempt 投影位置;动作由 Gate/Artifact 下发。 + assert state.position is None assert not hasattr(state, 'human_options') assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' diff --git a/backend/tests/test_shipping_upload_unknown_state.py b/backend/tests/test_shipping_upload_unknown_state.py index f95a896c..4f8a6ed8 100644 --- a/backend/tests/test_shipping_upload_unknown_state.py +++ b/backend/tests/test_shipping_upload_unknown_state.py @@ -53,9 +53,14 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app): task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual') db.session.add(task) db.session.flush() + # 冻结的逐源 Attempt 须携带完整 v2 身份(lease_token / candidate_set / execution / gate), + # 否则回调会先在 _validate_callback_attempt_identity 被 identity_mismatch 拒绝, + # 无法走到失败分支去写 callback_id。 first = ShippingTaskInventoryRpaAttempt( task_no=task.task_no, source_code='SRC-A', attempt_no=1, source_run_no='PSR-FIRST', status='failed', callback_id=None, + lease_token='lease-first', + extra_json={'candidate_set_id': 1, 'execution_id': 1, 'gate_id': 1}, ) second = ShippingTaskInventoryRpaAttempt( task_no='SN-CB-ID-OTHER', source_code='SRC-B', attempt_no=1, @@ -64,23 +69,43 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app): db.session.add_all([first, second]) db.session.flush() + def _payload(run_no: str, source_code: str, attempt_no: int) -> dict: + """构造完整 v2 身份围栏的回调 payload。 + + 与 _validate_callback_attempt_identity 的 required 字段一一对应, + 使失败回调(error_code)能通过身份校验并回写 callback_id。 + """ + return { + 'schema_version': 'shipping_inventory_rpa.v2', + 'callback_id': 'cb-unique', + 'task_no': task.task_no, + 'source_code': source_code, + 'source_run_no': run_no, + 'attempt_no': attempt_no, + 'lease_token': 'lease-first', + 'candidate_set_id': 1, + 'execution_id': 1, + 'gate_id': 1, + 'error_code': 'RPA_TIMEOUT', + } + result, handled = per_source_callback_handler( task, source_code='SRC-A', run_no='PSR-FIRST', - callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + callback_payload=_payload('PSR-FIRST', 'SRC-A', 1), ) assert result == 'failed' assert handled.id == first.id result, handled = per_source_callback_handler( task, source_code='SRC-A', run_no='PSR-FIRST', - callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + callback_payload=_payload('PSR-FIRST', 'SRC-A', 1), ) assert result == 'idempotent_ok' assert handled.id == first.id result, handled = per_source_callback_handler( task, source_code='SRC-B', run_no='PSR-SECOND', - callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + callback_payload=_payload('PSR-SECOND', 'SRC-B', 1), ) assert result == 'callback_conflict' assert handled.id == first.id diff --git a/backend/tests/test_shipping_uploaded_gate_closure.py b/backend/tests/test_shipping_uploaded_gate_closure.py index d3b8deaa..96991430 100644 --- a/backend/tests/test_shipping_uploaded_gate_closure.py +++ b/backend/tests/test_shipping_uploaded_gate_closure.py @@ -13,12 +13,12 @@ tests/test_shipping_uploaded_gate_closure.py from __future__ import annotations from app import db -from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate +from app.models import ShippingNotice, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, User from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version -def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution: +def _mk_execution(task: ShippingOrderTask) -> ShippingProcessExecution: """建正式 20-Gate Execution,并把 inventory_sufficiency 置为人工阻断,让任务停留在「通知准备」。""" execution = ensure_execution_for_workflow_version(task_id=int(task.id)) task.active_process_execution_id = int(execution.id) @@ -33,12 +33,18 @@ def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution: return execution -def test_step1a_closes_all_gates_when_uploaded(app): +def test_step1a_closes_all_gates_when_uploaded(app, monkeypatch): """upload_status=uploaded → STEP 1A 收口全部前置 Gate,Execution 落到 completed。""" - task = ShippingNotice(task_no='SN-UPLOADED-GATE', upload_status='uploaded', match_status='fulfillable') + user = User(username='uploaded-gate-user', email='uploaded-gate@example.com', password_hash='x') + db.session.add(user); db.session.flush() + task = ShippingOrderTask(task_no='OT-UPLOADED-GATE', user_id=user.id) db.session.add(task) db.session.flush() execution = _mk_execution(task) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status', + lambda _task: 'uploaded', + ) sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1) db.session.commit() @@ -53,17 +59,18 @@ def test_step1a_closes_all_gates_when_uploaded(app): assert execution.status == 'completed' -def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app): +def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app, monkeypatch): """上传已成功时,历史 upload_rpa_pending 不得将正式 Gate 重新投影为阻断。""" - task = ShippingNotice( - task_no='SN-UPLOADED-STALE-PENDING', - upload_status='uploaded', - pending_human_reason='upload_rpa_pending', - match_status='fulfillable', - ) + user = User(username='uploaded-stale-user', email='uploaded-stale@example.com', password_hash='x') + db.session.add(user); db.session.flush() + task = ShippingOrderTask(task_no='OT-UPLOADED-STALE-PENDING', user_id=user.id, pending_human_reason='upload_rpa_pending') db.session.add(task) db.session.flush() execution = _mk_execution(task) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status', + lambda _task: 'uploaded', + ) sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1) db.session.commit() @@ -75,7 +82,9 @@ def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app): def test_missing_upload_status_keeps_gate_stuck(app): """upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。""" - task = ShippingNotice(task_no='SN-UPLOAD-NOT-SET', upload_status='partial', match_status='fulfillable') + user = User(username='upload-not-set-user', email='upload-not-set@example.com', password_hash='x') + db.session.add(user); db.session.flush() + task = ShippingOrderTask(task_no='OT-UPLOAD-NOT-SET', user_id=user.id) db.session.add(task) db.session.flush() execution = _mk_execution(task) diff --git a/backend/tests/test_shipping_wave_rerouting.py b/backend/tests/test_shipping_wave_rerouting.py new file mode 100644 index 00000000..4edc0aa5 --- /dev/null +++ b/backend/tests/test_shipping_wave_rerouting.py @@ -0,0 +1,156 @@ +""" +tests/test_shipping_wave_rerouting.py + +用途:锁定 D8——履约波次(post_ot_fulfillment_wave)不再继承首通知任务级库存源字段, + 改为按自身行重跑路由冻结(freeze_wave_notice_routing)。 +依赖:post_ot_fulfillment_wave_service / inventory_candidate_freeze_service。 +逻辑:波次经 create_shipping_notice_after_inventory_gate 建单,不得携带 inventory_source_* / + routing_fingerprint / snapshot_id;freeze_wave_notice_routing 按波次行评估并冻结候选集。 +""" + +from __future__ import annotations + +import ast +import inspect + + +def test_wave_constructor_not_inherit_source_fields_and_reroutes(): + """[断言] 波次经 create_shipping_notice_after_inventory_gate 建单不继承首通知源字段,并在建波次后调用 freeze_wave_notice_routing。""" + from app.services.shipping_notice import ( + inventory_candidate_freeze_service as freeze_svc, + post_ot_fulfillment_wave_service as svc, + ) + + fn_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0] + assert isinstance(fn_node, ast.FunctionDef) + + # [断言 1] create_shipping_notice_after_inventory_gate 调用时无 inventory_source_* / fingerprint / snapshot_id 继承字段。 + source_kwargs: set[str] = set() + notice_calls = [ + node for node in ast.walk(fn_node) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'create_shipping_notice_after_inventory_gate' + ] + assert notice_calls, 'create_post_ot_fulfillment_wave 必须调用 create_shipping_notice_after_inventory_gate' + for call in notice_calls: + for kw in call.keywords: + if kw.arg is not None: + source_kwargs.add(str(kw.arg)) + inherited = source_kwargs & { + 'inventory_source_code', 'inventory_warehouse_id', + 'inventory_source_status', 'inventory_source_method', 'inventory_source_config_version', + 'inventory_routing_fingerprint', 'inventory_snapshot_id', + } + assert not inherited, f"波次不得继承首通知源字段: {sorted(inherited)}" + + # [断言 2] 建波次后必须调用 freeze_wave_notice_routing(按自身行重跑路由冻结)。 + freeze_calls = [ + node for node in ast.walk(fn_node) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'freeze_wave_notice_routing' + ] + assert freeze_calls, 'create_post_ot_fulfillment_wave 必须调用 freeze_wave_notice_routing' + assert hasattr(freeze_svc, 'freeze_wave_notice_routing') + + +def test_freeze_wave_notice_routing_routs_by_own_lines(app, monkeypatch): + """[断言] freeze_wave_notice_routing 按波次自身行评估候选,并以并集作为任务级候选集冻结。""" + from types import SimpleNamespace + + from app import db + from app.models import ShippingNotice, ShippingNoticeLine + from app.services.shipping_notice import inventory_candidate_freeze_service as svc + + src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None) + notice = ShippingNotice( + task_no='SN-WAVE-T6', source_type='post_ot_fulfillment_wave', + ) + db.session.add(notice) + db.session.flush() + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1, + part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1', 'f2': 'v2'}, + )) + db.session.commit() + + monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, [])) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values', + lambda **_kw: SimpleNamespace( + source_codes=['DSV360_AWSBI_BYAWSFRA01'], status='resolved', matched_rules=(), matched_rule_ids=[1], + ), + ) + monkeypatch.setattr( + svc, 'get_database_inventory_source', + lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa', + 'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None}, + ) + captured = {} + monkeypatch.setattr( + svc, 'freeze_candidates_for_task', + lambda task, *, adjudication=None, line_projections=None, **kw: captured.update( + {'task': task, 'adjudication': adjudication, 'line_projections': line_projections} + ) or svc.CandidateFreezeResult( + candidate_set_id=1, created_new=True, + source_codes=[c['source_code'] for c in adjudication.candidates], + line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1, + ), + ) + + svc.freeze_wave_notice_routing(notice, source_notice=src_notice) + + assert captured['task'] is notice + assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSBI_BYAWSFRA01'] + assert captured['adjudication'].status == 'candidates_frozen' + assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSBI_BYAWSFRA01'] + + +def test_freeze_wave_notice_routing_falls_back_to_task_candidates(app, monkeypatch): + """[断言] 波次行无规则命中时回退到订单级 task 候选集(与首单行为一致)。""" + from types import SimpleNamespace + + from app import db + from app.models import ShippingNotice, ShippingNoticeLine + from app.services.shipping_notice import inventory_candidate_freeze_service as svc + + src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None) + notice = ShippingNotice( + task_no='SN-WAVE-FB', source_type='post_ot_fulfillment_wave', + ) + db.session.add(notice) + db.session.flush() + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1, + part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1'}, + )) + db.session.commit() + + monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, [])) + + def _eval(**kw): + # task 级命中单源;行级规则不命中(unresolved)→ 应回退到 task 候选集。 + if kw.get('scope') == 'task': + return SimpleNamespace(status='resolved', source_codes=['DSV360_AWSDU'], matched_rules=(), matched_rule_ids=[1]) + return SimpleNamespace(status='unresolved', source_codes=[], matched_rules=(), matched_rule_ids=[]) + + monkeypatch.setattr('app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values', _eval) + monkeypatch.setattr( + svc, 'get_database_inventory_source', + lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa', + 'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None}, + ) + captured = {} + monkeypatch.setattr( + svc, 'freeze_candidates_for_task', + lambda task, *, adjudication=None, line_projections=None, **kw: captured.update( + {'adjudication': adjudication, 'line_projections': line_projections} + ) or svc.CandidateFreezeResult( + candidate_set_id=1, created_new=True, + source_codes=[c['source_code'] for c in adjudication.candidates], + line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1, + ), + ) + + svc.freeze_wave_notice_routing(notice, source_notice=src_notice) + + assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] + assert captured['line_projections'][0]['selection_mode'] == 'task_fallback' + assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSDU'] diff --git a/backend/tests/test_shipping_workbench_service_chains.py b/backend/tests/test_shipping_workbench_service_chains.py index 467d4cc4..ecd8b47b 100644 --- a/backend/tests/test_shipping_workbench_service_chains.py +++ b/backend/tests/test_shipping_workbench_service_chains.py @@ -31,7 +31,6 @@ def workbench_chain_ids(app): user_id=user.id, conversation_id=session.session_id, source_type='manual', - current_step='step3_confirm_customer', ) db.session.add(notice) db.session.flush() @@ -40,7 +39,6 @@ def workbench_chain_ids(app): user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), status='processing', stage='waiting_review', progress_version=1, diff --git a/backend/tests/test_shipping_workflow_recovery.py b/backend/tests/test_shipping_workflow_recovery.py index 3e75ce0b..efb2bf08 100644 --- a/backend/tests/test_shipping_workflow_recovery.py +++ b/backend/tests/test_shipping_workflow_recovery.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_workflow_recovery.py -用途:验收订单抽取 Job 超时回收后 WorkflowItem 从 layout_parsing/extracting 迁出。 -依赖:app fixture、_seed_run_input、workflow_ledger、sync_workflow_items_after_extraction_job_recovery。 -逻辑:模拟 Job queued/failed 回收,断言 Item 分别进入 queued / failed,不依赖完整 recover_stale_jobs。 +用途:验收订单抽取 Job 超时回收后 WorkflowItem 同步契约(co8 账本已下线,恒为无操作)。 +依赖:app fixture、_seed_run_input、sync_workflow_items_after_extraction_job_recovery、ensure_workflow_items_for_run。 +逻辑:模拟 Job queued/failed 回收,断言 WorkflowItem 相关同步恒为 0 / 空列表,进度以 Run/OrderTask 投影为准。 """ from __future__ import annotations @@ -17,15 +17,11 @@ from app.services.shipping_notice.order_extraction_run_service import ( ensure_workflow_items_for_run, sync_workflow_items_after_extraction_job_recovery, ) -from app.services.shipping_notice.workflow_ledger_service import ( - ensure_workflow_item_for_document, - transition_item_status, -) from tests.test_shipping_order_extraction_runs import _seed_run_input def test_sync_workflow_items_after_extraction_recovery_to_queued(app): - """Job 回收为 queued 时,layout_parsing/extracting Item 回到 queued。""" + """co8 后台账已 DROP:Job 回收为 queued 时 WorkflowItem 同步为无操作(恒 0)。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='WFR-Q') with patch( @@ -38,32 +34,18 @@ def test_sync_workflow_items_after_extraction_recovery_to_queued(app): conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - item = ensure_workflow_item_for_document( - conversation_id=session.session_id, - owner_user_id=int(user.id), - document_id=int(document.id), - run=run, - ) - transition_item_status( - item=item, - lifecycle_status='extracting', - actor_type='system', - actor_id='test', - ) db.session.commit() job = SimpleNamespace(status='queued', business_ref=run.run_no, id=1) updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job) db.session.commit() - # 关键断言:卡住的抽取态被回收为可重试 queued。 - assert updated == 1 - db.session.refresh(item) - assert item.lifecycle_status == 'queued' + # 关键断言:账本已下线,无 WorkflowItem 可回收,同步恒为 0(状态以 Run/OrderTask 投影为准)。 + assert updated == 0 def test_sync_workflow_items_after_extraction_recovery_to_failed(app): - """Job 回收为 failed 时,layout_parsing Item 进入 failed。""" + """co8 后台账已 DROP:ensure_workflow_items_for_run 不再物化 WorkflowItem。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='WFR-F') with patch( @@ -77,21 +59,13 @@ def test_sync_workflow_items_after_extraction_recovery_to_failed(app): intake_nos=[intake.intake_no], ) items = ensure_workflow_items_for_run(run, stage_when_ready='queued') - assert items - item = items[0] - transition_item_status( - item=item, - lifecycle_status='layout_parsing', - actor_type='system', - actor_id='test', - ) + # 关键断言:账本已下线,不再为 Run 物化 WorkflowItem,恒返回空列表。 + assert items == [] db.session.commit() job = SimpleNamespace(status='failed', business_ref=run.run_no, id=2) updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job) db.session.commit() - # 关键断言:终态失败回收把 Item 标 failed。 - assert updated == 1 - db.session.refresh(item) - assert item.lifecycle_status == 'failed' + # 关键断言:终态失败回收同样不再改动 WorkflowItem,同步恒为 0。 + assert updated == 0 diff --git a/backend/tests/test_shipping_xfa_formal_extraction_route.py b/backend/tests/test_shipping_xfa_formal_extraction_route.py index f4a6ded0..7770f9c2 100644 --- a/backend/tests/test_shipping_xfa_formal_extraction_route.py +++ b/backend/tests/test_shipping_xfa_formal_extraction_route.py @@ -85,7 +85,6 @@ def test_datasets_blind_cross_check_reports_shared_ocr_mismatch(): def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch): """关键断言:跨模板 overlap 先走共同 matcher,datasets 只能追加末端身份冲突。""" - from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice import order_document_profile_validation_service as validation_service from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset @@ -100,9 +99,9 @@ def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_co ), ) monkeypatch.setattr( - profile_service, - 'published_snapshots_for_schema', - lambda _schema_id: [{ + validation_service, + 'published_rival_snapshots_for_overlap', + lambda _profile: [{ 'profile_code': 'XFA-OTHER', 'version': 3, 'checksum': 'other', 'definition': {'source_contract': { 'template_packet_checksum': 'template', @@ -135,6 +134,41 @@ def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_co assert snapshot['conflict_profiles'][1]['reason_codes'] == ['value_source_exact_identity_conflict'] +def test_datasets_overlap_skips_same_profile_code_identity_rival(monkeypatch): + """datasets 身份冲突也不得拿同模板族旧版跟自己比。""" + from app.services.shipping_notice import order_document_profile_validation_service as validation_service + from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset + + monkeypatch.setattr( + validation_service, + '_build_coordinate_overlap_evidence', + lambda **_kwargs: ('passed', {'false_hit_other_count': 0}, {'conflict_profiles': []}), + ) + monkeypatch.setattr( + validation_service, + 'published_rival_snapshots_for_overlap', + lambda _profile: [], + ) + profile = SimpleNamespace( + profile_code='XFA-CURRENT', version=2, schema_version_id=9, + definition_json={'source_contract': { + 'template_packet_checksum': 'template', + 'dataset_structure_fingerprint': 'structure', + }}, + ) + + status, summary, snapshot = xfa_dataset.build_overlap_evidence( + profile=profile, + signature_run=SimpleNamespace(id=1), + training_samples=[], + blind_samples=[], + ) + + assert status == 'passed' + assert summary['value_source_identity_conflict_count'] == 0 + assert snapshot['conflict_profiles'] == [] + + def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypatch): """XFA overlap 解析门禁必须消费 datasets 抽取结果,不能误用坐标字段覆盖。""" from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset diff --git a/backend/tests/voucher_check/test_dms_archive.py b/backend/tests/voucher_check/test_dms_archive.py new file mode 100644 index 00000000..be40dd90 --- /dev/null +++ b/backend/tests/voucher_check/test_dms_archive.py @@ -0,0 +1,186 @@ +""" +backend/tests/voucher_check/test_dms_archive.py + +用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。 +依赖:pytest;不连文档库。 +逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。 +""" + +from __future__ import annotations + +from datetime import date + +import pytest + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.base import ScannedFile +from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter +from app.services.voucher_check.dms_client import ( + SalesDmsClient, + _extract_item_id, + _is_name_conflict, +) + + +def test_extract_item_id_from_nested_data(): + assert _extract_item_id({"Data": {"ID": "folder-1"}}) == "folder-1" + assert _extract_item_id({"Data": "folder-2"}) == "folder-2" + assert _extract_item_id({"Data": {"Item": {"ID": "folder-3"}}}) == "folder-3" + assert _extract_item_id({"Data": {}}) == "" + + +def test_name_conflict_detects_same_name_messages(): + assert _is_name_conflict("文件夹已存在") + assert _is_name_conflict("同名文件") + assert _is_name_conflict("The name already exists") + assert _is_name_conflict("网络超时") is False + + +def test_ensure_folder_returns_existing_without_save(monkeypatch): + monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: "folder-1") + calls: list[object] = [] + monkeypatch.setattr(SalesDmsClient, "_post_json", lambda *_args, **_kwargs: calls.append(1) or {}) + assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "folder-1" + assert calls == [] + + +def test_ensure_folder_creates_when_missing(monkeypatch): + monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: None) + monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1") + monkeypatch.setattr( + SalesDmsClient, + "_post_json", + lambda path, payload, **_kwargs: {"Code": 0, "Data": {"ID": "new-folder"}}, + ) + assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder" + + +def test_copy_skips_when_dest_has_same_name(monkeypatch): + monkeypatch.setattr( + SalesDmsClient, + "find_child_file", + lambda **_kwargs: {"ID": "dest-1", "LeafName": "INV001.pdf"}, + ) + calls: list[object] = [] + monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs)) + row, skipped = SalesDmsClient.copy_file_skip_same_name( + source_item_id="src-1", + dest_folder_id="inv-folder", + leaf_name="INV001.pdf", + ) + assert skipped is True + assert row["ID"] == "dest-1" + assert calls == [] + + +def test_copy_when_dest_has_no_same_name(monkeypatch): + listing = {"n": 0} + + def find_child_file(**_kwargs): + listing["n"] += 1 + if listing["n"] == 1: + return None + return {"ID": "dest-2", "LeafName": "INV001.pdf"} + + monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file) + copied: list[dict] = [] + monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0}) + row, skipped = SalesDmsClient.copy_file_skip_same_name( + source_item_id="src-1", + dest_folder_id="inv-folder", + leaf_name="INV001.pdf", + ) + assert skipped is False + assert row["ID"] == "dest-2" + assert copied == [{"item_ids": ["src-1"], "dest_folder_id": "inv-folder"}] + + +def test_copy_treats_api_same_name_error_as_skip(monkeypatch): + listing = {"n": 0} + + def find_child_file(**_kwargs): + listing["n"] += 1 + if listing["n"] == 1: + return None + return {"ID": "dest-3", "LeafName": "INV001.pdf"} + + monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file) + monkeypatch.setattr( + SalesDmsClient, + "copy_items", + lambda **_kwargs: (_ for _ in ()).throw( + ServiceUnavailableError("目标已存在同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED") + ), + ) + row, skipped = SalesDmsClient.copy_file_skip_same_name( + source_item_id="src-1", + dest_folder_id="inv-folder", + leaf_name="INV001.pdf", + ) + assert skipped is True + assert row["ID"] == "dest-3" + + +def test_archive_adapter_is_wired_and_skips_same_name(monkeypatch): + monkeypatch.setattr(SalesDmsClient, "ensure_month_archive_root", lambda **_kwargs: "archive-root") + monkeypatch.setattr(SalesDmsClient, "ensure_folder", lambda **_kwargs: "inv-folder") + monkeypatch.setattr( + SalesDmsClient, + "copy_file_skip_same_name", + lambda **_kwargs: ({"ID": "dest-9", "LeafName": "INV001-PO9.pdf"}, True), + ) + adapter = DmsArchiveAdapter() + assert adapter.wired is True + archived = adapter.archive( + period_month=date(2026, 8, 1), + invoice_no="INV001", + file=ScannedFile(filename="INV001-PO9.pdf", item_id="src-9", fingerprint="fp1"), + rule={"code": "po_order"}, + ) + assert archived.item_id == "dest-9" + assert archived.folder_id == "inv-folder" + assert archived.extra["skipped_same_name"] is True + assert archived.path == "销售开票附件/2026/08/所有归档/INV001/INV001-PO9.pdf" + + +def test_archive_adapter_missing_source_id_is_technical(): + adapter = DmsArchiveAdapter() + with pytest.raises(ServiceUnavailableError) as exc: + adapter.archive( + period_month=date(2026, 8, 1), + invoice_no="INV001", + file=ScannedFile(filename="INV001.pdf"), + rule={"code": "tax_invoice"}, + ) + assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED" + + +def test_month_archive_root_missing_month_is_technical(monkeypatch): + monkeypatch.setattr(SalesDmsClient, "resolve_period_folder", lambda **_kwargs: (None, None)) + with pytest.raises(ServiceUnavailableError) as exc: + SalesDmsClient.ensure_month_archive_root(period_month=date(2026, 8, 1)) + assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED" + + +def test_page_walks_until_short_batch(monkeypatch): + """「所有归档」超过一页时必须翻页,否则同名跳过会漏检已有发票目录。""" + calls = {"n": 0} + + def post(_path, payload, **_kwargs): + calls["n"] += 1 + index = payload["Page"]["Index"] + if index == 1: + return { + "Code": 0, + "Data": {"Items": [{"ID": "a", "IsFolder": True, "LeafName": "x"}] * 200, "Total": 201}, + } + return { + "Code": 0, + "Data": {"Items": [{"ID": "b", "IsFolder": True, "LeafName": "y"}], "Total": 201}, + } + + monkeypatch.setattr(SalesDmsClient, "_post_json", post) + monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1") + rows = SalesDmsClient.page(parent_folder_id="archive-root") + assert len(rows) == 201 + assert calls["n"] == 2 diff --git a/backend/tests/voucher_check/test_engine_profile_and_scan.py b/backend/tests/voucher_check/test_engine_profile_and_scan.py new file mode 100644 index 00000000..1a40fcf8 --- /dev/null +++ b/backend/tests/voucher_check/test_engine_profile_and_scan.py @@ -0,0 +1,127 @@ +""" +backend/tests/voucher_check/test_engine_profile_and_scan.py + +用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。 +依赖:pytest;不连 Oracle / 文档库。 +逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from zoneinfo import ZoneInfo + +import pytest + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter +from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter +from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter +from app.services.voucher_check.aggregator import aggregate_file_results +from app.services.voucher_check.erp_repository import previous_period_bounds +from app.services.voucher_check.filename_match import first_match, match_filename +from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules + + +def test_previous_period_bounds_from_early_september(): + """周二跑批时检核上个月;2026-09-01 应得到 2026-08。""" + now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai")) + period_month, current_month, period_start, next_start = previous_period_bounds(now) + assert period_month.isoformat() == "2026-08-01" + assert current_month.isoformat() == "2026-09-01" + assert period_start.isoformat().startswith("2026-08-01T00:00:00") + assert next_start.isoformat().startswith("2026-09-01T00:00:00") + + +def test_previous_period_bounds_january_cross_year(): + now = datetime(2026, 1, 6, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai")) + period_month, current_month, _, _ = previous_period_bounds(now) + assert period_month.isoformat() == "2025-12-01" + assert current_month.isoformat() == "2026-01-01" + + +def test_filename_templates_match_sales_rules(): + assert match_filename("INV001-PO9.pdf", template="{invoice}-{order_no}.pdf", invoice_no="INV001") + assert match_filename("INV001.pdf", template="{invoice}.pdf", invoice_no="INV001") + assert match_filename("INV001-DN8.pdf", template="{invoice}-{delivery_no}.pdf", invoice_no="INV001") + assert match_filename("INV001-TAX1.pdf", template="{invoice}-{tax_invoice_no}.pdf", invoice_no="INV001") + assert match_filename("INV001-CD2.pdf", template="{invoice}-{customs_no}.pdf", invoice_no="INV001") + assert match_filename("INV001-提单.pdf", template="{invoice}-提单.pdf", invoice_no="INV001") + assert match_filename("INV002.pdf", template="{invoice}.pdf", invoice_no="INV001") is None + assert first_match(["other.pdf", "INV001-提单.pdf"], template="{invoice}-提单.pdf", invoice_no="INV001") + + +def test_aggregator_dual_missing_metrics(): + """同一 invoice 缺两类文件:缺件文件=2,缺件 invoice=1。""" + rules = required_file_rules(SALES_PROFILE) + results = [ + {"invoice_no": "A", "rule_code": "po_order", "status": "missing"}, + {"invoice_no": "A", "rule_code": "customs_pack", "status": "missing"}, + {"invoice_no": "A", "rule_code": "sales_release", "status": "staged"}, + {"invoice_no": "A", "rule_code": "tax_invoice", "status": "archived"}, + {"invoice_no": "A", "rule_code": "customs_declaration", "status": "archived"}, + {"invoice_no": "A", "rule_code": "bill_of_lading", "status": "archived"}, + {"invoice_no": "B", "rule_code": "po_order", "status": "archived"}, + {"invoice_no": "B", "rule_code": "customs_pack", "status": "archived"}, + {"invoice_no": "B", "rule_code": "sales_release", "status": "archived"}, + {"invoice_no": "B", "rule_code": "tax_invoice", "status": "archived"}, + {"invoice_no": "B", "rule_code": "customs_declaration", "status": "archived"}, + {"invoice_no": "B", "rule_code": "bill_of_lading", "status": "archived"}, + ] + stats = aggregate_file_results(results, rules=rules) + assert stats["missing_file_count"] == 2 + assert stats["missing_invoice_count"] == 1 + by_invoice = {row["invoice_no"]: row for row in stats["excel_rows"]} + assert by_invoice["A"]["status"] == "缺件" + assert by_invoice["B"]["status"] == "完整" + assert by_invoice["A"]["cells"]["po_order"] == "缺件" + assert by_invoice["A"]["cells"]["sales_release"] == "未检核" + assert by_invoice["B"]["cells"]["po_order"] == "有" + assert stats["by_file_type"]["po_order"]["missing_file_count"] == 1 + assert stats["by_file_type"]["po_order"]["missing_invoice_count"] == 1 + assert stats["by_file_type"]["tax_invoice"]["missing_file_count"] == 0 + + +def test_po_and_oa_adapters_are_placeholders(): + with pytest.raises(ServiceUnavailableError) as po_exc: + ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[]) + assert po_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED" + with pytest.raises(ServiceUnavailableError) as oa_exc: + OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[]) + assert oa_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED" + assert ErpPoPrintAdapter.wired is False + assert OaSalesReleaseAdapter.wired is False + + +def test_directory_scan_matches_cached_listing(monkeypatch): + adapter = DmsDirectoryScanAdapter() + monkeypatch.setattr( + "app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.resolve_period_folder", + lambda **kwargs: ("year-id", "month-id"), + ) + monkeypatch.setattr( + "app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.find_child_folder", + lambda **kwargs: "type-id", + ) + monkeypatch.setattr( + "app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.list_files", + lambda **kwargs: [ + {"LeafName": "INV001-PO9.pdf", "ID": "item-1", "IsFolder": False, "Path": "销售开票附件/2026/08/PO订单/INV001-PO9.pdf", "VersionID": "v1"}, + {"LeafName": "OTHER.pdf", "ID": "item-2", "IsFolder": False}, + ], + ) + hit = adapter.scan( + period_month=date(2026, 8, 1), + invoice_no="INV001", + rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"}, + ) + assert hit.status == "matched" + assert hit.file is not None + assert hit.file.filename == "INV001-PO9.pdf" + + missed = adapter.scan( + period_month=date(2026, 8, 1), + invoice_no="INV999", + rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"}, + ) + assert missed.status == "missing" diff --git a/backend/tests/voucher_check/test_erp_settings.py b/backend/tests/voucher_check/test_erp_settings.py new file mode 100644 index 00000000..ead9c5d1 --- /dev/null +++ b/backend/tests/voucher_check/test_erp_settings.py @@ -0,0 +1,29 @@ +""" +backend/tests/voucher_check/test_erp_settings.py + +用途:立账凭证 ERP 凭据回退到通用 ERP_* / 合同付款同一套只读账号。 +依赖:voucher_check.config._erp_settings、Flask app。 +逻辑:清空 VOUCHER_CHECK_ERP_USERNAME 后仍能从 CONTRACT_PAYMENT_ERP_* 读到账号。 +""" + +from __future__ import annotations + +from app.services.voucher_check.config import _erp_settings + + +def test_erp_settings_falls_back_to_contract_payment_credentials(app): + """未单独配 VOUCHER_CHECK_ERP_USERNAME 时,应复用合同付款已有的只读账号。""" + with app.app_context(): + app.config["VOUCHER_CHECK_ERP_DSN"] = "" + app.config["VOUCHER_CHECK_ERP_USERNAME"] = "" + app.config["VOUCHER_CHECK_ERP_PASSWORD"] = "" + app.config["ERP_DB_DSN"] = "192.168.8.24:1521/topprod" + app.config["ERP_USERNAME"] = "" + app.config["ERP_PASSWORD"] = "" + app.config["CONTRACT_PAYMENT_ERP_USERNAME"] = "hxjm_ro" + app.config["CONTRACT_PAYMENT_ERP_PASSWORD"] = "secret-from-contract-payment" + dsn, username, password, timeout = _erp_settings() + assert dsn == "192.168.8.24:1521/topprod" + assert username == "hxjm_ro" + assert password == "secret-from-contract-payment" + assert timeout >= 1 diff --git a/backend/tests/voucher_check/test_share_and_fingerprint.py b/backend/tests/voucher_check/test_share_and_fingerprint.py deleted file mode 100644 index 43ee3b13..00000000 --- a/backend/tests/voucher_check/test_share_and_fingerprint.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -backend/tests/voucher_check/test_share_and_fingerprint.py - -用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。 -依赖:pytest、临时目录、voucher_check 领域模块。 -逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。 -""" - -from __future__ import annotations - -from datetime import date -from pathlib import Path - -import pytest - -from app.core.errors import ValidationError -from app.services.voucher_check.config import ( - RequiredFileRule, - validate_directory_template, -) -from app.services.voucher_check.fingerprint import build_material_fingerprint -from app.services.voucher_check.share_scanner import ( - FileMeta, - match_required_files, - scan_invoice_folder, -) - - -def test_directory_template_rejects_unknown_placeholder(): - with pytest.raises(ValidationError) as exc: - validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}") - assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID" - - -def test_exact_filename_match_and_zero_byte_counts(): - rules = ( - RequiredFileRule( - code="price_check_sheet", - name="核价单", - required=True, - accepted_filenames=("核价单.pdf",), - ), - RequiredFileRule( - code="purchase_order", - name="采购单", - required=True, - accepted_filenames=("采购单.pdf",), - ), - ) - files = [ - FileMeta(name="核价单.pdf", size=0, mtime_ns=1), - FileMeta(name="采购单.pdf", size=10, mtime_ns=2), - ] - matched, missing = match_required_files(files, rules, case_sensitive=True) - assert matched["price_check_sheet"] == "核价单.pdf" - assert matched["purchase_order"] == "采购单.pdf" - assert missing == [] - - -def test_subdir_same_name_does_not_count(tmp_path: Path): - """直接子文件才命中;子目录内同名文件不算。""" - from app.services.voucher_check.config import VoucherCheckConfig - - root = tmp_path / "vouche" - inv_dir = root / "2026" / "08" / "INV001" - inv_dir.mkdir(parents=True) - nested = inv_dir / "nested" - nested.mkdir() - (nested / "核价单.pdf").write_bytes(b"x") - (inv_dir / "采购单.pdf").write_bytes(b"y") - - cfg = VoucherCheckConfig( - scope_code="HXJM", - directory_template="{root}/{YYYY}/{MM}/{invoice_no}", - required_files=( - RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)), - RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)), - ), - filename_case_sensitive=True, - notify_missing_enabled=False, - notify_failure_enabled=False, - same_day_dedup_enabled=False, - local_root=str(root), - share_unc="", - healthcheck_relative_path=".hxops-share-ready", - erp_dsn="x", - erp_username="u", - erp_password="p", - ) - result = scan_invoice_folder( - cfg, - root=str(root), - period_month=date(2026, 8, 1), - invoice_no="INV001", - ) - assert result.result == "missing" - assert any(m["code"] == "price_check_sheet" for m in result.missing_materials) - assert result.matched_files.get("purchase_order") == "采购单.pdf" - - -def test_fingerprint_stable_and_changes_on_mtime(): - a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)]) - b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)]) - assert a == b - c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)]) - assert a != c diff --git a/backend/tests/voucher_check/test_tool_auth_and_openapi.py b/backend/tests/voucher_check/test_tool_auth_and_openapi.py deleted file mode 100644 index a0def318..00000000 --- a/backend/tests/voucher_check/test_tool_auth_and_openapi.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -backend/tests/voucher_check/test_tool_auth_and_openapi.py - -用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。 -依赖:pytest、openapi_base.json。 -逻辑:直接读 JSON,校验 operationId 与 securitySchemes。 -""" - -from __future__ import annotations - -import json -from pathlib import Path - -_SPEC = ( - Path(__file__).resolve().parents[2] - / "app" - / "services" - / "voucher_check" - / "openapi_base.json" -) - - -def test_openapi_base_contains_expected_operations(): - spec = json.loads(_SPEC.read_text(encoding="utf-8")) - paths = spec["paths"] - assert ( - paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"] - == "list_voucher_missing" - ) - assert ( - paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"] - == "list_voucher_run_items" - ) - assert ( - paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"] - == "get_voucher_invoice_latest" - ) - assert "BearerAuth" in spec["components"]["securitySchemes"] - assert "IntegrationKey" in spec["components"]["securitySchemes"] - - -def test_docs_openapi_export_in_sync(): - docs = ( - Path(__file__).resolve().parents[3] - / "docs" - / "openapi" - / "accounting_voucher_check_tools_openapi.json" - ) - assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py" - exported = json.loads(docs.read_text(encoding="utf-8")) - base = json.loads(_SPEC.read_text(encoding="utf-8")) - assert exported["paths"].keys() == base["paths"].keys() diff --git a/backend/tests/voucher_check/test_workspace_force_recheck.py b/backend/tests/voucher_check/test_workspace_force_recheck.py new file mode 100644 index 00000000..16c707ba --- /dev/null +++ b/backend/tests/voucher_check/test_workspace_force_recheck.py @@ -0,0 +1,203 @@ +""" +backend/tests/voucher_check/test_workspace_force_recheck.py + +用途:工作台强制重检入队(force_all)与并发冲突。 +依赖:pytest、Flask client;不执行真实周任务。 +逻辑:POST /api/workspace/accounting-voucher-check/runs 写入 run_options.mode=force_all;已有 queued 时 409。 +""" + +from __future__ import annotations + +from tests.conftest import parse_api_data, parse_api_error + +from app import db +from app.models import ScheduleRun, ScheduleTask, User +from app.core.errors import ValidationError +from app.services.voucher_check.dms_client import SalesDmsClient +from app.services.voucher_check.schedule_seed import ( + DEFAULT_VOUCHER_CHECK_PLATFORM_PATH, + DEFAULT_VOUCHER_CHECK_SCHEDULE_NO, + ensure_default_voucher_check_schedule, +) + + +def _ensure_user(*, username: str, role: str) -> User: + user = db.session.query(User).filter_by(username=username).first() + if user: + user.role = role + user.status = "active" + db.session.commit() + return user + user = User( + username=username, + email=f"{username}@example.com", + role=role, + status="active", + ) + user.set_password("test") + db.session.add(user) + db.session.commit() + return user + + +def _stub_force_run_preflight(monkeypatch) -> None: + """隔离配置预校验,只验证工作台入队和失败可见性契约。""" + monkeypatch.setattr( + "app.services.voucher_check.config.load_engine_config", + lambda _params: type("Config", (), {"profile_code": "sales"})(), + ) + monkeypatch.setattr( + "app.services.voucher_check.profile_loader.load_profile_definition", + lambda _code: {"profile_code": "sales"}, + ) + monkeypatch.setattr( + "app.services.voucher_check.profile_loader.ensure_published_profile", + lambda _code: None, + ) + monkeypatch.setattr("app.services.voucher_check.dms_client.SalesDmsClient.ensure_configured", lambda: None) + + +def test_dms_preflight_reports_missing_keys_without_secret_values(app, monkeypatch): + """DMS 配置缺失时要指出变量名,且不在错误内容中泄露凭据值。""" + with app.app_context(): + monkeypatch.setattr(SalesDmsClient, "base_url", classmethod(lambda _cls: "https://dms.example")) + monkeypatch.setattr(SalesDmsClient, "library_id", classmethod(lambda _cls: "library-id")) + monkeypatch.setattr(SalesDmsClient, "root_folder_id", classmethod(lambda _cls: "folder-id")) + monkeypatch.setattr(SalesDmsClient, "username", classmethod(lambda _cls: "")) + monkeypatch.setattr(SalesDmsClient, "password", classmethod(lambda _cls: "")) + try: + SalesDmsClient.ensure_configured() + except ValidationError as exc: + assert exc.code == "VOUCHER_CHECK.CONFIG_INVALID" + assert exc.details["missing"] == ["VOUCHER_CHECK_DMS_USERNAME", "VOUCHER_CHECK_DMS_PASSWORD"] + else: + raise AssertionError("expected missing DMS configuration to fail") + + +def test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers, monkeypatch): + """工作台按钮入队后,ScheduleRun 必须带 force_all,供 runner 跳过增量。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + assert task.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO + assert task.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH + _stub_force_run_preflight(monkeypatch) + + first = client.post( + "/api/workspace/accounting-voucher-check/runs", + json={"mode": "force_all"}, + headers=admin_headers, + ) + assert first.status_code == 200 + data = parse_api_data(first.get_json()) + assert data["mode"] == "force_all" + assert data["status"] == "queued" + assert data["run_no"] + + with app.app_context(): + run = db.session.get(ScheduleRun, data["schedule_run_id"]) + assert run is not None + options = (run.api_request_json or {}).get("run_options") or {} + assert options.get("mode") == "force_all" + + second = client.post( + "/api/workspace/accounting-voucher-check/runs", + json={"mode": "force_all"}, + headers=admin_headers, + ) + assert second.status_code == 409 + error = parse_api_error(second.get_json()) + assert error["code"] == "VOUCHER_CHECK.RUN_IN_PROGRESS" + + +def test_workspace_force_recheck_rejects_non_admin_and_invalid_mode(app, client, admin_headers, user_headers, monkeypatch): + with app.app_context(): + _ensure_user(username="admin", role="admin") + _ensure_user(username="user", role="user") + ensure_default_voucher_check_schedule(commit=True) + _stub_force_run_preflight(monkeypatch) + + forbidden = client.post( + "/api/workspace/accounting-voucher-check/runs", + json={"mode": "force_all"}, + headers=user_headers, + ) + assert forbidden.status_code == 403 + + invalid = client.post( + "/api/workspace/accounting-voucher-check/runs", + json={"mode": "incremental"}, + headers=admin_headers, + ) + assert invalid.status_code == 400 + error = parse_api_error(invalid.get_json()) + assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID" + + +def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, admin_headers): + """配置校验在建引擎批次前失败时,页面仍应展示技术失败与原因。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + run = ScheduleRun( + schedule_task_id=task.id, + run_no="RUN-PREENGINE-FAILED", + trigger_type="manual", + status="failed", + total_count=0, + success_count=0, + failed_count=1, + error_message="未配置销售开票附件文档库根目录", + response_summary_json={"voucher_check": {"period": "2026-08"}}, + ) + db.session.add(run) + db.session.commit() + + response = client.get( + "/api/workspace/accounting-voucher-check/runs?period=2026-08&status=technical_failed", + headers=admin_headers, + ) + assert response.status_code == 200 + payload = parse_api_data(response.get_json()) + assert payload["total"] == 1 + item = payload["items"][0] + # 关键断言:前端列表读取的 run 数据保留失败原因,而非呈现为“暂无检核批次”。 + assert item["run_no"] == "RUN-PREENGINE-FAILED" + assert item["status"] == "technical_failed" + assert item["error_message"] == "未配置销售开票附件文档库根目录" + + +def test_seed_strips_legacy_share_job_params(app): + """已有排程若仍带共享盘旧字段,启动/入队种子必须剥掉,否则 worker 会 unknown params。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + task.job_params = { + "scope_code": "HXJM", + "profile_code": "sales", + "notify_missing_enabled": True, + "notify_failure_enabled": True, + "directory_template": "{root}/{YYYY}/{MM}/{invoice_no}", + "dir_template": "{root}/{YYYY}/{MM}/{invoice_no}", + "required_files": ["核价单.pdf", "采购单.pdf"], + "filename_case_sensitive": True, + "case_sensitive": False, + "same_day_dedup_enabled": True, + "same_day_dedup": True, + } + db.session.commit() + + refreshed = ensure_default_voucher_check_schedule(commit=True) + params = refreshed.job_params if isinstance(refreshed.job_params, dict) else {} + assert "directory_template" not in params + assert "dir_template" not in params + assert "required_files" not in params + assert "filename_case_sensitive" not in params + assert "case_sensitive" not in params + assert "same_day_dedup_enabled" not in params + assert "same_day_dedup" not in params + assert params["scope_code"] == "HXJM" + assert params["profile_code"] == "sales" diff --git a/backend/tests/voucher_check/test_workspace_notifications.py b/backend/tests/voucher_check/test_workspace_notifications.py new file mode 100644 index 00000000..14746518 --- /dev/null +++ b/backend/tests/voucher_check/test_workspace_notifications.py @@ -0,0 +1,144 @@ +""" +backend/tests/voucher_check/test_workspace_notifications.py + +用途:工作台企微发送记录列表 API。 +依赖:pytest、Flask client;不发送真实企微。 +逻辑:GET /api/workspace/accounting-voucher-check/notifications 读 voucher_check_notifications, + 回填接收人姓名与 has_excel,并可按期间、发送状态筛选。 +""" + +from __future__ import annotations + +from datetime import date, datetime + +from tests.conftest import parse_api_data + +from app import db +from app.models import ScheduleRun, User +from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun +from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule + + +def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> User: + """测试用户幂等创建。""" + user = db.session.query(User).filter_by(username=username).first() + if user: + user.role = role + user.status = "active" + if real_name: + user.real_name = real_name + db.session.commit() + return user + user = User( + username=username, + email=f"{username}@example.com", + role=role, + status="active", + real_name=real_name, + ) + user.set_password("test") + db.session.add(user) + db.session.commit() + return user + + +def test_workspace_lists_wecom_notifications(app, client, user_headers): + """企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + recipient = _ensure_user(username="user", role="user", real_name="Zhang San") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + schedule_run = ScheduleRun( + schedule_task_id=task.id, + run_no="RUN-VC-NOTIFY-1", + trigger_type="cron", + status="success", + excel_file_name="voucher-check-2026-08.xlsx", + excel_file_size=12, + excel_file_data=b"xlsx-bytes", + ) + db.session.add(schedule_run) + db.session.flush() + engine_run = VoucherCheckRun( + id=1, + schedule_run_id=schedule_run.id, + run_no="VC-202608-001", + profile_code="sales", + profile_version="1", + profile_snapshot_json={"profile_code": "sales"}, + period_month=date(2026, 8, 1), + mode="incremental", + status="missing", + subject_count=10, + missing_file_count=4, + missing_invoice_count=2, + ) + db.session.add(engine_run) + db.session.flush() + db.session.add( + VoucherCheckNotification( + id=1, + run_id=engine_run.id, + excel_filename="voucher-check-2026-08.xlsx", + recipient_user_ids_json=[recipient.id], + send_status="sent", + skip_reason=None, + summary_json={"period": "2026-08", "subject_count": 10}, + sent_at=datetime(2026, 9, 1, 6, 10, 0), + ) + ) + skipped_run = VoucherCheckRun( + id=2, + run_no="VC-202607-001", + profile_code="sales", + profile_version="1", + profile_snapshot_json={"profile_code": "sales"}, + period_month=date(2026, 7, 1), + mode="incremental", + status="completed", + subject_count=8, + missing_file_count=0, + missing_invoice_count=0, + ) + db.session.add(skipped_run) + db.session.flush() + db.session.add( + VoucherCheckNotification( + id=2, + run_id=skipped_run.id, + send_status="skipped_no_missing", + skip_reason="本批无缺件", + summary_json={"period": "2026-07"}, + ) + ) + db.session.commit() + + listed = client.get( + "/api/workspace/accounting-voucher-check/notifications", + headers=user_headers, + ) + assert listed.status_code == 200 + payload = parse_api_data(listed.get_json()) + assert payload["total"] >= 2 + sent = next(item for item in payload["items"] if item["run_no"] == "VC-202608-001") + # 关键断言:工作台汇总列表能看到发送状态、接收人姓名和 Excel 入口。 + assert sent["send_status"] == "sent" + assert sent["missing_invoice_count"] == 2 + assert sent["missing_file_count"] == 4 + assert sent["recipient_names"] == ["Zhang San"] + assert sent["has_excel"] is True + assert sent["schedule_run_id"] + + filtered = client.get( + "/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing", + headers=user_headers, + ) + assert filtered.status_code == 200 + filtered_payload = parse_api_data(filtered.get_json()) + assert filtered_payload["total"] == 1 + item = filtered_payload["items"][0] + assert item["run_no"] == "VC-202607-001" + assert item["send_status"] == "skipped_no_missing" + assert item["skip_reason"] == "本批无缺件" + assert item["has_excel"] is False diff --git a/backend/tests/workers/test_in_transit_transfer_worker.py b/backend/tests/workers/test_in_transit_transfer_worker.py new file mode 100644 index 00000000..8b68b253 --- /dev/null +++ b/backend/tests/workers/test_in_transit_transfer_worker.py @@ -0,0 +1,23 @@ +"""在途调拨 transfer 队列 Worker 入口测试。 + +用途:验证 workers/worker_in_transit_transfer.py 可导入、目标队列为 transfer, + 且模块导入不触发主循环(__main__ 守卫)。 +依赖:workers.worker_in_transit_transfer(import 级验证,不启动进程)。 +""" + +from __future__ import annotations + +import importlib + + +def test_worker_module_imports_and_targets_transfer_queue(): + """worker 模块可导入并声明 transfer 队列。""" + module = importlib.import_module("workers.worker_in_transit_transfer") + assert module.QUEUES == ["transfer"] + + +def test_worker_main_guard_prevents_auto_start(): + """模块导入不执行 main(__main__ 守卫)。""" + module = importlib.import_module("workers.worker_in_transit_transfer") + assert hasattr(module, "main") + assert module.__name__ == "workers.worker_in_transit_transfer" diff --git a/backend/worker.py b/backend/worker.py index d26886f4..470cd720 100644 --- a/backend/worker.py +++ b/backend/worker.py @@ -4,6 +4,7 @@ backend/worker.py 用途:统一后台 worker 入口(方案 D)。 依赖:app.create_app、app.jobs.runner、app.jobs.handlers。 逻辑:--queues kb,shipping,contract,schedule;经 jobs.runner 统一 poll → dispatch。 + 启动诊断按队列打印,避免 schedule worker 误刷合同付款预警 ERP 配置。 """ from __future__ import annotations @@ -55,6 +56,35 @@ def _resolve_config_name() -> str: return mapping.get(env_name, 'production') +def _log_queue_startup_diagnostics(logger: logging.Logger, app, queue_names: list[str]) -> None: + """ + 按实际消费队列打印启动诊断,避免 schedule worker 刷出合同付款预警配置造成误判。 + + 核心逻辑:contract 队列才打印合同付款 ERP 就绪状态;schedule 队列说明 jobs 表身份字段。 + 只标记配置是否就绪,不输出密码或连接串。 + + Args: + logger: worker logger。 + app: Flask 应用,读取 config。 + queue_names: 本次启动消费的队列名。 + """ + if 'contract' in queue_names: + erp_dsn = str(app.config.get('CONTRACT_PAYMENT_ERP_DSN') or '').strip() + erp_user = str(app.config.get('CONTRACT_PAYMENT_ERP_USERNAME') or '').strip() + erp_pwd = str(app.config.get('CONTRACT_PAYMENT_ERP_PASSWORD') or '') + logger.info( + '合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s', + '✓就绪' if erp_dsn else '✗缺失', + '✓就绪' if erp_user else '✗缺失', + '✓就绪' if erp_pwd else '✗缺失', + ) + if 'schedule' in queue_names: + logger.info( + 'schedule 队列身份:domain/job_type 固定为 schedule/schedule_run;' + '立账凭证检核看 business_ref 后缀 accounting-voucher-check 或 payload.platform_api_path' + ) + + def main( *, queues: list[str] | None = None, @@ -75,16 +105,7 @@ def main( app = create_app(resolved_config) queue_names = queues or ['kb'] - # 启动期诊断:确认合同付款 ERP 回查的运行时配置状态(只标记是否就绪,不输出密码)。 - _erp_dsn = str(app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip() - _erp_user = str(app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip() - _erp_pwd = str(app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "") - logger.info( - "合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s", - "✓就绪" if _erp_dsn else "✗缺失", - "✓就绪" if _erp_user else "✗缺失", - "✓就绪" if _erp_pwd else "✗缺失", - ) + _log_queue_startup_diagnostics(logger, app, queue_names) if queue_names == ['schedule'] and not bool(app.config.get('SCHEDULE_WORKER_ENABLED', True)): logger.info('Schedule worker disabled by SCHEDULE_WORKER_ENABLED=false') diff --git a/backend/workers/worker_in_transit_transfer.py b/backend/workers/worker_in_transit_transfer.py new file mode 100644 index 00000000..1d5ace55 --- /dev/null +++ b/backend/workers/worker_in_transit_transfer.py @@ -0,0 +1,24 @@ +""" +backend/workers/worker_in_transit_transfer.py + +用途:在途仓自动调拨 transfer 队列 Worker Supervisor 兼容入口。 +依赖:backend/worker.py(通用领取/租约/回收)。 +逻辑:转调 backend/worker.py,仅消费 transfer 队列(预检/执行 Run/Item)。 +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main # noqa: E402 + +# transfer 队列消费类型:in_transit_transfer_precheck / in_transit_transfer_run / in_transit_transfer_item +QUEUES = ["transfer"] + +if __name__ == "__main__": + main(queues=QUEUES) diff --git a/docker-compose.yml b/docker-compose.yml index 2fadea96..d6a9b598 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -61,10 +61,7 @@ services: # 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC - FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-} - FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-} - # 立账凭证检核:容器必须读 LOCAL_ROOT,不能依赖 UNC - - VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-} - - VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-} - - VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready} + # 立账凭证检核:ERP 只读;文档库走 DMS 环境变量 - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} @@ -81,9 +78,6 @@ services: # test/prod 的 FIXED_ASSET_HISTORY_LOCAL_ROOT 分别指向对应路径;未使用的一侧为空目录无影响。 - /mnt/hxops-fixed-asset-history-test:/mnt/hxops-fixed-asset-history-test:ro - /mnt/hxops-fixed-asset-history-prod:/mnt/hxops-fixed-asset-history-prod:ro - # 立账凭证检核共享盘:宿主机 CIFS 挂载后再 bind 只读进容器 - - /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro - - /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro # 货代发货通知 RPA:分别挂载 test/prod Worker 的共享数据目录 - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data @@ -180,10 +174,7 @@ services: - SHIPPING_NOTICE_STORAGE_ROOT=${SHIPPING_NOTICE_STORAGE_ROOT:-/app/data/shipping_notice} - FREIGHT_INVENTORY_DROP_DIR=${FREIGHT_INVENTORY_DROP_DIR:-/app/data/shipping_notice/freight_rpa/inventory_drop} - FREIGHT_RPA_INVENTORY_TRIGGER_DIR=${FREIGHT_RPA_INVENTORY_TRIGGER_DIR:-/app/data/shipping_notice/freight_rpa/inventory_triggers} - # 立账凭证检核:日批在 schedule-worker 内执行,必须与 backend 同挂载 - - VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-} - - VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-} - - VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready} + # 立账凭证检核:周批在 schedule-worker 内执行 - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} @@ -192,8 +183,9 @@ services: volumes: - ./oracle_client:/app/oracle_client:ro - hxops_runtime_data:/app/data - - /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro - - /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro + # 库存 RPA trigger 由 schedule-worker 写入,必须与 backend 同挂 CIFS,否则 Windows Worker 看不到 + - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data + - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data networks: - ai-platform @@ -237,6 +229,56 @@ services: - SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=${SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS:-30} extra_hosts: - "host.docker.internal:host-gateway" + volumes: + - ./oracle_client:/app/oracle_client:ro + - hxops_runtime_data:/app/data + # 按需库存准备由 shipping-worker 写 RPA trigger,必须与 backend/schedule-worker 同挂 CIFS; + # 否则容器本地 mkdir /mnt/hxops-rpa-*-data 成功、DB 记 trigger_written,但 Windows 共享盘无文件。 + - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data + - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data + networks: + - ai-platform + + # ============================================================================== + # hxops-transfer-worker: 在途仓自动调拨专用 worker(transfer 队列) + # ============================================================================== + hxops-transfer-worker: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: . + dockerfile: backend/Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim-bookworm} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-transfer-worker + restart: always + command: ["python", "workers/worker_in_transit_transfer.py"] + depends_on: + - hxops-backend + env_file: + - ${COMPOSE_SHARED_ENV_BASENAME:-.env.shared} + - ${COMPOSE_ENV_BASENAME:-.env.dev} + environment: + - DATABASE_URL=${DATABASE_URL} + - SECRET_KEY=${SECRET_KEY} + - FLASK_APP=${FLASK_APP:-run.py} + - FLASK_ENV=${FLASK_ENV} + - REDIS_URL=${REDIS_URL:-redis://kb-redis:6379/0} + - SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=${SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR:-} + - IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=${IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY:-2} + - IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY:-2} + - IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY:-1} + - IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=${IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS:-60} + - IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=${IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS:-60} + - IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=${IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS:-600} + - IN_TRANSIT_TRANSFER_ERP_ENDPOINT=${IN_TRANSIT_TRANSFER_ERP_ENDPOINT:-} + - IN_TRANSIT_TRANSFER_ERP_USERNAME=${IN_TRANSIT_TRANSFER_ERP_USERNAME:-} + - IN_TRANSIT_TRANSFER_ERP_PASSWORD=${IN_TRANSIT_TRANSFER_ERP_PASSWORD:-} + - IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=${IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG:-} + - IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=${IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET:-hxops-transfer} + extra_hosts: + - "host.docker.internal:host-gateway" volumes: - ./oracle_client:/app/oracle_client:ro - hxops_runtime_data:/app/data diff --git a/docs/convention/环境变量规则.md b/docs/convention/环境变量规则.md index 8cbc611a..10d78f9b 100644 --- a/docs/convention/环境变量规则.md +++ b/docs/convention/环境变量规则.md @@ -83,3 +83,11 @@ - `PROCUREMENT_CONTRACT_LLM_DIFY_BASE` `PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` 属于密钥;生产环境优先由 Jenkins/部署平台注入。当前优先通过 `PROCUREMENT_CONTRACT_LLM_AGENT_ID` 复用已配置的 Chatflow Agent,不在环境文件重复保存密钥。 + +## 8. 立账凭证检核文档库 + +三环境一致、非密钥的销售开票附件根目录放在 `.env.shared`: + +- `VOUCHER_CHECK_DMS_ROOT_FOLDER_ID` + +登录基址、LibraryID、账号默认复用 `CONTRACT_DMS_*`。如需覆盖再设 `VOUCHER_CHECK_DMS_BASE_URL` / `VOUCHER_CHECK_DMS_LIBRARY_ID` / `VOUCHER_CHECK_DMS_USERNAME` / `VOUCHER_CHECK_DMS_PASSWORD`(密码禁止写入仓库)。 diff --git a/docs/demand.md b/docs/demand.md index 9f6ed3bd..45387816 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -37,23 +37,22 @@ - Header/Line 均支持可选 `reservation_id`;有效值 `effective_reservation_id = line ?? header`,字段层不强制必填,建单门禁另计。 - 项次三字段生命周期: - `customer_po_line_no`:客户 PO 原始项次(如 `00010`),识别/复核后永久保留原始事实。 - - `line_no`:内部业务项次;可识别、可由 Schema `derivation_rules` 派生(首期 `copy_if_empty`)、冻结前可人工覆盖;格式 1–6 位数字并保留前导零。 - - `export_sequence`:本次 Excel 最终导出行序号(1..N),仅导出期 `system_fact`,不属于订单字段。 -- 废除 `system_fact → line_no`;Excel 序号统一 `system_fact → export_sequence`。 + - `line_no`:系统按订单明细顺序生成的不可变项次;不参与 Schema 配置、解析或人工修改。 + - 发货通知项次:`ShippingNoticeLine.line_no`,每张通知单从 1 重新编号。 - 标准字段资产唯一键为 `(field_code, scope)`,允许 Header/Line 同名 Reservation。 - 库存匹配键仍为有效 Reservation + Part Number;行级多候选库存源属于后续阶段。 ### STP 阶段 1 模板起行锚点(2026-07-30) - 坐标模板以可配置 `line_start_field_code`(默认客户 PO 行号)识别逻辑明细起点;`line_no` 亦可作为可识别内部项次绑定。 -- 多物理行仍组成一条逻辑明细;Excel 导出行序号在最终导出集上连续生成(`export_sequence`)。 +- 多物理行仍组成一条逻辑明细;Excel 导出使用发货通知行项次。 - 首期两个现有模板须重新绑定并通过盲测。 ### STP 阶段 2 建单前库存源候选(2026-07-30) - 行级/任务级已发布路由规则产出 `candidate_inventory_source_codes`;多候选(`ambiguous`)允许建单,零候选或 `require_manual_review` 阻断。 - 有效 Reservation(`line ?? header`)与库存源候选共同构成建单门禁;Draft 校验与确认投影 `build_eligibility`。 -- 复核员可人工选择已启用库存源并填写原因(PUT `.../draft/lines//inventory-candidates`),覆盖规则零候选。 +- 通知准备阶段可按冻结档项次人工选择已启用库存源并填写原因;库存源未确认不创建正式发货通知。 ### STP 阶段 3 自动建单与复核工作台(2026-07-30) @@ -64,7 +63,7 @@ ### STP 阶段 4 跨候选库存匹配至待人工上传(2026-07-30) - 准备全部冻结候选库存文件;按有效 Reservation + Part Number 跨文件匹配。 -- 唯一命中且数量充足 → 冻结实际库存源与行证据,自动生成 Excel(`export_sequence` 为导出行号,`line_no` 为订单内部项次),止于待人工上传。 +- 库存门禁通过(无缺口或人工放行)→ 创建正式发货通知及通知明细,再生成 Excel,止于待人工上传。 - 多源行级全部成功 → 以主绑定源制单(保留行级 resolved);同键多文件冲突、短缺、缺文件 → 人工例外。 - 零规则候选时复核台可从「已启用库存源」多选并填原因;`match_completed` 禁止 partial 制单。 @@ -216,14 +215,14 @@ ### 3.x 立账凭证检核补充需求 - AI 工作台中的“立账凭证”入口及页面仅对 `role=admin` 用户开放;普通用户不展示入口,直接访问地址时返回工作台应用页。 -- **核心目标**:按当前自然月从 HXJM 套账 ERP `apa_file` 取得发票号清单,检查共享盘对应发票目录中的必检文件是否存在,输出齐全/缺资料结果。 -- **数据口径**:`apa08` 为发票号且唯一,`apa09` 为发票日期;只检核当前自然月,不追溯月末补录的上月发票;红冲、作废、取消票据一期不纳入。 -- **目录口径**:共享盘默认采用 `vouche/{YYYY}/{MM}/{invoice_no}/`,目录模板可配置以支持后续调整。 -- **判定边界**:严格按可配置文件名判断存在性;暂定必检「核价单.pdf」「采购单.pdf」;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 -- **实现状态**:一期 HXOPS 引擎/API/工作台已落地;日批 `0 6 * * *`;**Dify Chatflow 编排待完成**。 -- **可靠性要求**:共享盘不可用、Oracle 查询失败或配置错误时,整批失败并告警,不得把整批票标记为缺资料;单票缺目录/缺文件才记为缺资料。 -- **通知要求**:缺资料按固定接收人发送企业微信通知,并按同票同日节流。 -- 技术规格见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 +- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单沿用旧口径(HXJM `apa_file.apa08/apa09`);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 +- **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。 +- **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。 +- **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。 +- **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。 +- **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 +- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总落地;PO/OA 打印仍待接线。不做 Chatflow;查询走工作台 API。 +- 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 ### 3.x 货代发货通知库存源补充需求 @@ -865,3 +864,10 @@ XFA 模板管理端暂不启用字段脱敏,树、拆分预览和样本验证 - Casdoor 登录到 HXOPS 本地用户以 `employee_id`(工号)为主映射键;当前用户名等于工号,仅保留用户名到本地工号/用户名的兼容回退。邮箱和手机号不参与认证映射;工号与用户名命中不同本地用户时拒绝登录。 --- + +## 在途仓自动调拨 Agent(2026-08) + +- 需求:仓库管理人员按收料来源实例(DBS-AWSBI / DBS-AWSSG / CRANE-SZ)核对收料文件与 ERP 账面库存后生成 ERP 调拨单;DBS/Crane 仅分组,来源实例为执行边界。 +- 手工两步:选择来源实例 → 预检明细核对后直接生成 ERP 调拨单(无独立确认页);当天收料不查询 ERP;数量严格相等才可执行;不支持部分调拨/容差/单位换算/批次拆分。 +- ERP 写入由后端确定性服务与 Worker 完成,Dify 不得直接调用 ERP;Invoice No 幂等;结果未知只读禁自动重试;通知失败不改变 ERP 结果。 +- 完整规格见 [features/in-transit-transfer/minimum-implementation-spec.md](features/in-transit-transfer/minimum-implementation-spec.md)。 diff --git a/docs/features/README.md b/docs/features/README.md index 192c8d21..99088ef1 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -2,15 +2,20 @@ 按 **业务域** 组织已落地或正在落地的功能手册;**产品原型与该域文档同目录**。**实现状态**见 [funclist.md](../funclist.md)。 -| 域 | 说明 | 入口 | -| ----------------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) | -| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) | -| [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | -| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | -| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | -| | | | -| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核 | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | +| 域 | 说明 | 入口 | +| --- | --- | --- | +| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) | +| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [运维手册](in-transit-transfer/technical.md) | +| [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | +| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | +| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | +| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核 | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | +| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) | +| [procurement-contract](procurement-contract/README.md) | 采购合同审查 Agent(模板比对 / 单份审核) | [用户操作手册](procurement-contract/用户操作手册.md) · [demand.md](procurement-contract/demand.md) · [comprehensive-review-technical.md](procurement-contract/comprehensive-review-technical.md) · [原型](procurement-contract/procurement-contract-review-prototype.html) | +| [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) | +| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) | + +**平台级**设计与跨域原型见 [platform/](../platform/README.md)。 **约定** diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index 84b55b9b..d0997668 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -1,18 +1,16 @@ # 立账凭证检核(accounting-voucher-check) -| 文档 | 读者 | 路径 | -| ---------------------------- | ---------------- | --------------------------------------------------------------- | -| | | | -| **需求说明** | 产品、业务、测试 | [demand.md](demand.md) | -| **历史需求与规格手册** | 研发、运维、测试 | [technical.md](technical.md)(旧版单共享盘方案,仅供历史实现参考) | +| 文档 | 读者 | 路径 | +| --- | --- | --- | +| **需求说明** | 产品、业务、测试 | [demand.md](demand.md) | +| **技术设计** | 研发 | [technical-design.md](technical-design.md) | +| **技术规格** | 研发、测试 | [technical.md](technical.md) | +| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) | +| **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) | - -| **销售一期需求说明** | 产品、业务、测试 | [demand.md](demand.md) | -| **需求与规格手册** | 产品、业务、测试 | [technical.md](technical.md) | - -**定位**:以业务方 Profile 驱动的批量资料检核;每周增量处理上一个自然月,按 `invoice` 集中归档。 +**定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。 **要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。 **检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。 -**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数,提供按文件类型、按 `invoice` 的汇总和单文件明细;同一 `invoice` 的多个缺件合并为一条企业微信通知。 +**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。 -**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。旧版已实现代码与文档尚未按新版需求改造,实施前须以 [technical-design.md](technical-design.md) 的新版设计为准。 +**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。ERP PO / OA 销货放行打印仍待接线。 diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html index f5dc97df..70874c6c 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html @@ -46,16 +46,16 @@ const profiles = { sales: { name: '销售一期', enabled: true, - desc: '每周增量检核上一个自然月;以销售 invoice 为核心,从 ERP、OA 与固定目录获取文件并集中归档。', + desc: '每周增量检核上一个自然月;获取后写入销售开票附件/{年}/{月}/{类型目录}/,再按 invoice 归入所有归档。', metrics: [['6','必检文件规则'],['每周','执行频率'],['上月','检核范围']], note: '缺少任一必检文件时生成双维度汇总 Excel 并发送企业微信通知;通知接收人待业务确认。', rules: [ - ['PO订单','{invoice号}-{订单号}.pdf','erp','ERP 查询并打印','以 invoice 反查 PO','查询条件待补充','已确认'], - ['报关资料','{invoice号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['销货放行申请单','{invoice号}-{销货单号}.pdf','oa','OA 报表打印','OA 读取发票号和销货单号','上月 + 归档 + HXJM + 发票号非空','流程已确认'], - ['发票','{invoice号}-{发票号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['报关单','{invoice号}-{报关单号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['提单','{invoice号}-提单.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'] + ['PO订单','{invoice号}-{订单号}.pdf','erp','ERP 查询并打印','以 invoice 反查 PO','销售开票附件/{年}/{月}/PO订单/','已确认'], + ['报关资料','{invoice号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/报关资料/','已确认'], + ['销货放行申请单','{invoice号}-{销货单号}.pdf','oa','OA 报表打印','OA 读取发票号和销货单号','销售开票附件/{年}/{月}/销货单/','已确认'], + ['发票','{invoice号}-{发票号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/发票/','已确认'], + ['报关单','{invoice号}-{报关单号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/报关单/','已确认'], + ['提单','{invoice号}-提单.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/提单/','已确认'] ], subjects: [ ['INV-202607-00128','已归档',[['PO订单','ERP 打印','archived'],['销货放行申请单','OA 打印','archived'],['报关资料','固定目录','archived'],['发票','固定目录','archived'],['报关单','固定目录','archived'],['提单','固定目录','archived']]], diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md index 8d080ee5..f3cbbbe2 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md @@ -15,8 +15,8 @@ ## 业务口径 -- 销售一期:每周增量检核上一个自然月,支持 ERP、OA 和固定目录来源,按 invoice 集中归档。 -- 销货放行申请单:OA 过滤上月、归档、HXJM、发票号码非空;关联字段不完整时直接跳过,不打印、不归档、不记录字段异常。 +- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `apa_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。 +- 销货放行申请单:一期模拟 OA 页面;后期换新接口。关联字段不完整时直接跳过。 - 采购二期:展示六类拟定文件规则;路径、主体来源和 Adapter 参数待确认,原型不执行采购检核。 - 批量缺件同时统计“缺件文件总数”和“缺件 `invoice` 数”;同一 `invoice` 缺多个文件时前者累计多个、后者只计一次。 - 统一 Excel 仅包含“检核结果”工作表:每行一个 `invoice`,直接展示各必检文件“有 / 缺件 / 未检核”和状态;全部文件均为“有”时状态为“完整”。 diff --git a/docs/features/accounting-voucher-check/demand.md b/docs/features/accounting-voucher-check/demand.md index 5091238f..f8e92b11 100644 --- a/docs/features/accounting-voucher-check/demand.md +++ b/docs/features/accounting-voucher-check/demand.md @@ -1,8 +1,10 @@ # 立账凭证资料检核需求说明 -> 文档版本:v1.1 -> 更新时间:2026-08-18 +> 文档版本:v1.9 +> 更新时间:2026-09-08 > 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置 +> +> 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。 ## 1. 背景与目标 @@ -25,31 +27,33 @@ | 项目 | 规则 | | -------- | ----------------------------------------------------------------------------------------------------------------------- | -| 执行频率 | 每周执行一次 | +| 执行频率 | 每周二执行一次(默认 06:00,Asia/Shanghai) | | 检核期间 | 执行日的上一个自然月;例如 2026-08-18 执行,检核 2026-07 | -| 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核 | -| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体 | -| 归档单位 | 以 `invoice` 为目录单位,同一 `invoice` 的全部已获取文件放入同一归档目录 | +| 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核。归档目录已有同名文件时按「同名跳过」不覆盖 | +| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。工作台「强制重检上月」入队 `force_all` | +| 归档单位 | 文档库「所有归档」下以 `invoice` 为子目录;同一 `invoice` 的已获取文件集中存放。获取后先落入当月类型目录 | ### 3.2 Profile 驱动扩展 -| 配置项 | 说明 | -| ---------------- | ------------------------------------------------------------------------------------- | -| `profile_code` | 业务方标识,例如 `sales`、`procurement` | -| 主体来源 | 获取本期应检 `invoice` 清单的来源和关联字段 | -| 文件规则 | 文件类型、必检性、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时目录、归档模板 | -| 通知规则 | 缺件通知开关、接收人、通知模板与去重策略 | +| 配置项 | 说明 | +| ---------------- | ----------------------------------------------------------------------------------------- | +| `profile_code` | 业务方标识,例如 `sales`、`procurement` | +| 主体来源 | 获取本期应检 `invoice` 清单的来源和关联字段 | +| 文件规则 | 文件类型、必检性、命名模板、关联字段、来源 Adapter、查询/扫描条件、类型存放路径、归档模板 | +| 通知规则 | 缺件通知开关、接收人、通知模板与去重策略 | 新增业务方时优先新增或调整 Profile;只有新增外部系统或获取协议时才开发新的来源 Adapter。 +销售一期主体清单**沿用旧方案 ERP 口径**:HXJM 套账只读查询 `apa_file`,`apa08` 为发票号、`apa09` 为发票日期,发票号非空。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。 + ### 3.3 结果状态 -| 状态 | 含义 | 是否计入缺件 | -| -------- | ---------------------------------------- | ------------ | -| 已归档 | 文件已取得、校验关联并复制到目标归档目录 | 否 | -| 缺件 | 必检文件未找到或未成功取得 | 是 | -| 已跳过 | 增量规则判定无需本次重新处理 | 否 | -| 技术失败 | 登录、查询、打印、复制等系统异常 | 否;单独告警 | +| 状态 | 含义 | 是否计入缺件 | +| -------- | ----------------------------------------------------- | ------------ | +| 已归档 | 文件已取得、校验关联并复制到「所有归档/{invoice号}/」 | 否 | +| 缺件 | 必检文件未找到或未成功取得 | 是 | +| 已跳过 | 增量规则判定无需本次重新处理 | 否 | +| 技术失败 | 登录、查询、打印、复制等系统异常 | 否;单独告警 | ### 3.4 检核任务列表 @@ -62,34 +66,69 @@ | 任务列表字段 | 批次号、业务方、资料所属期间、执行时间、主体总数、已归档数、缺件文件数、缺件 `invoice` 数、状态 | | 状态 | 缺件、已完成、技术失败、待配置 | | 操作 | 查看详情;进入该批次的执行记录,并可查看企业微信通知附件 Excel | -| 任务入口 | 支持新建任务、强制重检;强制重检仍只针对上一个自然月 | +| 任务入口 | 支持新建任务、强制重检(仅上一个月);企微接收人从系统用户多选,可复用排程通知人选择器 | + +### 3.5 企业微信发送记录 + +工作台同一入口用 Tab 切换「检核任务」与「企微发送记录」。发送记录以 `voucher_check_notifications` 为真相源,每批一条缺件汇总(已发送 / 失败 / 无缺件未发送 / 未配置接收人 / 通知关闭)。 + +| 区域 | 内容 | +| -------- | --------------------------------------------------------------------------------------------- | +| 筛选条件 | 资料所属期间、发送状态 | +| 列表字段 | 批次号、资料所属期间、invoice 总数、invoice 缺件数、缺件文件数、发送状态、未发送原因、接收人、发送时间、Excel | +| 操作 | 有附件时可下载该批 Excel;查看详情进入对应批次明细 | ## 4. 销售一期文件规则 -| 文件类型 | 命名方式 | 获取方式 | `invoice` 关联 | 扫描/查询条件 | 路径状态 | -| -------------- | ------------------------------ | -------------------------- | --------------------------- | ---------------------- | ------------------- | -| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | 以销售 `invoice` 反查 PO | ERP 具体查询字段待补充 | 临时/归档路径待确认 | -| 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | OA 列表读取发票号、销货单号 | 见 5.1 | 临时/归档路径待确认 | -| 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 报关单 | `{invoice号}-{报关单号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 提单 | `{invoice号}-提单.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | +销售开票附件落在文档管理系统(文档库)中。不论从 ERP 打印、OA 打印还是固定目录扫描,**获取成功后都先写入当月类型存放目录**,再按发票号归档到「所有归档」。 -> 各路径确认前不得虚构实际目录。文件命名、路径和查询条件均由销售 Profile 配置。 +目录层级(销售一期检核涉及的类型目录): + +```text +文档库 / 销售开票附件 / {yyyy} / {MM} / + ├── PO订单/ + ├── 发票/ + ├── 报关资料/ + ├── 销货单/ ← 销货放行申请单的类型存放目录 + ├── 报关单/ + ├── 提单/ + └── 所有归档/{invoice号}/ +``` + +`{yyyy}`、`{MM}` 为检核月份的四位年份与两位月份,例如 `2026/08`。 + +| 文件类型 | 命名方式 | 获取方式 | 存放路径 | `invoice` 关联 | 扫描/查询条件 | +| -------------- | ------------------------------ | -------------------------- | --------------------------------------------- | --------------------------- | ---------------------- | +| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | 以销售 `invoice` 反查 PO | **待确认**:查询字段、关联与打印方式 | +| 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关资料/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | OA 列表读取发票号、销货单号 | 见 5.1 | +| 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/发票/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 报关单 | `{invoice号}-{报关单号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 提单 | `{invoice号}-提单.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/提单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | + +归档路径(六类文件共用,按发票号集中): + +```text +文档库/销售开票附件/{yyyy}/{MM}/所有归档/{invoice号}/ +``` + +> 固定目录扫描的来源即上表「存放路径」。ERP/OA 打印件写入同一类型目录后再归档。销售类型目录名已确认固定,不随现场习惯改名:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单`。文档库系统、接口与账号见 §5.4。 ## 5. 销售文件获取与归档 ### 5.1 销货放行申请单(OA) -| 步骤 | 操作与规则 | -| ---- | ------------------------------------------------------------------ | -| 1 | 在 OA 进入“报表 → 流程报表 → 自定义报表”,选择“销货放行单” | -| 2 | 过滤申请日期为检核期间(上一个自然月) | -| 3 | 过滤流程状态为“归档”、账套为 `HXJM`、发票号码不为空 | -| 4 | 从结果列表读取发票号和销货单号,以二者关联并生成文件名 | -| 5 | 对关联字段完整的每条申请单逐条打印并保存为 PDF | -| 6 | 关联字段不完整时直接丢弃该 OA 记录:不打印、不归档、不记录字段异常 | -| 7 | 校验后复制至对应 `invoice` 的归档目录 | +一期**只支持按页面模拟**完成下列步骤;不依赖尚未提供的 OA 打印 API。后续对接新 OA 接口时,过滤条件、命名和归档规则不变,仅替换 Adapter 实现。 + +| 步骤 | 操作与规则 | +| ---- | --------------------------------------------------------------------- | +| 1 | 在 OA 进入“报表 → 流程报表 → 自定义报表”,选择“销货放行单” | +| 2 | 过滤申请日期为检核期间(上一个自然月) | +| 3 | 过滤流程状态为“归档”、账套为 `HXJM`、发票号码不为空 | +| 4 | 从结果列表读取发票号和销货单号,以二者关联并生成文件名 | +| 5 | 对关联字段完整的每条申请单:一期按页面逐步模拟打开并打印/保存 PDF;预留切换新 OA 接口,接口就绪后不改过滤与命名规则 | +| 6 | 关联字段不完整时直接丢弃该 OA 记录:不打印、不归档、不记录字段异常 | +| 7 | 校验后先写入当月「销货单」存放目录,再复制到「所有归档/{invoice号}/」 | ```mermaid flowchart TD @@ -97,36 +136,61 @@ flowchart TD B --> C[读取发票号与销货单号] C --> D{关联字段完整?} D -- 否 --> E[直接丢弃,不记录字段异常] - D -- 是 --> F[逐条打印并保存 PDF] - F --> G[按 invoice 校验命名并归档] + D -- 是 --> F[一期模拟页面打印 PDF / 后期改走 OA 接口] + F --> G[写入销货单目录并归档到所有归档/invoice] ``` ### 5.2 PO 订单(ERP) -| 步骤 | 操作与规则 | -| ---- | ------------------------------------------------------------- | -| 1 | 以上月销售 `invoice` 清单为入口 | -| 2 | 在 ERP 查询并反查对应 PO 订单 | -| 3 | 每个 PO 订单打印并保存一个 PDF | -| 4 | 按 `invoice + 订单号` 命名,复制至对应 `invoice` 归档目录 | -| 5 | ERP 查询字段、过滤条件和具体路径待业务补充 | +| 步骤 | 操作与规则 | +| ---- | -------------------------------------------------------- | +| 1 | 以上月销售 `invoice` 清单为入口 | +| 2 | 在 ERP 查询并反查对应 PO 订单 | +| 3 | 每个 PO 订单打印并保存一个 PDF | +| 4 | 按 `invoice + 订单号` 命名,写入当月「PO订单」存放目录 | +| 5 | 再复制到「所有归档/{invoice号}/」 | +| 6 | **待确认**:ERP 查询字段、invoice 与 PO 关联、打印入口与 PDF 落盘方式 | -### 5.3 通用归档流程 +### 5.3 通用存放与归档流程 + +获取与归档分两步,都在文档库「销售开票附件」下完成: + +| 步骤 | 位置 | 规则 | +| ---------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| 1 类型存放 | `销售开票附件/{yyyy}/{MM}/{类型目录}/` | ERP/OA 打印或目录扫描的成功文件先落入对应类型目录,按上表命名 | +| 2 按票归档 | `销售开票附件/{yyyy}/{MM}/所有归档/{invoice号}/` | 校验 `invoice` 关联和命名后,将成功文件**复制**(不移动类型目录原件)到该发票子目录;同一 `invoice` 的多个文件必须集中在同一子目录,不同 `invoice` 不得混放。**重复文件策略:同名跳过**——目标目录已有相同 `LeafName` 时不覆盖、不报缺件,视为已归档 | ```mermaid flowchart TD A[每周任务启动] --> B[确定上一个自然月] B --> C[加载业务方 Profile 和本期 invoice 清单] C --> D[按文件规则调用来源 Adapter] - D --> E[获取或打印至临时目录] + D --> E[写入类型存放目录] E --> F[校验 invoice 关联和命名] - F --> G[建立 invoice 归档目录] - G --> H[复制文件并记录单文件结果] + F --> G[复制到所有归档/invoice号] + G --> H[记录单文件结果] H --> I[汇总缺件与技术失败] I --> J[生成统一 Excel 并发送通知] ``` -归档目录模板:`{归档根路径}/{yyyy}/{MM}/{invoice号}/`。同一 `invoice` 的多个文件必须集中在同一目录下。 +类型存放失败或归档复制失败属于技术失败,不可降级为缺件。固定目录扫描找不到文件记为缺件。 + +### 5.4 文档管理系统(已确认可复用) + +销售开票附件与采购合同附件使用**同一套文档管理系统**,不新造存储。 + +| 项 | 已确认内容 | +| --- | --- | +| 系统 | 文档管理系统(Web 文档库,路径形如 `文档库 > 销售开票附件 > {年} > {月}`) | +| 基址 | 复用现有 `CONTRACT_DMS_BASE_URL`(与合同付款文档库相同) | +| 登录接口 | `POST {基址}/Login/_api/Login`,body:`LoginName` / `Pwd` | +| 目录/文件查询 | `POST {基址}/Api/_api/APS/Public/Item/Page`(`LibraryID`、`ParentFolderID`、分页) | +| 建文件夹 | `POST {基址}/Api/_api/APS/Public/Item/SaveFolder`(`LibraryID`、`ParentFolderID`、`LeafName`、`FieldValues`) | +| 复制文件 | `POST {基址}/Api/_api/APS/Public/Item/Copy`(`ItemID` 数组、目标 `ParentFolderID`)。归档**禁止**使用 Move | +| 账号 | 复用现有 DMS 账号;用户名与密码只放环境变量/密钥注入,禁止写入代码、Profile JSON、Excel 或日志 | +| 库与目录 | 全公司只有一个文档库:`LibraryID` 与现网 `CONTRACT_DMS_LIBRARY_ID` 相同(`LibraryName` 为「文档库」)。「设备合同书」「销售开票附件」都是该库下的文件夹,**不要另配 LibraryID**。销售根目录单独配置 FolderID,**不得**复用合同根目录。现网销售根 FolderID 为 `727c3683-dcdb-4d62-a5b1-b164224162bc`(接口无 `FolderID` 字段,用条目 `ID` / `IDPath`) | + +下载、建文件夹、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;目标已有同名文件则跳过。仍不把凭据写入需求正文。 ## 6. 批量缺件汇总与企业微信通知 @@ -149,7 +213,7 @@ flowchart TD | 聚合 | 一个检核批次发送一条汇总通知;不在企业微信中逐票展开缺失明细 | | 内容 | 业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型、Excel 下载入口 | | 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 | -| 接收人 | 待业务确认;未配置接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | +| 接收人 | 业务可暂不指定具体人;**必须提供配置界面**,从 HXOPS 系统用户中多选(须已绑定企微 userid)。可复用管理后台排程任务的通知人选择器。未配置任何接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | | 技术失败 | 不作为缺件通知;按技术告警规则单独处理 | ## 7. 企业微信通知附件 Excel @@ -168,285 +232,23 @@ flowchart TD ## 8. 验收要点 -1. 每周任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 +1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 4. 企业微信每批仅发送一条缺件汇总通知,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 -6. 路径、ERP 查询条件等待确认项保持待确认,系统通过 Profile 配置承接,不能写死在通用逻辑中。 - ======= - -# 销售立账凭证检核一期需求说明 - -> 文档状态:需求梳理稿 -> -> 适用阶段:一期销售业务 -> -> 说明:本文用于确认业务范围、文件获取方式、归档规则和结果输出。各文件的具体扫描路径、目录名称、ERP 查询字段及自动化接口,待业务方继续补充后固化。 - -## 1. 需求概述 - -### 1.1 背景 - -立账凭证资料由不同业务方分别维护。不同业务方需要检核的文件数量、文件命名方式、获取方式和存放路径并不相同,因此不能继续按单一共享目录和固定文件清单进行扫描。 - -本期先建设销售业务的立账凭证资料检核流程,后续再扩展采购及其它业务方。 - -### 1.2 建设目标 - -| 目标 | 说明 | -| --------------- | ---------------------------------------------------------- | -| 周度增量检核 | 每周执行一次,仅处理上一个自然月内新增或发生变化的销售资料 | -| 多来源获取 | 支持 ERP、OA 和固定目录等不同文件来源 | -| 按 invoice 归档 | 同一 invoice 的相关文件集中放在同一归档目录 | -| 缺失可追踪 | 明确列出缺少的文件及查询、打印、复制失败原因 | -| 缺失通知 | 发现缺失文件后发送企业微信通知,提醒相关人员补齐资料 | -| 统一输出 | 将所有 invoice 和文件的处理结果汇总为一个 Excel | -| 可扩展 | 后续可以按业务方配置不同的文件清单和处理规则 | - -## 2. 业务范围 - -### 2.1 分期范围 - -| 阶段 | 业务方 | 范围 | -| ---- | ---------- | ---------------------------------------------------------------- | -| 一期 | 销售 | 检核销售立账凭证相关文件,获取并归档已找到的文件,输出统一 Excel | -| 二期 | 采购 | 待一期稳定后建设,文件清单和处理规则另行确认 | -| 后续 | 其它业务方 | 按业务方独立配置文件、路径和处理流程 | - -### 2.2 本期不包含 - -- 不处理采购及其它业务方的文件。 -- 不读取 PDF 或其它文件的业务内容。 -- 不校验金额、供应商、订单信息等字段是否一致。 -- 不使用 LLM 判断文件是否合格。 -- 不回写 ERP 或 OA 业务数据。 -- 不虚构尚未确认的扫描路径、目录名称和 ERP 查询字段。 - -## 3. 检核周期与处理范围 - -### 3.1 执行与检核口径 - -系统每周执行一次增量检核,检核范围始终为上一个自然月。每次执行只处理自上次成功执行后新增或发生变化的资料,避免重复处理已成功归档且未发生变化的文件。 - -| 执行时间 | 检核月份 | 执行方式 | -| ------------------ | ------------- | -------- | -| 2026 年 8 月任一周 | 2026 年 7 月 | 增量检核 | -| 2027 年 1 月任一周 | 2026 年 12 月 | 增量检核 | - -任务需要正确处理跨年场景,不能将执行所在月份误作为检核月份。进入新的自然月后,检核目标相应切换至新月份的上一个自然月。 - -### 3.2 检核主键 - -- 以销售 `invoice 号` 作为一组资料的核心关联标识。 -- 同一 invoice 下的 PO 订单、销货放行申请单、发票、报关资料、报关单和提单统一归档。 -- 一个 invoice 对应多个业务单号时,每个实际文件单独记录,但归档到同一 invoice 目录。 - -## 4. 销售文件配置总表 - -下表根据当前业务资料整理。标记为“待确认”的内容,在业务方补充抓取规则后更新。 - -| 文件类型 | 命名规则 | 获取/处理方式 | 扫描路径 | 扫描目录名称 | 归档路径 | invoice 关联方式 | 状态 | -| -------------- | -------------------------------- | --------------------------------------- | -------- | ------------------------------ | ---------------------------- | --------------------------------------- | ------------------------------------ | -| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 条件查询对应 PO,逐个打印并保存 PDF | 待确认 | `PO订单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 以上月 invoice 清单为入口,反查 PO 订单 | 获取方式已确认,查询条件待补充 | -| 报关资料 | `{invoice号}.pdf` | 从固定目录读取 | 待确认 | `报关资料/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表筛选后,逐条打印并保存 PDF | OA | `销货放行申请单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | OA 记录直接提供发票号和销货单号 | 获取流程已确认,打印及落盘细节待补充 | -| 发票 | `{invoice号}-{发票号}.pdf` | 从固定目录读取 | 待确认 | `销货单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 报关单 | `{invoice号}-{报关单号码}.pdf` | 从固定目录读取 | 待确认 | `报关单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 提单 | `{invoice号}-提单.pdf` | 从固定目录读取 | 待确认 | `提单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | - -> 说明:表中的 `{yyyy}`、`{MM}` 和 `{invoice号}` 为路径变量,分别表示检核月份的四位年份、两位月份和 invoice 号。实际归档根路径待确认。 - -## 5. 文件获取需求 - -### 5.1 OA 销货放行申请单 - -#### 5.1.1 OA 报表入口 - -```text -报表 → 流程报表 → 自定义报表 → 销货放行单 -``` - -#### 5.1.2 查询条件 - -| 条件 | 过滤要求 | 目的 | -| -------- | ------------ | --------------------------- | -| 申请日期 | 上一个自然月 | 限定本次月度检核范围 | -| 流程状态 | `归档` | 只处理已完成归档的流程 | -| 账套 | `HXJM` | 限定销售一期目标账套 | -| 发票号码 | 不为空 | 确保能够与 invoice 建立关联 | - -#### 5.1.3 处理流程 - -```mermaid -flowchart TD - A[进入 OA 自定义报表] --> B[选择销货放行单] - B --> C[设置申请日期为上月] - C --> D[流程状态=归档] - D --> E[账套=HXJM] - E --> F[发票号码不为空] - F --> G[获取过滤后的列表] - G --> H[读取发票号和销货单号] - H --> I{关联字段完整?} - I -->|否| J[跳过该条记录] - I -->|是| K[逐条打开申请单] - K --> L[打印并保存独立 PDF] - L --> M[按 invoice 号复制归档] - M --> N[汇总到 Excel] -``` - -#### 5.1.4 业务规则 - -- OA 过滤结果中的每一条申请单生成一个独立 PDF。 -- 发票号和销货单号直接从 OA 列表或申请单详情读取,不依赖 PDF OCR。 -- 文件名按 `{invoice号}-{销货单号}.pdf` 生成。 -- 发票号码为空的记录由 OA 查询条件排除,不进入打印流程。 -- 发票号或销货单号缺失时,直接跳过该条记录;不打印、不归档,也不记录字段异常。 -- 单条申请单打开、打印或保存失败时,继续处理其它申请单,并在 Excel 中记录失败原因。 - -### 5.2 ERP PO 订单 - -#### 5.2.1 处理流程 - -```mermaid -flowchart TD - A[获取上月销售 invoice 清单] --> B[按 invoice 查询 ERP] - B --> C{查询到 PO 订单?} - C -->|否| D[记录 PO 缺失] - C -->|是| E[获取 PO 订单号] - E --> F[逐个打开 PO 订单] - F --> G[打印并保存独立 PDF] - G --> H[按 invoice 号复制归档] - D --> I[汇总到 Excel] - H --> I -``` - -#### 5.2.2 业务规则 - -- 以上一个自然月的销售 invoice 清单作为 PO 查询入口。 -- 针对每个 invoice 在 ERP 中反查对应 PO 订单。 -- 每个 PO 订单生成一个独立 PDF。 -- 文件名按 `{invoice号}-{订单号}.pdf` 生成。 -- 一个 invoice 对应多个 PO 时,多个 PO 文件均归档到该 invoice 目录。 -- ERP 具体查询条件、字段名称、打印入口和登录方式待后续补充确认。 -- 查询无结果、订单字段缺失、打印失败或保存失败均需记录到统一 Excel。 - -## 6. 整体处理流程 - -```mermaid -flowchart TD - A[每周增量任务启动] --> B[确定上一个自然月] - B --> C[获取销售 invoice 清单] - C --> D[按文件类型执行独立获取规则] - D --> E{文件来源} - E -->|ERP| F[查询 PO 并打印 PDF] - E -->|OA| G[筛选销货放行单并逐条打印 PDF] - E -->|固定目录| H[按命名规则扫描文件] - F --> I[临时目录保存] - G --> I - H --> I - I --> J{文件名和 invoice 关联有效?} - J -->|否| K[记录获取或关联异常] - J -->|是| L[创建 invoice 归档目录] - L --> M[复制文件到归档目录] - M --> N{复制成功?} - N -->|否| O[记录复制失败] - N -->|是| P[记录文件成功] - K --> Q[汇总所有处理结果] - O --> Q - P --> Q - Q --> R[生成统一 Excel] -``` - -### 6.1 临时目录与归档目录 - -文件处理采用“先临时保存、后校验归档”的方式: - -1. ERP、OA 打印生成的文件先保存至本次任务的临时目录。 -2. 系统校验文件名、invoice 号和业务单号是否完整。 -3. 按下列规则创建 invoice 归档目录: - -```text -{归档根路径}/{yyyy}/{MM}/{invoice号}/ -``` - -4. 将获取成功的文件复制到对应 invoice 目录。 -5. 记录来源文件路径、归档文件路径和复制结果。 - -同一 invoice 的文件只能归档到该 invoice 对应目录,不同 invoice 之间不得混放。 - -### 6.2 异常处理 - -| 异常类型 | 处理方式 | 是否阻断其它数据 | -| -------------------- | -------------------------------------- | ----------------- | -| ERP 查询无 PO | 记录该 invoice 缺少 PO 订单 | 否 | -| OA 查询无销货放行单 | 记录该 invoice 缺少销货放行申请单 | 否 | -| 固定目录找不到文件 | 记录对应文件缺失 | 否 | -| 发票号或业务单号为空 | 记录关联字段异常,不归档无归属文件 | 否 | -| ERP/OA 查询接口失败 | 记录技术失败原因,按任务策略重试或补跑 | 其它 invoice 继续 | -| PDF 打印或保存失败 | 记录单文件失败 | 否 | -| 文件复制失败 | 记录来源路径和目标路径 | 否 | -| 归档根路径不可用 | 记录归档技术异常,并触发运维处理 | 由任务策略决定 | - -### 6.3 缺失文件企业微信通知 - -- 当任一 invoice 缺少应检文件时,系统需发送企业微信通知。 -- 通知内容至少包含检核月份、invoice 号、缺失文件类型、期望文件名和本次任务标识。 -- 企业微信通知用于提醒补齐资料,不替代统一 Excel 检核结果。 -- 单个 invoice 存在多个缺失文件时,应在同一条通知中汇总展示。 -- 通知接收人、通知频率和通知模板待业务方确认后配置。 - -## 7. 统一 Excel 结果 - -### 7.1 输出要求 - -- 每次周度增量任务生成一个统一 Excel。 -- Excel 同时包含成功、缺失、查询异常、打印异常和复制异常记录。 -- 记录粒度为“一个 invoice + 一种文件类型 + 一个实际文件”。 -- 一个 invoice 存在多个 PO 或多个销货放行申请单时,分别生成多行记录。 -- 缺失文件也必须生成记录,不能只输出成功文件。 - -### 7.2 建议字段 - -| 字段 | 说明 | -| ------------ | -------------------------------------------------- | -| 检核月份 | 上一个自然月,格式 `yyyy-MM` | -| 业务方 | 一期固定为销售 | -| invoice 号 | 资料归属的核心编号 | -| 文件类型 | PO 订单、报关资料、销货放行申请单等 | -| 业务单号 | 订单号、销货单号、报关单号码等 | -| 期望文件名 | 按规则生成的文件名或匹配规则 | -| 获取方式 | ERP、OA 或固定目录 | -| 查询条件摘要 | 实际使用的日期、状态、账套等条件 | -| 处理状态 | 成功、缺失、查询失败、打印失败、保存失败、复制失败 | -| 来源路径 | 原始文件或临时文件路径 | -| 归档路径 | 最终归档文件路径 | -| 错误原因 | 缺失或失败的具体说明 | -| 处理时间 | 文件处理完成时间 | - -## 8. 验收标准 - -| 编号 | 验收场景 | 验收要求 | -| ----- | ---------- | -------------------------------------------------------- | -| AC-01 | 月份计算 | 任务始终检核上一个自然月,跨年计算正确 | -| AC-02 | OA 过滤 | 只处理上月、归档、HXJM 且发票号码不为空的记录 | -| AC-03 | OA 关联 | 每条记录能够取得发票号和销货单号,并正确命名 PDF | -| AC-04 | ERP PO | 按 invoice 反查 PO,每个 PO 生成独立 PDF | -| AC-05 | 文件归档 | 同一 invoice 的文件全部进入同一目录,不同 invoice 不混放 | -| AC-06 | 异常继续 | 单个文件失败不影响其它文件和其它 invoice 继续处理 | -| AC-07 | 结果完整 | Excel 同时包含成功、缺失和失败记录 | -| AC-08 | 信息可追溯 | Excel 能够追溯来源路径、归档路径和失败原因 | +6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 反查与打印、OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 +7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。 ## 9. 待补充事项 -| 待确认项 | 负责补充内容 | -| ---------------------- | ---------------------------------------------------------- | -| 销售 invoice 清单来源 | ERP 查询入口、字段和筛选条件 | -| 各固定目录扫描路径 | 服务器/共享盘路径、访问方式和权限 | -| 各固定目录实际目录名称 | 年月目录层级及命名格式 | -| ERP PO 查询规则 | 查询字段、关联字段、账套和日期条件 | -| ERP 打印方式 | 页面入口、打印范围、分页和 PDF 保存方式 | -| OA 自动化细节 | 登录方式、分页方式、详情打开方式和打印接口 | -| 归档根路径 | 测试、生产环境的实际路径 | -| 重复执行规则 | 已归档文件的覆盖、跳过或版本保留策略 | -| 企业微信通知 | 缺失文件必须发送企业微信;待确认接收人、通知频率和通知模板 | +| 待确认项 | 当前结论 | 仍缺什么 | +| --- | --- | --- | +| 销售 invoice 清单 | **已确认**:HXJM `apa_file.apa08/apa09`,期间为上一个月 | 无 | +| ERP 反查 PO 并打印 | **待确认** | 查询字段、关联、打印入口、PDF 保存 | +| OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 | +| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy` | 无 | +| 企微接收人 | **已确认产品**:界面从系统用户多选;人可以后配 | 业务最终勾选哪些人 | +| 周任务 | **已确认**:每周二(默认 06:00 上海时区) | 无 | +| 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 | +| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 已有相同文件名则不覆盖,记已归档 | diff --git a/docs/features/accounting-voucher-check/dify-chatflow-draft.md b/docs/features/accounting-voucher-check/dify-chatflow-draft.md deleted file mode 100644 index d9015899..00000000 --- a/docs/features/accounting-voucher-check/dify-chatflow-draft.md +++ /dev/null @@ -1,196 +0,0 @@ -# 立账凭证检核 — Dify Chatflow 编排草稿 - -> **状态**:草稿(待 Dify 画布落地) -> **前提**:HXOPS Tool / 工作台 API 已就绪;本文件只约定意图 → Tool 映射与节点配置,不参与文件是否齐全的判定。 -> **参考**:文件检核 Chatflow 手册 [../file-check/technical.md](../file-check/technical.md) 第二部分;技术设计 [technical-design.md](technical-design.md) §12。 - ---- - -## 1. 设计原则 - -1. Dify **只做**意图识别、调 Tool、组织自然语言回复。 -2. **禁止**让 LLM 判断「文件在不在」或读取共享盘/附件内容。 -3. 启动检核复用现有 `POST /api/file-check/tools/tasks/run`,通过顶层 `mode` / `invoice_no` 区分模式(Dify 友好;亦兼容嵌套 `run_options`)。 -4. 缺资料/单票查询走 `/api/accounting-voucher-check/tools/*`。 -5. 进度卡仍走工作台 file-check 轮询链路(`ChatToolRun` 绑定 + `progress_metrics`)。 - ---- - -## 2. 意图清单 - -| 意图 code | 示例话术 | Tool | 关键参数 | -| --- | --- | --- | --- | -| `run_incremental` | 执行今日立账凭证检核 | `run_file_check` | 顶层 `mode=incremental` | -| `run_force_all` | 重新检核当月全部 | `run_file_check` | 顶层 `mode=force_all` | -| `run_single` | 检核发票 INV-xxx | `run_file_check` | 顶层 `mode=single` + `invoice_no` | -| `query_latest` | 查询最新检核结果 | `get_latest_file_check_run` | `task_id` | -| `query_run` | 查询批次 xxx | `get_file_check_run` | `run_id` | -| `query_missing` | 查询缺资料发票 | `list_voucher_missing` | `task_id`,可选 `period` | -| `query_invoice` | 发票 INV-xxx 检核结果 | `get_voucher_invoice_latest` | `invoice_no` | -| `capability` | 你能做什么 | (无 Tool) | 固定能力说明文案 | -| `fallback` | 无法识别 | (无 Tool) | 引导上述话术 | - ---- - -## 3. Tool 注册(建议 OpenAPI 操作) - -### 3.1 复用 file-check(已有) - -| operationId(建议) | Method / Path | 说明 | -| --- | --- | --- | -| `run_file_check` | `POST /api/file-check/tools/tasks/run` | Body 增加顶层 `mode` / `invoice_no`(兼容 `run_options`) | -| `get_file_check_run` | `GET /api/file-check/tools/runs/{run_id}` | 查批次 | -| `get_latest_file_check_run` | `GET /api/file-check/tools/tasks/{task_id}/latest-run` | 最新批次 | -| `download_file_check_excel` | `GET /api/file-check/tools/runs/{run_id}/excel` | Excel(可选,前端也可下) | - -> **Dify 注意**:部分版本对 OpenAPI **嵌套 object**(`run_options`)不展示输入框。请绑定顶层 `mode`、`invoice_no`。改完 OpenAPI 后须在 Dify **重新导入/更新** file-check 工具包。 - -`RunCheckRequest`(Dify 推荐写法): - -```json -{ - "task_id": 12, - "hxops_turn_id": "{{#ctx.hxops_turn_id#}}", - "conversation_id": "{{#sys.conversation_id#}}", - "user_message": "{{#sys.query#}}", - "mode": "incremental", - "invoice_no": null -} -``` - -### 3.2 本域新增(HXOPS 已实现,可 URL 导入) - -| operationId | Method / Path | 说明 | -| --- | --- | --- | -| `list_voucher_missing` | `GET /api/accounting-voucher-check/tools/tasks/{task_id}/missing` | Query: `period`, `limit` | -| `list_voucher_run_items` | `GET /api/accounting-voucher-check/tools/runs/{run_id}/items` | Query: `result`, `page` | -| `get_voucher_invoice_latest` | `GET /api/accounting-voucher-check/tools/invoices/{invoice_no}/latest` | Query: `period` | - -**Dify 导入**: - -```text -GET {HXOPS_TOOLS_API_BASE}/api/accounting-voucher-check/tools/openapi.json -``` - -鉴权与 file-check **同一密钥**:`FILE_CHECK_TOOL_API_KEY` 或 `INTEGRATION_API_KEY`(Bearer / `X-Integration-Key`)。`openapi.json` 本身无需鉴权。 - ---- - -## 4. 画布节点建议顺序 - -```text -开始 - → 解析运行态上下文(agent_runtime_context:task_id / hxops_turn_id) - → 意图识别 LLM(输出 intent + invoice_no?) - → 意图分支 - ├─ run_* → HTTP Tool 启动检核 → 回复「已启动,请看进度卡」 - ├─ query_latest → latest-run Tool → 摘要回复(齐全/缺资料/跳过) - ├─ query_missing→ missing Tool → 列表摘要 + 引导打开工作台记录 - ├─ query_invoice→ invoice latest Tool → 单票结论卡文案 - ├─ capability → 固定能力说明 - └─ fallback → 引导话术 - → 结束 -``` - -要点: - -- `task_id` 必须来自 **Agent 绑定的 `bound_schedule_task_id` / runtime refs**,禁止让用户随口编造或 LLM 瞎填。 -- `hxops_turn_id` 必传,保证进度卡能绑到本轮助手消息。 -- 启动成功后**不要**在 Chatflow 里同步轮询到结束;进度由前端 `ToolRunProgressCard` 负责。 - ---- - -## 5. 意图识别 Prompt 草稿 - -```text -你是「立账凭证检核」助手的意图分类器。只输出 JSON,不要解释。 - -可选 intent: -- run_incremental:执行今日/当月增量检核 -- run_force_all:重新检核当月全部(不跳过) -- run_single:检核指定发票(需抽取 invoice_no) -- query_latest:查最新检核结果 -- query_run:查指定批次(若用户给出 run_no/run_id,放入 run_ref) -- query_missing:查缺资料发票 -- query_invoice:查某发票最近结论(需 invoice_no) -- capability:询问能力 -- fallback:其它 - -规则: -1. 本助手只做「共享盘必检材料是否存在」,不核对金额/供应商,不回写 ERP。 -2. 无法确定发票号时,run_single / query_invoice 不要猜,改用 fallback 并追问。 -3. invoice_no 保持用户原文(仅去首尾空白),不要改写。 - -输出 schema: -{ - "intent": "...", - "invoice_no": null, - "run_ref": null, - "period": null -} -``` - -`[PARAM_TUNING]` 建议 Temperature ≤ 0.2,避免发散意图。 - ---- - -## 6. 回复文案要点(Answer 节点) - -| 场景 | 回复应包含 | -| --- | --- | -| 启动成功 | 已启动、批次号、提示查看进度卡(当月总数/待检/跳过/齐全/缺资料) | -| `check_running` | 已有任务执行中,请稍候或查最新结果 | -| 最新结果 | 月份、齐全/缺资料/跳过计数;有 Excel 则提示下载 | -| 缺资料列表 | 票数 + 前几张发票号 + 缺项;引导 `/workspace/accounting-voucher-check` | -| 单票 | 齐全或缺资料 + 缺项名;目录相对路径(勿暴露宿主机绝对路径) | -| 能力说明 | 明确「只查文件在不在」「不读内容」「不回写 ERP」 | -| 共享盘/ERP 失败 | 转述错误码友好文案,提示联系运维检查挂载/Oracle | - ---- - -## 7. Agent Registry 配置(HXOPS 侧) - -落地 Chatflow 时同步: - -| 项 | 建议值 | -| --- | --- | -| Agent 名称 | 立账凭证检核 | -| `bound_schedule_task_id` | `SCH-ACCOUNTING-VOUCHER-CHECK` 对应 id | -| `capabilities.task_progress` | `true` | -| Dify app | 本 Chatflow 应用 | -| 知识库同步 | 关闭(任务级 `kb_sync_enabled=false`) | - -进度展示:服务端已写 `progress_metrics`(齐全/缺资料等),前端进度卡自动切换,无需 RoHS 八格文案。 - ---- - -## 8. 联调检查单(Chatflow) - -- [ ] 话术「执行今日立账凭证检核」→ `mode=incremental`,进度卡出现 -- [ ] 「重新检核当月全部」→ `force_all`,完成后 `skipped_count=0` -- [ ] 「检核发票 {真实 apa08}」→ `single`,可跳过历史不影响 -- [ ] 「查询缺资料发票」→ missing Tool,列表与工作台一致 -- [ ] 运行中重复启动 → `check_running`,不双开批次 -- [ ] LLM 未被要求/未尝试判断文件内容 - ---- - -## 9. 与文件检核 Chatflow 的差异(编排时勿混) - -| 点 | 文件检核 | 立账凭证检核 | -| --- | --- | --- | -| 队列 | SRM 未检核 | ERP 当月发票清单 | -| 判定 | Dify Workflow/字段规则 | **仅 HXOPS 文件名存在性** | -| 启动 Body | 通常无 mode | **须传顶层 `mode`(单票再加 `invoice_no`)** | -| 历史知识库检索 | 有 | **无**(默认不入 KB) | -| 进度格 | 合格/不合格/人工 | 齐全/缺资料/跳过 | - ---- - -## 10. 落地待办(给编排同学) - -1. 在 Dify 新建独立 Chatflow(勿直接改 RoHS 画布)。 -2. 导入/配置上述 HTTP Tools(file-check + accounting-voucher-check)。 -3. 按 §4 搭意图分支与 Prompt。 -4. HXOPS 注册 Agent 并绑定排程任务。 -5. 用 §8 联调;通过后把本文状态改为「已落地」,并链到正式导出 OpenAPI(若另出 voucher OpenAPI 文件)。 diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index 9141466a..0b7fd610 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -1,8 +1,10 @@ -# 立账凭证检核 — 迁移与部署验收清单 +# 立账凭证检核 — 部署验收清单 -> 适用环境:dev / test / prod -> 前置文档:[technical.md](technical.md) · [technical-design.md](technical-design.md) -> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通日批/手动触发并看到进度与记录。 +> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `apa_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。 +> +> 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。 +> +> 适用环境:dev / test / prod ## 0. 变更摘要(上线前确认) @@ -10,27 +12,29 @@ | --- | --- | | Job key | `accounting-voucher-check` | | 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` | -| Cron | `0 6 * * *`(Asia/Shanghai) | -| 必检材料(暂定) | `核价单.pdf`、`采购单.pdf` | -| 迁移 revision | `a0b1c2d3e4f5` | +| Cron | `0 6 * * 2`(Asia/Shanghai,每周二 06:00) | +| 检核期间 | 上一个自然月 | +| 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 | +| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` | +| 已删除旧表 | `voucher_check_invoice_states`、`voucher_check_run_items`(revision `vc2b3c4d5e6f`) | +| 旧 job_params 清洗 | revision `vc3d4e5f6a7b`:去掉共享盘字段;启动种子同样幂等剥离 | | 工作台入口 | `/workspace/accounting-voucher-check` | --- ## 1. 数据库迁移 -- [ ] 备份目标库(至少 `schedule_tasks` / 相关 schema) +- [ ] 备份目标库 - [ ] 后端目录执行: ```bash cd backend -# 激活对应环境 venv flask db upgrade ``` -- [ ] 确认表存在: - - `voucher_check_invoice_states` - - `voucher_check_run_items` +- [ ] 确认引擎表存在:`voucher_check_profiles`、`voucher_check_runs`、`voucher_check_subjects`、`voucher_check_file_results`、`voucher_check_notifications` +- [ ] 确认旧表已删除:`voucher_check_invoice_states`、`voucher_check_run_items` +- [ ] 确认排程 `job_params` 仅含 `profile_code` / `scope_code` / 两个通知开关(无 `directory_template` / `required_files`) - [ ] 确认种子排程存在(有用户时): ```sql @@ -41,124 +45,112 @@ SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at ``` - [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建) -- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含必检材料 JSON +- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含 `profile_code=sales`、`scope_code=HXJM` --- ## 2. 环境变量 -写入 `.env.`(密码勿提交仓库): +写入 `.env.`(密码勿提交仓库)。文档库登录可复用 `CONTRACT_DMS_*`;销售开票附件根目录必须单独配置: ```bash -# 共享盘(Linux/容器必须 LOCAL_ROOT) -VOUCHER_CHECK_SHARE_UNC=\\192.168.100.230\ai_file\vouche -VOUCHER_CHECK_LOCAL_ROOT=/mnt/hxops-voucher-check-test # prod 换 prod 路径 -VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=.hxops-share-ready - -# Oracle(只读;DSN 可复用 ERP_DB_DSN) +# Oracle(只读;未单独配置 VOUCHER_CHECK_ERP_* 时复用 ERP_DB_DSN / ERP_USERNAME,再回退 CONTRACT_PAYMENT_ERP_*) VOUCHER_CHECK_ERP_DSN=${ERP_DB_DSN} VOUCHER_CHECK_ERP_USERNAME= VOUCHER_CHECK_ERP_PASSWORD= VOUCHER_CHECK_ERP_TIMEOUT_SECONDS=30 + +# 文档库(LibraryID 与合同相同;只单独配销售根 FolderID) +VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= +# 如需覆盖合同 DMS 登录: +# VOUCHER_CHECK_DMS_BASE_URL= +# VOUCHER_CHECK_DMS_LIBRARY_ID= +# VOUCHER_CHECK_DMS_USERNAME= +# VOUCHER_CHECK_DMS_PASSWORD= ``` 检查: -- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_*` +- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*` - [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中 +- [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除) --- -## 3. 共享盘挂载(当前阻塞项) +## 3. 排程与通知配置 -对齐固资履历思路:宿主机 CIFS → bind 进容器只读。 - -示意(路径按环境替换): - -```bash -# 宿主机 -sudo mkdir -p /mnt/hxops-voucher-check-test -# 使用只读 SMB 账号挂载 ai_file 或 vouche 子路径到 LOCAL_ROOT - -# 健康标记(根目录下) -sudo touch /mnt/hxops-voucher-check-test/.hxops-share-ready - -# 容器内验收 -docker exec hxops-backend test -f /mnt/hxops-voucher-check-test/.hxops-share-ready -docker exec hxops-schedule-worker test -f /mnt/hxops-voucher-check-test/.hxops-share-ready - -# 抽查当月目录(示例) -docker exec hxops-backend ls "/mnt/hxops-voucher-check-test/$(date +%Y)/$(date +%m)" | head -``` - -- [ ] backend 与 schedule-worker 均可读健康标记 -- [ ] 用真实 `apa08`(含 `+` 等特殊字符)抽查子目录名一致 -- [ ] Compose 已挂载 `/mnt/hxops-voucher-check-test|prod`(见根目录 `docker-compose.yml`) -- [ ] recreate backend + schedule-worker 使 env/volume 生效 - -> 未挂载或缺少健康标记时:批次应 **整批 failed**,且不写入业务「缺资料」单票状态。 - ---- - -## 4. 排程与通知配置 - -- [ ] 管理后台打开任务「立账凭证检核(日批)」 -- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * *` +- [ ] 管理后台打开任务「立账凭证检核(周批)」 +- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * 2` - [ ] `kb_sync_enabled=false`(本域不需要进知识库) -- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户 -- [ ] `job_params.required_files` 确认为核价单/采购单(或业务最终定稿) +- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户;未配置则不发 +- [ ] `job_params.profile_code=sales`,`scope_code=HXJM` --- -## 5. 功能冒烟 +## 4. 功能冒烟 -### 5.1 管理台手动跑一批(共享盘可用后) +### 4.1 管理台手动跑一批 - [ ] 「立即执行」创建 `ScheduleRun` -- [ ] `response_summary_json.voucher_check` 含 `complete_count` / `missing_count` / `skipped_count` -- [ ] Excel 可下载,表头含发票号/结论/缺失材料 -- [ ] `failed_count` **不含**缺资料票(仅技术异常) +- [ ] `response_summary_json.voucher_check` 含缺件文件数 / 缺件 invoice 数 +- [ ] Excel 可下载,以 invoice 为行、文件类型为列 +- [ ] 技术失败不计入缺件 -### 5.2 增量跳过 +### 4.2 增量与强制重检 -- [ ] 第一次跑后,第二次对未变更齐全票:`skipped_count > 0` -- [ ] 强制语义(会话/Tool `mode=force_all`):跳过为 0 +- [ ] 第一次跑后,第二次对未变更齐全票:跳过数 > 0 +- [ ] 工作台「强制重检上月」:`mode=force_all`,跳过为 0 +- [ ] 仅管理员可触发强制重检 -### 5.3 共享盘故障 - -- [ ] 临时移除健康标记或卸载挂载 -- [ ] 再跑:批次 `failed`,不产生批量 missing 状态覆盖 -- [ ] 企微失败告警到达(若开启) - -### 5.4 工作台记录页 +### 4.3 工作台记录页 - [ ] 打开 `/workspace/accounting-voucher-check` -- [ ] 可按月/状态/发票号筛选 -- [ ] 缺资料票的缺失材料列非空 +- [ ] 「检核任务」可按月/状态筛选,分页可用 +- [ ] 「企微发送记录」可按月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口 +- [ ] 「查看详情」进入 `/workspace/accounting-voucher-check/runs/:runId`(`runId` 为 ScheduleRun.id) -### 5.5 Tool API(可用 curl / Postman) +### 4.4 文档库 / ERP 故障 -```bash -# 启动(增量)— 复用 file-check -POST /api/file-check/tools/tasks/run -{ "task_id": , "run_options": { "mode": "incremental" }, "hxops_turn_id": "..." } +- [ ] DMS 或 ERP 不可用时批次 `failed`,不得把空结果批量判为缺件 +- [ ] 企微失败告警到达(若开启) -# 缺资料查询 -GET /api/accounting-voucher-check/tools/tasks//missing +--- -# 批次明细 -GET /api/accounting-voucher-check/tools/runs//items?result=missing +## 5. 在 jobs 表识别立账凭证检核 + +平台排程(含立账凭证)仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**,这是 worker 认领约定,不要按这两列区分业务。 + +升级后新入队的 Job: + +| 列 | 立账凭证检核示例 | +| --- | --- | +| `business_ref` | `schedule_run:{id}:accounting-voucher-check` | +| `payload_json.platform_api_path` | `accounting-voucher-check` | +| `payload_json.task_name` | `立账凭证检核` | +| `message` | `立账凭证检核等待后台执行` | + +```sql +SELECT id, status, business_ref, message, payload_json + FROM jobs + WHERE domain = 'schedule' + AND job_type = 'schedule_run' + AND ( + business_ref LIKE '%:accounting-voucher-check' + OR payload_json->>'platform_api_path' = 'accounting-voucher-check' + ) + ORDER BY id DESC + LIMIT 20; ``` -- [ ] 上述接口返回符合约定(Tool 非 envelope / 工作台 envelope) +Worker 日志关键字:`[voucher-check]` 或 `[schedule-run] name=立账凭证检核 path=accounting-voucher-check`。 --- ## 6. 回滚要点 -- [ ] 代码回滚后:可 `flask db downgrade` 到上一 revision(会删本域两表 + 种子 `schedule_no`) -- [ ] **勿**在有生产检核数据时贸然 downgrade;优先停用任务 `enabled=false` -- [ ] 共享盘挂载可保留,不影响其它服务 +- [ ] **勿**在有生产检核数据时贸然 `flask db downgrade`(会回建空的旧表,不恢复历史数据) +- [ ] 优先停用任务 `enabled=false` +- [ ] 旧共享盘挂载与 `VOUCHER_CHECK_SHARE_*` 已不再使用,可从宿主机/Compose 移除 --- @@ -167,6 +159,6 @@ GET /api/accounting-voucher-check/tools/runs//items?result=missing | 角色 | 确认项 | 签名/日期 | | --- | --- | --- | | 研发 | 迁移 + Job 注册 + 冒烟 | | -| 运维 | env + 挂载 + 双容器可读 | | -| 业务 | 必检文件名 + 通知接收人 | | -| 测试 | T1–T12 关键场景抽样 | | +| 运维 | env + DMS/ERP 连通 | | +| 业务 | 类型目录 + 通知接收人 | | +| 测试 | 周批 / 强制重检 / 企微记录抽样 | | diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index a2c789f9..28b841c7 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -1,9 +1,11 @@ # 立账凭证资料检核技术设计 -> 文档版本:v2.0 -> 更新时间:2026-08-18 -> 状态:目标设计,销售一期待实施;替代旧版“当月 + 单一共享盘 + 固定文件名”方案 +> 文档版本:v2.3 +> 更新时间:2026-09-08 +> 状态:销售一期引擎已落地;ERP PO / OA 打印仍待接线 > 需求基线:[demand.md](demand.md) +> +> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。 ## 1. 设计目标 @@ -13,7 +15,7 @@ | ------------ | ------------------------------------------------------------------------------------------------- | | 支持多业务方 | 新业务方优先新增 Profile,不在通用流程中增加销售/采购分支 | | 支持多来源 | 新文件来源通过 Adapter 接入,不将查询、打印、目录扫描逻辑写死在引擎中 | -| 支持周度增量 | 每周处理上一个自然月;以 `invoice + 文件规则` 的来源指纹和结果判断是否跳过 | +| 支持周度增量 | **每周二**处理上一个自然月;以 `invoice + 文件规则` 的来源指纹和结果判断是否跳过 | | 可审计 | 保存批次、单文件结果、归档结果、缺件汇总、通知状态与配置快照 | | 可汇总 | 明确区分缺件文件总数和缺件 `invoice` 数;通知 Excel 以 `invoice` 为行、以文件规则为动态状态列 | @@ -21,7 +23,7 @@ ```mermaid flowchart LR - Scheduler[周度排程 / 手动触发] --> Period[上月期间计算] + Scheduler[每周二排程 / 手动触发] --> Period[上月期间计算] Period --> Profile[加载已发布 Profile 快照] Profile --> Subjects[主体清单 Adapter] Profile --> Rules[文件规则] @@ -53,23 +55,23 @@ business_profiles/ 生产配置应存放于数据库或受控配置中心,以上目录仅表示逻辑结构;发布后的 Profile 必须生成不可变快照并绑定批次。 -| 配置项 | 说明 | -| -------------------------------------- | ------------------------------------------------------------------------ | -| `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | -| `subject_adapter` | 获取本期 `invoice` 主体清单的 Adapter 和参数 | -| `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | -| `notification` | 企业微信接收人、启用开关、模板、去重策略 | -| `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | +| 配置项 | 说明 | +| -------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | +| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `apa_file`(`apa08`/`apa09`),期间为上一个月 | +| `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | +| `notification` | 企业微信接收人、启用开关、模板、去重策略 | +| `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | ### 3.2 Adapter 契约 -| Adapter | 责任 | 统一输出 | -| -------------------------- | -------------------------------- | -------------------------------- | -| `subject_adapter` | 获取期间内应检主体及关联信息 | `invoice`、主体属性、来源指纹 | -| `erp_print_adapter` | 查询业务单据并打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `oa_report_adapter` | 按 OA 报表条件查询、逐条打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `directory_scan_adapter` | 扫描目录并匹配命名模板 | 匹配文件、扫描路径、来源指纹 | -| `cloud_drive_adapter` | 按接口检索和下载文件 | 文件临时路径、关联字段、来源指纹 | +| Adapter | 责任 | 统一输出 | +| -------------------------- | ----------------------------------------------------------------- | -------------------------------- | +| `subject_adapter` | 获取期间内应检主体及关联信息 | `invoice`、主体属性、来源指纹 | +| `erp_print_adapter` | 查询业务单据并打印 PDF | 文件临时路径、关联字段、来源指纹 | +| `oa_report_adapter` | 一期模拟 OA 页面查询并打印 PDF;预留新 OA 接口 | 文件临时路径、关联字段、来源指纹 | +| `directory_scan_adapter` | 扫描文档库类型目录并匹配命名模板(复用现网 DMS 登录与 Page 接口) | 匹配文件、扫描路径、来源指纹 | +| `cloud_drive_adapter` | 按接口检索和下载文件 | 文件临时路径、关联字段、来源指纹 | Adapter 不负责归档、Excel 或通知;引擎不理解 ERP/OA 的具体页面、SQL、目录规则。 @@ -86,7 +88,7 @@ flowchart TD F -- 否 --> H[调用来源 Adapter 获取文件] H --> I[校验 invoice 关联、命名和必填字段] I --> J{成功取得文件?} - J -- 是 --> K[复制至 invoice 归档目录] + J -- 是 --> K[写入类型目录并复制到所有归档/invoice] J -- 否,业务未找到 --> L[写入缺件] J -- 否,技术异常 --> M[写入技术失败] K --> N[写入已归档] @@ -95,149 +97,6 @@ flowchart TD M --> O N --> O O --> P[生成 Excel 与企业微信通知] -======= -# 立账凭证检核通用引擎技术设计 - -> 文档版本:v2.0 -> -> 更新时间:2026-08-14 -> -> 状态:重构设计,待研发评审 -> -> 需求基线:[demand.md](demand.md) -> -> 技术规格:[technical.md](technical.md) - -## 1. 设计目标 - -当前 `voucher_check` 实现按“单一 HXJM 账套、单一共享根目录、固定文件名、invoice 一票一状态”组织,无法覆盖销售和采购的多来源、多文件、多实例场景。 - -本次改造建立通用 `document_check` 引擎: - -- 以 `profile_code` 隔离销售、采购及后续业务方。 -- 以 `DocumentRule` 描述每种文件的业务规则。 -- 以 `SourceAdapter` 封装 ERP、OA、固定目录和其它系统差异。 -- 以 `CheckItem` 保存一个主体下一个文件规则实例的结果。 -- 复用现有排程、异步批次、Excel 下载、权限和企业微信基础能力。 - -## 2. 总体组件 - -```mermaid -flowchart LR - Schedule[ScheduleTask / 手动API] --> RunService[CheckRunService] - RunService --> ProfileRegistry[ProfileRegistry] - RunService --> SubjectLoader[SubjectLoaderRegistry] - RunService --> RuleExecutor[RuleExecutor] - RuleExecutor --> AdapterRegistry[SourceAdapterRegistry] - AdapterRegistry --> Directory[DirectoryScanAdapter] - AdapterRegistry --> ERP[ErpQueryPrintAdapter] - AdapterRegistry --> OAReport[OAReportPrintAdapter] - AdapterRegistry --> OARelation[OARelationPrintAdapter] - AdapterRegistry --> Upload[UploadDirectoryAdapter] - AdapterRegistry --> Payment[PaymentDownloadAdapter] - RuleExecutor --> Archive[ArchiveService] - RuleExecutor --> Repository[CheckRepository] - Repository --> Excel[ExcelExporter] - Repository --> Notify[WeComNotificationService] -``` - -## 3. 代码目录 - -```text -backend/app/ -├── domains/document_check/ -│ ├── profiles/ -│ │ ├── registry.py -│ │ ├── schema.py -│ │ ├── loader.py -│ │ ├── sales.yaml -│ │ └── procurement.yaml -│ ├── engine/ -│ │ ├── context.py -│ │ ├── run_service.py -│ │ ├── incremental_service.py -│ │ ├── subject_loader.py -│ │ ├── rule_executor.py -│ │ └── result_aggregator.py -│ ├── sources/ -│ │ ├── base.py -│ │ ├── models.py -│ │ ├── registry.py -│ │ ├── directory_scan.py -│ │ ├── erp_query_print.py -│ │ ├── oa_report_print.py -│ │ ├── oa_relation_print.py -│ │ ├── upload_directory_scan.py -│ │ └── payment_download.py -│ ├── archive/ -│ │ ├── archive_service.py -│ │ ├── path_renderer.py -│ │ └── fingerprint.py -│ ├── persistence/ -│ │ ├── models.py -│ │ └── repository.py -│ ├── exporters/ -│ │ └── excel_exporter.py -│ └── notifications/ -│ └── wecom.py -├── api/ -│ ├── document_check.py -│ └── workspace_document_check.py -└── schedule/ - └── document_check_job.py - -frontend/src/features/document-check/ -├── api/document-check.api.ts -├── composables/useDocumentCheckRuns.ts -├── views/DocumentCheckPage.vue -├── components/CheckProgressCard.vue -├── components/CheckResultTable.vue -└── components/MissingFilesPanel.vue -``` - -## 4. Profile Schema - -Profile 建议首期使用仓库内版本化 YAML/JSON,避免在业务规则尚未稳定时直接引入复杂管理后台。后续可把同一 Schema 存入数据库。 - -```yaml -code: sales -name: 销售立账凭证 -version: 2026-08-14.1 -enabled: true -subject_loader: - type: erp_invoice - config: - scope_code: HXJM - date_field: invoice_date -period_policy: - type: previous_month -archive_policy: - root_env: DOCUMENT_CHECK_ARCHIVE_ROOT - template: "{root}/{YYYY}/{MM}/{invoice_no}/" -incremental_policy: - enabled: true - fingerprint_fields: [name, size, mtime_ns] - retry_statuses: [missing, query_failed, print_failed, copy_failed] -notification_policy: - missing_enabled: true - recipient_keys: [] - dedup_scope: invoice_period -documents: - - code: shipping_release - name: 销货放行申请单 - required: true - source_type: oa_report_print - source_config: - report_name: 销货放行单 - filters: - application_date: previous_month - process_status: 归档 - scope_code: HXJM - invoice_no: not_empty - filename_template: "{invoice_no}-{shipment_no}.pdf" - relation_keys: [invoice_no, shipment_no] - incomplete_relation_policy: skip ->>>>>>> Stashed changes ``` ### 4.1 增量判定 @@ -252,15 +111,18 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ## 5. 归档与结果模型 -### 5.1 归档规则 +### 5.1 存放与归档规则 -文件先放入临时目录,完成 `invoice` 关联、命名和文件完整性校验后,复制到: +销售开票附件在文档库中分两步落盘(路径以销售 Profile 配置,默认与文档库现状一致): ```text -{archive_root}/{yyyy}/{MM}/{invoice}/ +存放:文档库/销售开票附件/{yyyy}/{MM}/{类型目录}/ +归档:文档库/销售开票附件/{yyyy}/{MM}/所有归档/{invoice}/ ``` -同一 `invoice` 的所有成功资料必须集中在同一目录。复制失败属于技术失败,不可降级为缺件。 +类型目录与一期文件对应(**已确认固定,不改名**):`PO订单`、`报关资料`、`销货单`(销货放行申请单)、`发票`、`报关单`、`提单`。 + +ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。 ### 5.2 建议持久化实体 @@ -274,6 +136,8 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 `voucher_check_file_results` 是缺件统计和 Excel 明细的真相源;不得仅保存 `invoice` 级结论,否则无法正确统计同一 `invoice` 的多个缺件。 +旧表 `voucher_check_invoice_states` / `voucher_check_run_items` 已由迁移 `vc2b3c4d5e6f` 删除,不得再恢复为写入目标。 + ## 6. 批量缺件统计 ### 6.1 统计口径 @@ -294,7 +158,7 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ### 6.2 通知聚合 -通知以 `run_id` 聚合:一个检核批次仅生成一条企业微信汇总消息,展示业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数和主要缺失文件类型,并提供该批 Excel 下载入口。消息正文不得逐票展开全部 `invoice` 或缺失文件;完整清单由 Excel 和执行记录承载。未配置接收人时不发送空消息,保存未发送原因。技术失败进入独立运维告警,不混入缺件通知。 +通知以 `run_id` 聚合:一个检核批次仅生成一条企业微信汇总消息。接收人由任务配置界面从系统用户多选(须已绑定企微);未配置则不发送并记录原因。技术失败进入独立运维告警,不混入缺件通知。 ### 6.3 检核任务列表 @@ -337,18 +201,19 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ## 9. 实施顺序 -1. 建立 Profile、文件规则、批次、单文件结果和通知审计模型,并提供销售 Profile 配置。 -2. 实现通用期间计算、增量决策、归档器、统计聚合器和 Excel 生成器。 -3. 接入销售主体、OA 销货放行申请单、ERP PO 和目录扫描 Adapter;路径/ERP 条件确认后发布。 -4. 接入企业微信通知和执行记录工作台。 -5. 采购通过新增 Profile 和 Adapter 参数接入;新来源系统再新增 Adapter。 +1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表与企微发送记录。 +2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。 +3. **已预留**:`erp_po_print`、`oa_sales_release` Adapter,周任务不调用。 +4. 接入 ERP PO 打印与 OA 模拟页,作为独立抓取任务写入类型目录。 +5. 采购通过新增 Profile 和 Adapter 参数接入。 ## 10. 验收重点 - 一次批次中多个 `invoice` 缺件、且单个 `invoice` 缺多个文件时,两个缺件指标均正确。 - Excel 报告以“资料所属期间”筛选,顶部单独展示“执行时间”;每个 `invoice` 一行,动态文件列与 Profile 必检规则一致;所有文件列均为“有”时状态为“完整”。 - 企业微信每批发送一条汇总通知并提供 Excel 下载入口;完整 `invoice` 明细仅在 Excel 和执行记录中查看。 -- 周度任务仅处理上一个自然月;增量、强制重检和跨年期间计算正确。 +- 每周二任务仅处理上一个自然月;增量、强制重检和跨年期间计算正确。 +- 企微接收人可从系统用户配置;未配置不发空通知。 - 新增采购或其它业务方无需修改通用检核、汇总、Excel 和通知逻辑。 - Profile 加载后必须生成不可变快照,批次全程使用同一版本。 - `source_type` 必须在 Adapter Registry 注册。 @@ -356,297 +221,21 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 - 配置错误在批次开始前失败,不产生批量业务缺失结果。 - 密码、Token、Cookie 不允许出现在 Profile 文件、数据库 JSON、Excel 或日志中。 -## 5. 核心接口 +## 11. 与旧实现的差异(已完成清理) -### 5.1 检核上下文 +当前 `backend/app/services/voucher_check/` 按本期引擎运行。与旧共享盘方案的差异: -```python -@dataclass(frozen=True) -class CheckContext: - profile_code: str - profile_version: str - period_month: date - run_id: int - mode: str - temp_root: Path - archive_root: Path -``` +| 旧实现 | 当前实现 | +| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | +| 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** | +| HXJM `apa_file.apa08/apa09` 拉发票清单 | **沿用该口径**,仅把期间改为上一个月 | +| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(ERP/OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | +| 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 | +| 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel | +| Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` | -### 5.2 检核主体 +约束: -```python -@dataclass(frozen=True) -class CheckSubject: - subject_type: str - subject_key: str - invoice_no: str | None - relation_values: dict[str, str] - source_metadata: dict[str, Any] -``` - -`relation_values` 用于保存 `shipment_no`、`po_no`、`delivery_no` 等业务关联字段;禁止把不同业务方字段硬编码到统一表列中。 - -### 5.3 来源 Adapter - -```python -class SourceAdapter(Protocol): - source_type: str - - def fetch( - self, - context: CheckContext, - rule: DocumentRule, - subject: CheckSubject, - ) -> list[ArtifactCandidate]: - """返回候选文件;不得写最终归档目录。""" -``` - -Adapter 返回的 `ArtifactCandidate`: - -```python -@dataclass(frozen=True) -class ArtifactCandidate: - artifact_key: str - filename: str | None - temporary_path: Path | None - source_path: str | None - relation_values: dict[str, str] - fingerprint: str | None - status: str - error_code: str | None = None - error_message: str | None = None -``` - -Adapter 只负责查询/下载/打印和返回候选文件;命名校验、归档、落库由通用引擎负责。 - -### 5.4 Profile Registry - -```python -class ProfileRegistry(Protocol): - def get(self, profile_code: str, version: str | None = None) -> ProfileSnapshot: - ... - - def list_enabled(self) -> list[ProfileSummary]: - ... -``` - -## 6. 执行编排 - -### 6.1 主流程 - -```python -def run_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - profile = profile_registry.get(run.profile_code) - context = build_context(profile, run) - subjects = subject_loader_registry.load(context, profile.subject_loader) - - for subject in subjects: - for rule in profile.documents: - if incremental_service.can_skip(context, subject, rule): - repository.save_skipped(context, subject, rule) - continue - candidates = adapter_registry.get(rule.source_type).fetch(context, rule, subject) - items = rule_executor.evaluate(context, subject, rule, candidates) - repository.save_items(items) - - archive_service.finalize(context) - excel_exporter.export(context) - notification_service.notify_missing(context) - return result_aggregator.to_schedule_result(context) -``` - -### 6.2 Adapter 结果统一化 - -| Adapter 状态 | 统一结果 | 说明 | -| ---------------------- | -------------------------------------- | --------------------------------------------- | -| 找到候选文件 | `found` | 尚未完成归档 | -| 找不到业务文件 | `missing` | 正常业务缺件 | -| 查询无记录 | `missing` | 由 Profile 指定是否为必缺 | -| 外部系统超时/登录失败 | `query_failed` | 技术失败,可重试 | -| 打印或保存 PDF 失败 | `print_failed` | 技术失败,可重试 | -| 文件名或关联字段不完整 | 由 `incomplete_relation_policy` 决定 | `skip` 不生成检核项;其它策略可记录处理失败 | -| 复制归档失败 | `copy_failed` | 保留源、目标和错误信息 | - -## 7. 持久化设计 - -建议新增或改造以下表。最终字段以模型评审和迁移脚本为准。 - -### 7.1 `document_check_profiles` - -| 字段 | 说明 | -| ------------------------------- | ------------------ | -| `code` | Profile 编码,唯一 | -| `name` | 业务方名称 | -| `version` | 配置版本 | -| `config_json` | 非敏感配置快照 | -| `enabled` | 是否启用 | -| `created_at` / `updated_at` | 审计时间 | - -### 7.2 `document_check_runs` - -| 字段 | 说明 | -| -------------------------------------- | ------------------------------------------- | -| `id` | 批次 ID | -| `profile_code` / `profile_version` | 本批次使用的 Profile | -| `period_month` | 检核月份 | -| `mode` | incremental / force_all / single | -| `status` | running / success / partial_failed / failed | -| `summary_json` | 统计和阶段信息 | -| `excel_file_*` | 复用现有下载字段或关联文件资产 | - -### 7.3 `document_check_subjects` - -保存本批次主体快照,避免外部系统后续变化导致历史结果无法解释。 - -### 7.4 `document_check_items` - -建议唯一约束: - -```text -(profile_code, period_month, subject_key, rule_code, artifact_key) -``` - -保存期望文件、来源类型、实际关联字段、状态、错误、指纹和最后成功批次。 - -### 7.5 `document_check_artifacts` - -保存来源、临时文件、归档文件和指纹。文件路径字段必须经过脱敏展示策略,避免把敏感 UNC 凭据写入前端或通知。 - -### 7.6 `document_check_notifications` - -保存 `dedup_key`、接收人、通知内容摘要、发送状态和失败原因,支撑每周增量重复通知控制。 - -## 8. 增量与幂等 - -### 8.1 跳过条件 - -只有同时满足以下条件才允许跳过: - -- 上次文件状态为 `archived`。 -- Profile 版本一致。 -- 文件规则版本或模板指纹一致。 -- 来源指纹一致。 -- 归档目标仍存在且指纹一致。 - -### 8.2 重试条件 - -以下状态每周自动重试: - -```text -missing / query_failed / print_failed / copy_failed / technical_error -``` - -缺件不阻断其它主体;批次只有在配置、数据库或核心基础设施故障时才进入批次失败。 - -### 8.3 外部操作幂等 - -- OA/ERP 打印前根据 `artifact_key` 检查当前批次临时文件,避免重复打印。 -- 归档目标相同指纹时直接复用。 -- 目标存在但指纹不同,按 Profile 的 `overwrite_policy` 处理:默认保留原文件并记录版本,禁止静默覆盖。 -- 同一批次并发启动使用现有 ScheduleRun 锁,同时 Profile 维度增加 running 检查。 - -## 9. API 与兼容层 - -### 9.1 新 API - -```text -POST /api/document-check/runs -GET /api/document-check/runs/{run_id} -GET /api/document-check/runs/{run_id}/items -GET /api/document-check/runs/{run_id}/excel -GET /api/document-check/missing -GET /api/document-check/profiles -``` - -启动请求: - -```json -{ - "profile_code": "sales", - "mode": "incremental", - "period": "2026-07" -} -``` - -### 9.2 错误契约 - -继续使用 `{success, data | error, request_id}` envelope;业务错误使用 `AppError` 子类。建议新增: - -| 错误码 | 含义 | -| -------------------------------------- | ----------------------------- | -| `DOCUMENT_CHECK.PROFILE_NOT_FOUND` | Profile 不存在或未启用 | -| `DOCUMENT_CHECK.PROFILE_INVALID` | Profile 校验失败 | -| `DOCUMENT_CHECK.ADAPTER_NOT_FOUND` | 来源 Adapter 未注册 | -| `DOCUMENT_CHECK.SOURCE_UNAVAILABLE` | 外部来源不可用 | -| `DOCUMENT_CHECK.ARCHIVE_UNAVAILABLE` | 归档路径不可用 | -| `DOCUMENT_CHECK.RUN_ALREADY_RUNNING` | 同 Profile 和期间已有运行批次 | - -新增错误码需要同步四语言 `locales/*/errors.json`。 - -### 9.3 旧接口兼容 - -现有 `/api/accounting-voucher-check/*` 和 `/api/file-check/tools/tasks/run` 在迁移期间保留: - -- 旧入口默认映射 `profile_code=sales`。 -- 旧的 `invoice_no` 参数映射为 `subject_key`。 -- 旧查询结果转换为通用 `CheckItem` 视图。 -- 销售迁移验证完成后,再评估下线旧接口。 - -## 10. 前端与通知 - -- 工作台页面改为读取 Profile 名称和 DocumentRule 元数据,不写死采购单、核价单等文件名称。 -- 结果表以 `document_type`、`status`、`business_no` 和 `archive_path` 为通用列。 -- 每周增量进度展示主体总数、文件规则总数、已处理、跳过、缺失和技术失败。 -- 企业微信缺件通知按 invoice 合并,接收人从 Profile 的通知配置解析;接收人待定时显示未发送原因。 -- 文件缺失和技术失败分开展示,不能把 OA 登录失败显示为缺件。 - -## 11. 测试设计 - -### 11.1 单元测试 - -- Profile Schema 校验、版本快照和非法模板。 -- Adapter Registry 注册、未知类型和参数校验。 -- 文件名、路径和关联字段渲染。 -- 多实例 `artifact_key` 生成和重复去重。 -- 增量跳过、失败重试、Profile 版本变化和归档指纹变化。 - -### 11.2 Adapter 合约测试 - -每个 Adapter 统一覆盖: - -- 成功返回候选文件。 -- 业务无记录返回 `missing`。 -- 外部系统异常返回明确技术状态。 -- 临时文件隔离和失败清理。 -- 重试不产生重复业务实例。 - -### 11.3 集成测试 - -- 销售 Profile 混合 OA、ERP 和固定目录来源。 -- 采购 Profile 混合固定目录、OA 关联和付款下载来源。 -- 同一 invoice 多个 PO/送货单归档不互相覆盖。 -- 一条文件缺失时其它文件继续处理并触发企业微信通知。 -- 接收人未配置时不调用发送接口但保留审计记录。 - -## 12. 实施顺序 - -1. 定义 Profile Schema、Adapter 契约和通用状态枚举。 -2. 新增通用 Profile/Adapter Registry 和配置校验。 -3. 新增单文件级数据模型及迁移脚本。 -4. 把现有共享盘扫描封装为 `directory_scan` Adapter。 -5. 建立销售 Profile,完成销售回归和旧接口兼容。 -6. 接入 OA/ERP Adapter,补齐销售打印流程。 -7. 建立采购 Profile,接入采购所需来源。 -8. 迁移 Excel、企业微信通知和工作台查询到通用 API。 -9. 运行新旧结果对比,确认无误后下线旧单票专用逻辑。 - -## 13. 风险与控制 - -| 风险 | 控制措施 | -| ---------------------------- | -------------------------------------------------- | -| Profile 配置错误导致大批缺件 | 启动前 Schema 校验、Profile 版本和小范围试运行 | -| OA/ERP 打印不稳定 | Adapter 超时、重试、临时目录和可恢复状态 | -| 多文件实例覆盖 | `artifact_key` 唯一键和默认不覆盖策略 | -| 缺件通知重复 | `dedup_key` 按 Profile、期间、invoice 和规则生成 | -| 旧接口改造影响现有 Agent | 保留兼容层,内部映射到销售 Profile | -| 敏感路径和账号泄露 | 凭据仅 env/secret,日志和 Excel 脱敏 | +- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。 +- 不得再写入 `voucher_check_invoice_states` / `voucher_check_run_items`。 +- 部署与冒烟见 [ops-checklist.md](ops-checklist.md)。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index 502e839b..9fdaefa2 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -1,24 +1,11 @@ -# 立账凭证检核 — 历史方案归档 - -> **已废弃**:本文记录旧版“当前自然月 + 单一共享盘 + 固定文件名”的实现方案,不再作为需求或技术设计依据。当前业务需求见 [demand.md](demand.md),新版技术设计见 [technical-design.md](technical-design.md)。 - # 立账凭证检核技术规格 ->>>>>>> Stashed changes ->>>>>>> ->>>>>> ->>>>> ->>>> ->>> ->> - -> 文档状态:重构设计基线 -> +> 文档状态:销售一期规格基线 > 适用范围:销售一期、采购二期及后续其它业务方 +> 需求基线:[demand.md](demand.md) +> 落地设计:[technical-design.md](technical-design.md) > -> 需求基线:[销售一期需求说明](demand.md) -> -> 本文描述通用实现目标。当前已有的单一共享盘实现仅作为迁移对象,不再作为新业务方扩展的结构基础。 +> 本文描述通用实现目标。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘扫描与一票一状态表已移除。 ## 1. 设计结论 @@ -105,7 +92,7 @@ Profile 是一个可版本化的业务方配置快照,至少包含: | `subject_loader` | 检核主体加载器,如 ERP invoice 清单、业务清单 | | `period_policy` | 上月周期和跨年计算规则 | | `documents` | 文件规则集合 | -| `archive_policy` | 归档根路径和目录模板 | +| `archive_policy` | 类型存放路径与「所有归档/{invoice}」模板 | | `incremental_policy` | 指纹、重试和跳过策略 | | `notification_policy` | 缺件通知开关、接收人和去重策略 | | `enabled` | 是否允许执行 | @@ -375,26 +362,29 @@ sequenceDiagram ## 8. 归档与文件安全 -默认归档模板: +默认存放与归档模板(销售文档库): ```text -{archive_root}/{YYYY}/{MM}/{invoice_no}/ +{dms_root}/销售开票附件/{YYYY}/{MM}/{类型目录}/ +{dms_root}/销售开票附件/{YYYY}/{MM}/所有归档/{invoice_no}/ ``` 要求: -- 所有生成或扫描的文件先进入任务隔离的临时目录,再校验关联字段和命名后归档。 -- 同一 invoice 的所有文件进入同一目录;不同 invoice 不得混放。 -- 复制采用幂等策略,目标文件相同指纹时跳过,指纹不同按 Profile 的覆盖策略处理。 +- ERP/OA 打印或目录扫描的成功文件先写入当月类型存放目录,再校验关联字段和命名后复制到「所有归档/{invoice_no}/」。 +- 同一 invoice 的所有文件进入同一归档子目录;不同 invoice 不得混放。 +- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。归档只 `Copy`、不 `Move`。 - `invoice_no`、业务单号和路径变量必须做路径穿越校验。 - 临时目录和日志不得输出密码、Token 或完整外部系统会话信息。 - 归档记录保存来源路径、临时路径、归档路径、指纹、Profile 版本和处理时间。 ## 9. Excel 与企业微信通知 -### 9.1 Excel +执行记录可按「一个 invoice + 一种文件类型 + 一个实际文件」保留明细。企业微信通知附件 Excel **不**使用该明细表结构,口径见 [demand.md](demand.md) §7:一张「检核结果」工作表,一行一个 `invoice`,按 Profile 动态展开「有 / 缺件 / 未检核」。 -一批次生成一个统一 Excel,记录粒度为“主体 + 文件规则 + 文件实例”: +### 9.1 执行记录字段(审计用,不是企微附件) + +一批次的执行记录粒度为“主体 + 文件规则 + 文件实例”: | 字段 | 说明 | | --------------------- | ---------------------------- | @@ -416,11 +406,11 @@ sequenceDiagram ### 9.2 缺件企业微信通知 -- 任一必检文件状态为 `missing` 时发送企业微信通知。 -- 同一 invoice 的多个缺件合并通知。 -- 通知至少包含业务方、检核月份、invoice 号、缺失文件和批次号。 -- 接收人、通知模板、发送频率和去重规则由 Profile 的 `notification_policy` 管理。 -- 当前业务接收人待定,未配置接收人时必须在批次日志和 Excel 中保留“未发送原因”。 +- 本批存在必检文件缺件时发送企业微信。 +- **一个检核批次只发一条汇总通知**,不在消息正文逐票展开缺失明细。 +- 通知至少包含业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型和本批 Excel 下载入口。 +- 完整 `invoice` 与缺失文件清单以企微附件 Excel 和执行记录为准。 +- 接收人、通知模板由 Profile 的 `notification_policy` 管理;未配置接收人时不发送空通知,并在批次日志和 Excel 中保留未发送原因。 - 技术失败使用独立失败告警,不应伪装成业务缺件。 ## 10. API、任务和前端影响 @@ -498,11 +488,11 @@ backend/app/domains/document_check/ 迁移顺序: 1. 先建立 Profile Schema、Adapter 契约和单文件数据模型。 -2. 将现有销售共享盘扫描逻辑封装为 `directory_scan` Adapter。 +2. 销售文档扫描走 `dms_directory_scan` Adapter(文档库类型目录),不再封装旧共享盘扫描。 3. 将销售 invoice 主体加载和 OA/ERP 获取逻辑分别封装为 Loader/Adapter。 -4. 保留旧 `voucher_check` API 兼容层,内部调用通用引擎。 +4. 工作台 API 只读引擎表;已删除 Chatflow Tool 与旧 states 接口。 5. 完成销售回归后增加采购 Profile 和采购专用 Adapter。 -6. 最后清理只服务旧模型的单票状态、单一共享根配置和重复接口。 +6. 已清理只服务旧模型的单票状态、单一共享根配置和重复接口。 ## 12. 测试与验收 @@ -517,7 +507,7 @@ backend/app/domains/document_check/ - 固定目录命中、缺失、路径不可用和大小写规则。 - ERP/OA 查询成功、无结果、超时、登录失败和分页。 - ERP/OA 每个业务单生成独立 PDF,正确返回 invoice 和业务单关联字段。 -- Adapter 重试不产生重复归档文件。 +- Adapter 重试不产生重复归档文件:目标已有同名则跳过复制。 ### 12.3 增量与归档 @@ -528,21 +518,21 @@ backend/app/domains/document_check/ ### 12.4 结果与通知 -- Excel 同时包含成功、跳过、缺失和技术失败记录。 -- 同一 invoice 多个缺件合并企业微信通知。 -- 接收人未配置时不发送空通知,并记录明确原因。 +- 企微附件 Excel 一行一个 `invoice`,动态文件列为「有 / 缺件 / 未检核」;执行记录可另存单文件明细。 +- 同一批次多个 `invoice` 缺件、同一 `invoice` 缺多个文件时,缺件文件总数累计、缺件 `invoice` 数去重。 +- 企业微信每批一条汇总通知,提供 Excel 下载入口;接收人未配置时不发送空通知,并记录明确原因。 - 批次级技术故障不批量伪装成缺件。 ## 13. 待确认事项 | 事项 | 当前状态 | | -------------------------------- | ------------------------------------------------ | -| 销售各固定目录路径 | 待确认 | +| 销售开票附件文档库路径 | 已确认固定:`销售开票附件/{年}/{月}/{类型目录}`,类型目录为 `PO订单`/`报关资料`/`销货单`/`发票`/`报关单`/`提单`,归档 `所有归档/{invoice}` | | 采购各固定目录路径 | 待确认 | -| 销售 invoice 主体来源与 ERP 字段 | 待确认/需适配现有来源 | +| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `apa_file` `apa08`/`apa09`,期间上一个月 | | 采购 invoice 主体来源 | 待确认 | -| ERP PO 查询字段与打印方式 | 待确认 | -| OA 登录、报表分页和打印接口 | 待确认 | -| 归档根路径及重复文件策略 | 待确认 | -| 企业微信通知接收人、模板和频率 | 待确认 | +| ERP PO 查询字段与打印方式 | **待确认** | +| OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 | +| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy`;同名跳过 | +| 企业微信通知接收人、模板和频率 | 界面从系统用户多选;每周二;具体人选可后配 | | Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 | diff --git a/docs/features/faq/faq_cache_ops_manual.md b/docs/features/faq/faq_cache_ops_manual.md index 58d078c1..451b8792 100644 --- a/docs/features/faq/faq_cache_ops_manual.md +++ b/docs/features/faq/faq_cache_ops_manual.md @@ -64,7 +64,7 @@ flowchart TD A[用户发消息 chat.py] --> B{有附件?} B -->|是| Z[跳过 FAQ,走业务路由] B -->|否| C[FaqCacheService.try_match] - C --> D{agent 全局 FAQ
cache_enabled=true
is_enabled=true
stale_at 为空
未过期?} + C --> D{agent 全局 FAQ
cache_enabled=true
stale_at 为空
未过期?} D -->|否| E[未命中 → Dify 等] D -->|是| F{归一化问句匹配
question / title / aliases?} F -->|否| E @@ -283,6 +283,7 @@ FAQ_HOT_BAD_SCORE=2 | --- | --- | | 新建/编辑 | 填写 question、answer、aliases;开启「启用缓存」 | | 关闭缓存 | `cache_enabled=false` 后不再在线命中,但不删 ChatLog | +| 关闭前台展示 | `is_enabled=false` 后工作台首页不显示快捷入口,**不影响** FAQ 缓存命中 | | 设置过期 | `expires_at` 到期后 `try_match` 自动跳过 | | 查看命中 | 列表字段 `hit_count` | diff --git a/docs/features/hr-system/AI知识库对接HR系统.md b/docs/features/hr-system/AI知识库对接HR系统.md new file mode 100644 index 00000000..e7ceb3f4 --- /dev/null +++ b/docs/features/hr-system/AI知识库对接HR系统.md @@ -0,0 +1,66 @@ +# AI知识库对接HR系统 + +- DB:192.168.100.191:1433 +- UserName:AI\_Knowledge\_Base\_Hr +- Password:hoo-thai\@123\_AI\_HR +- 默认数据库:NH\_N8\_HEXIN + +## 用途:年假记录表 + +- 视图:VIEW\_D044 + \| 字段名称 | 类型 | 长度 | 字段说明 | + \| --- | --- | --- | --- | + \| c001001 | nvarchar | 200 | 部门编号 | + \| c001002 | nvarchar | 200 | 部门名称(小部门) | + \| a008003 | nvarchar | 200 | 上级部门名称(大部门) | + \| c002001 | nvarchar | 200 | 员工工号 | + \| c002002 | nvarchar | 200 | 员工姓名 | + \| d072001 | int | - | 年份 | + \| d072002 | int | - | 总育儿假时数 | + \| d072003 | int | - | 已休育儿假时数 | + \| d072004 | int | - | 未休育儿假时数 | + +## 用途:育儿假记录表 + +- 视图:VIEW\_D072 + \| 字段名称 | 类型 | 长度 | 字段说明 | + \| --- | --- | --- | --- | + \| c001001 | nvarchar | 200 | 部门编号 | + \| c001002 | nvarchar | 200 | 部门名称(小部门) | + \| a008003 | nvarchar | 200 | 上级部门名称(大部门) | + \| c002001 | nvarchar | 200 | 员工工号 | + \| c002002 | nvarchar | 200 | 员工姓名 | + \| d072001 | int | - | 年份 | + \| d072002 | int | - | 总育儿假时数 | + \| d072003 | int | - | 已休育儿假时数 | + \| d072004 | int | - | 未休育儿假时数 | + +# OA数据对接AI知识库-请假流程相关视图 + +- DB:192.168.100.225:1433 +- UserName:AI\_Knowledge\_Base\_OA +- Password:hoo-thai\@123\_AI\_OA +- 默认数据库:ecology + +## 用途:流程当前节点视图 + +- 视图:v\_workflow\_requestbase + | 字段名称 | 字段类型 | 字符长度 | 字段说明 | + | ---------- | ------- | ------------- | ------ | + | requestid | int | int | 流程ID | + | status | varchar | varchar(500) | 流程状态 | + | workflowid | int | int | 流程类型ID | + | nodename | varchar | varchar(1000) | 当前节点名称 | + +## 用途:员工信息视图 + +- 视图:userInfo\_view + | 字段名称 | 字段类型 | 字符长度 | 字段说明 | + | ----------------- | ------- | ------------- | ------ | + | workcode | varchar | varchar(1000) | 员工工号 | + | lastname | varchar | varchar(1000) | 员工姓名 | + | id | int | int | 员工ID | + | **jobtitle** | int | int | 岗位ID | + | **departmentid** | int | int | 所属部门ID | + | **subcompanyid1** | int | int | 所属分部ID | + diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md new file mode 100644 index 00000000..8ee235be --- /dev/null +++ b/docs/features/in-transit-transfer/technical.md @@ -0,0 +1,95 @@ +# 在途仓自动调拨 Agent — 运行维护手册 + +> 状态:后端 Phase 0-4 已交付(领域/文件/预检/执行/排程/恢复/通知/归档/指标),前端实施中。 +> 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) · [TDD](./in-transit-transfer-tdd.md) · [PRD](./prd.md) · [路线图](./roadmap.md) + +## 1. 架构概览 + +- **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。 +- **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。 +- **真相源**:`TransferRun` / `TransferPrecheck` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`)。 +- **ERP 访问唯一出口**:`erp_adapter.py`(query_inventory / create_transfer / verify_duplicate);SOAP 在 WSDL 冻结前 fail-closed(`ErpNotFrozenError`)。 +- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费预检/执行 Run/执行 Item 三类 Job。 +- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。 + +## 2. 数据库 + +- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`)。 +- 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。 +- 表:transfer_runs / transfer_source_jobs / transfer_prechecks / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。 +- 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。 + +## 3. 环境变量(⑨业务模块区;凭据只由环境/Secret 注入) + +| 变量 | 默认 | 说明 | +| --- | --- | --- | +| `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 | +| `IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY` | 2 | ERP 查询并发 | +| `IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY` | 1 | ERP 写并发(一期恒 1,禁止提升) | +| `IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS` | 60 | 查询超时 | +| `IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS` | 60 | 写超时 | +| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 确认有效期(10 分钟) | +| `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 | +| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 | +| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 | +| `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) | +| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket | +| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) | +| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) | + +> 凭据纪律:ERP/MinIO 凭据只存在于环境/Secret;不得写入代码、日志、DOM、Excel 或 API 响应。 + +## 4. API(`/api/in-transit-transfer`,统一 envelope + requestJson) + +| Method | Path | 说明 | +| --- | --- | --- | +| POST | `/prechecks` | 创建预检(只读) | +| GET | `/prechecks/{id}` | 预检进度恢复 | +| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run | +| GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) | +| POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | +| POST | `/items/{id}/retry` | 人工重试(erp_recheck,新 Attempt) | +| POST | `/items/{id}/manual-close` | 人工关闭(原因必填) | +| GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) | +| GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) | +| GET | `/runs/{run_no}/erp-inventory` | 预检冻结 ERP 库存表 csv(下载留审计) | + +权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。 + +## 5. 部署 + +```bash +# 后端(迁移 + worker) +cd backend && flask db upgrade +# 新增 transfer worker 服务(docker-compose 增加 hxops-transfer-worker, +# command: python workers/worker_in_transit_transfer.py,环境同后端) +``` + +上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(预检、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。 + +## 6. 告警与运维关注点 + +- `result_unknown` 项数量(只读隔离,等待人工核实 SOP;禁止自动重试)。 +- 待处理池 3/5/7 天老化计数(`metrics.collect_metrics()` / 待处理页)。 +- `notification_status=failed` 的 Run(ERP 结果不受影响,但通知缺失需人工补发)。 +- ERP 超时率与 `ErpNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。 +- 归档 Hash 复核(`verify_archive_hash`)与 MinIO 容量。 + +## 7. 归档与数据保留 + +- 大型快照/Excel/报文经 `archive.py` 归档 MinIO,`transfer_archives` 索引+Hash 留库;归档必须重算 Hash 并写审计。 +- 审计事件永久保留(到期清理需显式配置,参照既有 shipping 审计保留机制)。 + +## 8. 回退策略 + +- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读预检与手工执行。 +- `result_unknown` 继续进入人工核实池;已成功 ERP 单据不自动撤销。 +- 回退配置走新发布版本 + Diff 审计,不直接改数据库。 + +## 9. E2E 与验收(前置:ERP 契约/路由归属/单据分组冻结 + 测试组织/白名单 + Secret 注入 + SOP 确认) + +- 后端专项:`cd backend; pytest -q tests/services/in_transit_transfer; pytest -q tests/api/test_in_transit_transfer_api.py; pytest -q tests/jobs/test_in_transit_transfer_jobs.py; pytest -q tests/workers/test_in_transit_transfer_worker.py` +- 性能:`pytest -q tests/performance/test_in_transit_transfer.py` +- 前端:`cd frontend; npm run test:unit -- src/features/chat; npm run build` +- 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。 +- 上线门禁:P0/P1 缺陷 0;越权写 403 100%;当天收料 ERP 调用 0;审计 Hash 复算一致率 100%;Secret 明文暴露 0。 diff --git a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md index c616467e..ec7ffe94 100644 --- a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md +++ b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md @@ -12,7 +12,7 @@ ## Global Constraints -- 禁止修改 `scripts/rpa/freight_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 +- 禁止修改 `scripts/rpa/inventory/inventory_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 - 首版不实现库存和收料间的登录会话复用、同 Profile 互斥锁或跨排程协调;运维上错开使用同一 Profile 的排程时间。 - 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。 - DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。 @@ -88,10 +88,10 @@ ### Task 4: 实现独立 DBS/Crane 收料 Windows Worker **Files:** -- Create: `scripts/rpa/freight_receipt_rpa_worker.py` -- Create: `scripts/rpa/freight_receipt_dbs_export.py` -- Create: `scripts/rpa/freight_receipt_crane_export.py` -- Create: `scripts/rpa/start_receipt_rpa_worker.ps1` +- Create: `scripts/rpa/receipt/receipt_rpa_worker.py` +- Create: `scripts/rpa/receipt/receipt_dbs_export.py` +- Create: `scripts/rpa/receipt/receipt_crane_export.py` +- Create: `scripts/rpa/receipt/start_receipt_worker.ps1` - Modify: `scripts/rpa/README.md` - Test: `backend/tests/test_freight_receipt_worker_contract.py` diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index d462af31..53493a7e 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -684,3 +684,65 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理; | 技术文档 | `docs/features/shipping-notice/technical.md` | | 同步维护 | 流程、字段、确认节点变更时 **两份文档一并更新** | | 最近更新 | 2026-07-22:履约策略更新为 `SHIP_AVAILABLE_ROLLING`;允许完整满足的预约单分轮制单,仍禁止按同一预约单拆分可发数量 | + +--- + +## 15. 多库存源自动探测与行级选源(一期) + +> 针对一个订单可能命中多个库存源(仓库)的场景。系统会**自动**从各缺失候选源获取库存并匹配,全程零人工;只有在「同一行在多个库存源都命中」这种无法自动裁决时,才会请你人工选源。 + +### 15.1 什么时候会自动获取库存 + +- 建单后进入「通知准备」,若某些候选源还没有可用库存快照,系统会自动触发一次**批量库存获取**(单批次、逐源、超时与重试沿用既有机制),页面显示「已触发库存获取,等待各库存源回调」。 +- 已有快照的库存源会直接复用,**不会重复获取**。 +- 之前“缺文件就停在库存等待”的阻断,现在只在**库存获取本身失败**(超时/用尽)时才出现,且仍可沿用既有的 reload/retry 恢复动作。 + +### 15.2 行级匹配与选源 + +- 匹配按「数据自证」原则:每条订单明细会在全部候选源快照里比对,按行写回**实际库存源 / 可用量 / 缺口**。 +- 如果某一行**只在单一库存源**有货,则该行自动确定来源,无需你操作。 +- 如果某一行**在多个库存源都命中**,系统无法替你决定,会在该行显示一个**库存源下拉**(候选 + 规则首选 + 命中规则提示)。你选择后点击确认,系统**只对该行重新匹配**,其他行不受影响: + - 候选源标记为首选(规则首选)的排在前面; + - 下拉里只出现该行真正命中的候选源; + - 你选定的来源会写入该行,并记入审计(`review_line_source_selected`)。 + +### 15.3 何时锁定为只读 + +- **边界 = Excel 生成**:通知的 Excel 一旦生成(导出产物落库),该行库存源即转**只读**,页面显示“已锁定”徽标,不再提供下拉。 +- 生成前的任何时间(含匹配完成后)你都可以改行源:系统只重新匹配该行,**不会重复触发库存获取**。 +- Excel 生成后想纠错:按既有撤销 / 人工流程处理。 + +### 15.4 同一行命中多源的提示 + +- 出现下拉行时,系统提示「同一明细在多个库存源命中,请选择实际库存源」。 +- 若某行**规则未命中任何候选源**,不提供下拉,沿用既有「规则未命中」阻断与重试入口。 + +### 15.5 波次通知的库存源(D8 已实现) + +- 波次通知(同 PO 分轮制单产生的后续发货通知)**不再继承首通知的库存源字段**,改为按**波次自己的明细行**重新评估库存源并冻结候选集(同一套自动探测/匹配/反写)。这样「同一订单不同行来自不同仓库」不会因为波次照抄首单源而冲突。 +- 波次行为设计:若某一行命中了路由规则,就按该规则确定来源;若某一行**一条规则都没命中**,则回退到该订单级(任务级)可用的候选来源,和首张通知的处理方式一致,不会把该行算成“无候选”而卡死。 +- 若确实极个别订单需要人工确认来源,按既有「无候选/歧义」阻断与人工选源流程处理。 + +--- + +## 16. 确认后、Excel 前的订单编辑窗(二期) + +> 订单确认后、首通知 Excel **生成前**,业务人员仍可修正少量订单头字段或行字段(如目的地、料号、数量、预约号)。Excel 一旦生成即转只读,纠错走既有撤销/人工流程。 + +### 16.1 什么时候可以编辑 + +- **头字段**:该订单所有通知都还没有生成 Excel、且没有正在处理的库存获取/匹配(系统不忙)时,可编辑单头字段(如目的地、客户、PO)。 +- **行字段**:每条明细行可编辑的窗口更宽松——只要该行**所属的通知**还没生成 Excel、且系统不忙即可;尚未进入任何波次的行,即使首张 Excel 已生成,也仍可编辑(D10「未入波次行不受首单 Excel 限制」)。 + +### 16.2 编辑后会发生什么 + +- 系统按字段类型自动决定下游动作: + - **路由字段**(目的地、仓提示等)变更 → 自动**重新路由库存源 + 重新获取(复用已有快照)+ 全单重新匹配**。 + - **行字段**(料号/数量/预约号)变更 → **仅该行重新匹配**;若该行被行级路由规则引用则同时重路由该行。 + - 与路由/匹配无关的字段 → 仅保存 + 版本递增 + 审计,无额外动作。 +- 编辑期间若系统正在处理库存获取或匹配,会提示「系统处理中,请稍后再修改」,待处理结束再改。 + +### 16.3 Excel 生成后 + +- Excel 一旦生成,头字段、行字段、行源全部转为**只读**;页面按后端 `edit_window` 禁用对应输入。 +- 若已确认信息有误,只能走既有的撤销 / 人工纠错流程(D12:编辑窗只覆盖「确认后、Excel 前」;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销)。 diff --git a/docs/features/shipping-notice/customer_identity_rules_plan.md b/docs/features/shipping-notice/customer_identity_rules_plan.md index 4985cdff..8c184b9e 100644 --- a/docs/features/shipping-notice/customer_identity_rules_plan.md +++ b/docs/features/shipping-notice/customer_identity_rules_plan.md @@ -107,7 +107,7 @@ - 新增 `backend/app/services/shipping_notice/identity_resolution/`:来源适配器、标准化、匹配、冲突裁决、快照序列化。 - `backend/app/services/shipping_notice/customer_shadow_resolution.py`:替换固定权重/固定提取。 -- `backend/app/services/shipping_notice/order_customer_matching.py`:保留编码优先,名称/地址/联系人使用统一候选。 +- `backend/app/services/shipping_notice/identity_resolution/` 与 `customer_shadow_resolution.py`:按已发布规则集汇总名称、编码、地址、联系人等指纹证据,生成统一候选与确认快照。 - `backend/app/services/shipping_notice/order_schema/runtime.py`:提供仅读取已裁决 Header 值的稳定入口。 - `backend/app/models/shipping_customer_resolution.py`:记录规则版本、定义快照、来源字段快照和命中原因。 - `backend/app/services/shipping_notice/order_schema/service.py`:把启用识别定义纳入字段引用阻断。 diff --git a/docs/features/shipping-notice/display-and-button-contract.md b/docs/features/shipping-notice/display-and-button-contract.md new file mode 100644 index 00000000..f5d39e0d --- /dev/null +++ b/docs/features/shipping-notice/display-and-button-contract.md @@ -0,0 +1,337 @@ +# 货代发货通知 — 工作台「展示 & 按钮」唯一契约(冻结 2026-09) + +> **本文件是订单处理工作台在「展示数据」与「任务级/明细级按钮」两方面唯一权威契约。** +> 结论基于现有实现(`shipping_processing_projection` / `ui_state` / `process_gate` / +> `stage_context.preparation`),**不新增投影/抽象**,只做「单一来源 + 去冗余」。 +> 后端只读投影与前端所有消费方都必须遵守,禁止再私自分叉。 + +--- + +## 0. 一句话结论 + +- **展示单源**:右「当前任务」卡、5 阶段页签、批次中心卡 **全部** 以 `shippingProcessingProjection` + (含其 `ui_state` 子 DTO)为单一来源;`formalTaskDetail.ui_state` **不再**参与「当前阶段 / 用户状态 / + 阻断 / 动作」展示,只保留它独有的**工作面只读事实**(`stage_context.preparation`、`edit_window`、 + `steps/todo/checkpoint`、`business_no`、`export_artifacts`)。 +- **任务级按钮单源 A**:右卡主按钮 / 恢复按钮 **只读** A 的 `primary_action` / `secondary_actions`。 + **禁止**再把 `stage_context.preparation.capabilities` 独立渲成右卡按钮(capabilities 仅可作点击后 + `stageCapabilityBypass` 查找,见 §3.2)。 +- **按钮分域**:只有 **1 个**动作是**明细级**(`override_line_inventory_source`),只出现在库存表格逐行; + 其余全部**任务级**,只出现在右「当前任务」卡。旧 D5 `select_line_inventory_source` **已删除**。 +- **零新动作码**:库存「复用快照 / 强制 RPA / 只读轮询」靠**已有码**映射 `ensure_inventory.mode` + (见 §3.3),禁止再造 `fetch_inventory` / `force_inventory_rpa` 等新合同。 +- **库存动作语义**:`retry_inventory_preparation` / `retry_inventory_from_preparation` → `mode=retry_rpa`; + `poll_inventory_preparation` → 只读轮询(`allow_auto_retry=False`);首次 `gate_attempt_passed` 自动投递 + 保持默认 `auto`。`retry_inventory_matching` 优先复用快照重匹配(无快照再回退 RPA)。 + `reload_inventory_result` 写契约仍有效,**用户按钮面已下线**(并入 matching,见 §3.3)。 +- **明细级按钮的数据源**:`ui_state.stage_context.preparation.lines[].line_allowed_actions / + inventory_allowed_actions`(后端已下发,零 N+1,见 §3.4 / §5)。 +- **行级库存作用域**:明细行点击重抓/重匹配携带 `snapshot_line_id` → 后端按该行 + `candidate.source_codes_json` 收窄 RPA/获取/失效;同行源未发通知行可共享新快照; + 已产生发货通知行(`ShippingNoticeLine`)匹配与 Artifact **不得**被行级重抓改写。 + +--- + +## 1. 现有投影「角色」归类 + +| 编号 | 形状 | 产出方 | 唯一用途 | 稳态/运行态 | 底层唯一事实源 | +|---|---|---|---|---|---| +| A | `shipping_processing_projection.order_task`(含 `ui_state`) | `_project_order_task_work_item` → `reconcile_processing_projection_facts` → `apply_user_projection_fields` → `_with_processing_ui_state` | 右「当前任务」卡 + 批次中心卡 + 会话卡 | 稳态只读 | `ShippingOrderTask.stage/status/pending_human_reason/review_status/progress_version/active_process_execution_id` + `ShippingProcessExecution.current_gate_code/status` + `ShippingProcessGate` + `ShippingNotice.lifecycle_status` + 库存准备/导出/上传 Attempt | +| B | `formalTaskDetail.ui_state` | `build_task_ui_state` → `resolve_task_ui_state` → `_task_lifecycle` → `_unified_actions` | 工作面只读事实:`stage_context.preparation`(表格/编辑窗)、`edit_window`、`steps/todo/checkpoint`、`business_no` | 稳态只读 | `ShippingNotice.lifecycle_status/task_no/review_status` + `ShippingOrderTask` + 最新 Export/Upload/Verification/Match/Preparation 行 | +| C | `process_gate` 摘要 | `project_user_gate_summary` → `_resolve_recovery_next_action` → `recovery_targets` | 唯一「当前能做什么 + 为何阻断」裁决(`execution_no/evaluation_version/recovery_targets` 供**写**请求) | 稳态只读 | `ShippingProcessExecution` + `ShippingProcessGate` + `PROCESS_GATE_DEFINITIONS.default_next_actions` | +| D | `stage_context.preparation` | `_build_stage_context` → `preparation` | 通知准备面板的库存事实(`frozen_order_lines`/`lines[]`/`source_options`/`inventory_sources`/`capabilities`) | 稳态只读 | `ShippingNoticeLineInventoryMatch(is_current)` + `ShippingInventoryVerification` + `ShippingInventoryPreparationAttempt` + `ShippingExportArtifact` + `ShippingUploadAttempt` | +| E | `lifecycle_stage`/`stage_label_key` | `project_lifecycle`(`lifecycle_stage/entries/authority`)+ `project_stage_for_task`(`current_stage.code/label_key`) | 5 阶段页签/入口 + 技术阶段码+文案键 | 稳态只读 | `ShippingOrderTask.stage`(优先)+ `map_run_to_processing_stage` + `ShippingProcessExecution.current_gate_code` + 核验上传成功 | + +**关键澄清(根因)**:`stage` 这个字段名在 A 的 `ui_state` 是**技术阶段码** +(`shipping_processing_projection.py:3128`),在 B 的 `build_task_ui_state` 是 **5 阶段 DTO** +(`ui_state.py:1117`)。**同一键、两个无关值域**。契约用不同且唯一的键区分: +`stage/stage_label_key/current_stage.code` 只承载**技术阶段码**;`lifecycle_stage/lifecycle_entries/lifecycle_authority` +只承载 **5 阶段业务标签**。 + +--- + +## 2. 展示契约:每个字段的唯一来源 + +> 规则:右卡与 5 阶段页签的字段**全部读 A**,不再读 B。B 只保留工作面事实。 +> 稳态/运行态只影响「是否可能为空/待刷新」,**不改变字段来源**。 + +| 展示值 | 唯一来源(单源) | 稳态/运行态 | 落点 UI | +|---|---|---|---| +| 5 阶段当前阶段 | `shippingProcessingProjection.ui_state.lifecycle_stage` | 稳态 | 5 阶段页签头 + 右卡 | +| 5 阶段入口/授权 | `...ui_state.lifecycle_entries` / `.lifecycle_authority` | 稳态 | 5 阶段页签 | +| 技术阶段码+文案键 | `shippingProcessingProjection.stage` / `.stage_label_key` | 稳态 | 右卡「当前门禁」行、批次卡 | +| 用户状态 | `...ui_state.status` | 稳态 | 右卡「状态」行 / 处理详情抽屉 | +| 阻断原因(下一步) | `...ui_state.blocking_reason` | 稳态 | 右卡「下一步」 | +| Gate 状态 | `shippingProcessingProjection.current_gate.status` | **运行态** | 右卡(区分未入队/运行/待外部回执) | +| 主动作/恢复动作 | `...ui_state.primary_action` / `.secondary_actions`(**仅此**;禁止叠加 `preparation.capabilities`) | **运行态** | 右卡主按钮 + 恢复按钮 | +| 库存准备时间线 | `shippingProcessingProjection.inventory_preparation` + `.facts` | **运行态** | 通知准备时间线 | +| 工作面表格行/改源/编辑 | `formalTaskDetail.ui_state.stage_context.preparation.*` | 稳态 | 通知准备表格(**明细级**) | +| 编辑窗(D10) | `formalTaskDetail.ui_state.edit_window` | 稳态 | 编辑面 | +| 步骤条/todo/checkpoint | `formalTaskDetail.ui_state.steps/todo/checkpoint` | 稳态 | 顶部步骤条 | +| 业务号/导出产物 | `formalTaskDetail.business_no` / `export_artifacts` | 稳态 | 上传面 | + +### 稳态 vs 运行态 +- **稳态**(`stage/lifecycle_stage/status/blocking_reason`):由 `ShippingOrderTask.stage/status` + + `ShippingProcessExecution.current_gate_code` + `project_lifecycle` 派生,不随 RPA 运行而变。 +- **运行态**(`current_gate.status`、`ui_state.primary_action/secondary_actions`):由 + `ShippingProcessExecution/ShippingProcessGate` 当前行派生,随 RPA/执行推进。前端轮询 A + (`startWorkflowProgressPolling` → `refreshShippingProcessing` → `shippingProcessingProjection`) + 刷新,`progress_version` 单调递增驱动右卡刷新。 + +### 2.1 A↔C 等价性验证结果(已用 `tests/test_shipping_projection_gate_equivalence.py` 锁定) + +> **结论:历史 D1/D2 漂移已由 STEP8 flatten 消除;A 的 `primary_action`/`blocking_reason` 在有 +> `payload['process_gate']` 时消费 C,与写裁决同源。** + +| # | Gate | 历史漂移(已修) | 修法 | +|---|---|---|---| +| D1 | `artifact_generation` | A 曾用 `regenerate_excel` 别名 | STEP8 取 C 规范码 `regenerate_excel_artifact` | +| D2 | `inventory_preparation` blocked_retryable | A 曾坍缩为 `technical_failure_present` | STEP8 取 C 的 `inventory_preparation_failed` | + +**flatten A 的边界(重要)**:A 的 `user_status`(六值展示分组)是 A 独有,**不得**纳入 flatten。 +flatten 只动 `primary_action.code` 与 `blocking_reason.code/i18n_key`。Intake/min 无 C 时保留现有推导。 + +**等价性已锁定(A==B==C)**:harness 覆盖多 Gate × A↔C + B↔C + 生命周期 + 明细按钮 + N+1。 +右卡/对话流/批次进度中心不再各自为政(须与前端右卡仅读 A 同批,已完成)。 + +**动作码 A↔B/C(差异① 已归一)**:A 的 `secondary_actions` 已透传 C 原始 Gate 码(含 +`mark_manual_uploaded`,不再别名成 `open_manual_upload`)。前端 `manualUploadRegistrationAuthorized` +与右卡恢复入口均读 A,与写契约码一致。详见 §2.5.2。 + +**生命周期阶段 A↔B 同源确认(无伪漂移)**:A(`_processing_ui_state_from_item`)与 B(`_task_lifecycle`) +**都**调用 `project_lifecycle`。`LIFECYCLE_STAGE_BY_GATE`(`lifecycle_projection.py:30`)是正式 Gate→五阶段 +业务码的唯一表。前端正式 OT 的 5 阶段页签已 **A-first**(§2.5.3 / §6),属收敛而非行为改写。 + +### 2.5 A↔B/C 动作码与生命周期形状归一化(后端前置 → 前端已切) + +> **一句话**:A 的 `ui_state` 在「动作码」上与 B/C **逐字一致**后,前端已把 §1.1(`lifecycleUiState` +> 正式 OT 读 A)与 `manualUploadRegistrationAuthorized`(读 A)切过去;blocker 由前端从 A 的 +> `blocking_reason` 解析(优先 `i18nKey`→`te/t`,否则 `code`),不要求后端再造平行 `blocker` 字段。 +> ① 动作码 `mark_manual_uploaded`:**已归一**(§2.5.2)。 +> ② 页签 `lifecycleUiState`:**已落地(方案甲′)**(§2.5.3)。 + +#### 2.5.1 现状(三源逐一对比) +| 字段 | A(`shippingProcessingProjection.ui_state`) | B(`formalTaskDetail.ui_state`) | C(`project_user_gate_summary`) | 差异 | +|---|---|---|---|---| +| 动作码 `mark_manual_uploaded` | `secondary_actions` 透传 **`mark_manual_uploaded`** | `actions.secondary` 同码 | `allowed_actions` 同码 | ✅ 已归一 | +| 阶段入口 | `lifecycleEntries`(`[]如{code,state,targetSurface}`) | `lifecycle_entries`(同形状) | `lifecycle_entries`(同形状) | ✅ 已同形 | +| 阻断说明 `blocker` | `blocking_reason`(`{code,i18nKey,details}`) | `reason.message`(已翻译文案) | `blocking_reason_code`+`explainability` | 形状不同;前端读 A 时本地解析,不 flatten 成 message | +| 阶段码 | `lifecycleStage` | `stage.code` / `lifecycle_stage` | 由 `project_lifecycle` 统一 | ✅ 同源 | + +**已确认同源的部分**:`lifecycle_stage`(阶段码)3 源均用 `project_lifecycle`。动作码差异①已消除; +blocker 保持 A 结构化形状,由前端统一解析(§2.5.3)。 + +#### 2.5.2 差异①:`mark_manual_uploaded` 被 A 别名成 `open_manual_upload`(**已归一,验证通过**) +- **根因**:`processing_projection_invariants._ACTION_CODE_ALIASES['mark_manual_uploaded'] = 'open_manual_upload'`(`:88`) + 与 `derive_available_actions`(`:476-477`)把 `gate_action ∈ {open_manual_upload,wait_manual_upload,mark_manual_uploaded}` + `_push('open_manual_upload')`,导致 A 的 `secondary_actions` 曾输出别名,而非原始 Gate 码。 +- **影响(历史)**:`manualUploadRegistrationAuthorized` 若读 A 找 `mark_manual_uploaded` 会失效。 +- **修法(已实施 + 验证)**:`shipping_processing_projection` 新增 `_process_gate_allowed_action_codes(item)`, + `_processing_ui_state_from_item` 用它从 C 摘要(`payload['process_gate'].allowed_actions` / `action_presentation[].code`) + 取**原始 Gate 码**构造 `secondary_actions`(不再经 `_ACTION_CODE_ALIASES` 归一为 `open_manual_upload`)。 + 无 C 时回退 `available_actions`(Intake/min 投影路径)。 +- **验收(已绿)**:`test_a_secondary_actions_carry_mark_manual_uploaded` 在 `freight_upload_rpa` + 门禁下断言 **A.secondary_actions 含 `mark_manual_uploaded`** 且与 `C.allowed_actions` 同集。 + +#### 2.5.3 差异②:页签 `lifecycleUiState` 读 A(**已落地,方案甲′**) +- **形状事实**:A 的 `blocking_reason` 是 `{code,i18nKey,details}`;B 的 `reason.message` 是已翻译文案。 + 前端页签需要「可展示阻断字符串」,**不在后端再造平行 `blocker` 字段**。 +- **落地读序(`ShippingOrderReviewView.vue` `lifecycleUiState`)**: + 1. **正式 OT 且 A 已有 lifecycle** → stage / entries / blocker **认 A**(与右卡同源); + blocker = `te(i18nKey) ? t(...) : code`(禁止直接吐机器 i18nKey 原文)。 + 2. **A 尚未落位** → 短暂降级 B,避免页签空窗。 + 3. **建单前** → 仍用 `reviewQueue` / `reviewRun` 项的 `lifecycle_entries`(字段明确存在时 + 空数组也是后端拒绝结果,禁止回退到会话级其他 PDF 投影)。 +- **历史风险说明**:曾尝试「A 绝对优先」导致 upload/freight 相关 spec 失败;甲′ 用「正式 OT + A 有数据」 + 门闩 + B/队列降级,`ShippingOrderReviewView.spec.ts` **103/103 全绿**。 +- **capabilities 不进页签/右卡渲染**:见 §3.2 / §6。 + +#### 2.5.4 落地顺序(已完成) +1. ~~加守卫测试~~ → 已绿(`mark_manual_uploaded` 透传)。 +2. ~~后端归一~~ → 已绿(A.secondary_actions 原始 Gate 码)。 +3. ~~前端切换~~ → 已绿:`lifecycleUiState` 正式 OT A-first(甲′);`manualUploadRegistrationAuthorized` 读 A; + 右卡恢复动作只读 A.secondary_actions(停 capabilities 叠加)。 +4. ~~全量回归~~ → 前端 `ShippingOrderReviewView.spec.ts` 103/103;相关后端投影/恢复用例已绿。 +5. **性能护栏仍有效**:归一只改读序 / 内存组装,不新增轮询或查询。 + +#### 2.5.5 边界(不改的部分) +- `user_status`(A 独有的六值展示分组枚举)留在 A,**不**纳入归一。 +- `open_manual_upload` 作为「聊天/通知级手工上传入口」在 `derive_available_actions` 仍保留(它本就是另一层 + 展示别名),只是**不得再覆盖 `mark_manual_uploaded` 的原始码**。 +- 写契约(`request_gate_action`)仍只认 `mark_manual_uploaded` 等 `PROCESS_GATE_ACTION_CODES`; + 前端从 A 读到的动作码必须能与写契约对齐。 +- **禁止新增动作码**解决库存语义;用已有码映射 `ensure_inventory.mode`(§3.3)。 +- 行级点击已携带 `snapshot_line_id`;后端按该行 `candidate.source_codes_json` 收窄获取/RPA/ + 失效范围;已产生发货通知的行不得被行级重抓改写匹配或 Artifact。 + + + +### 两个展示 bug 的契约修法 +- **「当前门禁 —」**:`resolveShippingProcessingStageLabel('')` 返回 `'—'`(`shippingProcessingLabels.ts:150`), + 当 `currentProcessingStageDisplay` 因投影 `stage/ui_state.lifecycle_stage` 均空(且 `!loading`)返回空时触发。 + **修法**:已知正式 OT 必有阶段,投影恒有 `stage/lifecycle_stage`;投影未就绪由右卡 `:loading` + (`formalTaskProjectionPending`/`formalTaskDetailLoading`/`caseSwitchLoading`)驱动骨架占位,**禁止**落 `'—'`。 +- **「状态待确认」**:`resolveShippingProcessingStatusLabel` 不认识码时的兜底(`labels.ts:69`), + 仅被 `ReviewProcessDetailDrawer` 消费(读 `projection.status`)。右卡空态用的是 `statusIdle`(待机)、 + 表格行数用 `'待确认'`——**三套词汇**。**修法**:状态统一从 `shippingProcessingProjection.ui_state.status` + (受控 6 值)取,禁止给投影塞不受控码;`resolveShippingProcessingStatusLabel` 仅作不受控码兜底。 + +--- + +## 3. 按钮契约:任务级 vs 明细级 + +### 3.1 动作面与作用域 +`PROCESS_GATE_ACTION_CODES`(`process_gate_contract.py`)∪ `STAGE_CAPABILITY_DEFINITIONS` +(同文件)。**只有 1 个是明细级**: + +| 动作码 | 作用域 | 宿主 | 位置 | +|---|---|---|---| +| `override_line_inventory_source` | **明细级** | `_handle_override_line_inventory_source` | 库存表格逐行(override 下拉) | +| ~~`select_line_inventory_source`~~ | ~~明细级~~ | **已删除** | — | +| 其余全部 | **任务级** | 右「当前任务」卡 | 主按钮 + 恢复按钮 | + +前端唯一判据:`LINE_SCOPE_INVENTORY_ACTIONS = {override_line_inventory_source}` +(`ShippingOrderReviewView.vue`)。凡在此集合内的动作一律不进任务级按钮(右卡主/恢复均排除)。 + +### 3.2 步骤/状态 → 动作(按 Gate 阻断归属) +主动作唯一裁决:`_resolve_recovery_next_action`(`process_gate_projection.py`);侧路: +`gate_side_recovery_actions`(`process_gate_contract.py`)。二者与校验层 `request_gate_action` +的 `allowed_side` **共用同一份裁决**(保证「投影放行==校验放行」)。 + +| Gate 阻断 | 主动作 | 侧路 | +|---|---|---| +| `inventory_preparation` blocked_manual/retryable | `retry_inventory_preparation` | — | +| `inventory_preparation` waiting_external | `poll_inventory_preparation` | — | +| `inventory_preparation` RPA 超时/耗尽 | `retry_inventory_matching`(复用快照重匹配,无则 RPA) | `retry_inventory_preparation` | +| `inventory_sufficiency` 正式 OT+已确认库存 | `retry_inventory_matching` | — | +| `inventory_sufficiency` 正式 OT+无确认库存(短缺) | `open_shortage_review` | — | +| `inventory_matching`/`inventory_sufficiency` 建单前 | `open_inventory_match_review`/`open_shortage_review` | `override_line_inventory_source`(多文件冲突,明细级) | +| `freight_upload_rpa` 失败 | `retry_freight_upload_rpa` | — | +| `manual_upload_handoff` | `mark_manual_uploaded` | `retry_freight_upload_rpa` | + +**任务级常驻能力(`STAGE_CAPABILITY_DEFINITIONS` / `_stage_capabilities_for_task`)**: +仍可由后端下发到 `stage_context.preparation.capabilities`(如 `retry_inventory_preparation`、 +`reload_inventory_result`、`retry_inventory_matching`;`override_line_inventory_source` 为明细级)。 +**展示契约**:这些能力 **不得**再独立渲成右卡按钮;右卡只读 A 的 `primary_action` / +`secondary_actions`。若某能力应对用户可见,必须先并进 A(经 C 裁决进投影)。点击路径仍可 +用 capabilities 作 `stageCapabilityBypass` 查找(执行框架不变)。 + +### 3.3 库存动作与 `ensure_inventory.mode` 映射(零新动作码) +| 动作码 | 用户语义 | `ensure_inventory` | 跑 RPA | +|---|---|---|---| +| `retry_inventory_preparation` / `retry_inventory_from_preparation` | 显式强制重抓 | `mode=retry_rpa` | ✅ | +| `poll_inventory_preparation` | 只读轮询结果 | 默认 mode + `allow_auto_retry=False` | ❌(不自动重试) | +| 首次 `gate_attempt_passed` 自动投递 | 进入库存准备 | 默认 `auto`(先复用快照) | 视缺文件 | +| `retry_inventory_matching`(**主恢复合并动作**) | 优先复用快照重匹配;无快照回退 RPA | 经 `match_inventory` → 必要时 `ensure_inventory` | 视情况 | + +落点:`process_gate_executor._handle_retry_inventory_preparation` 内 +`_FORCE_INVENTORY_RPA_ACTION_CODES`;**禁止**「人工入口一律 `retry_rpa`」。 + +**`reload_inventory_result` 已下线展示**:行为并入 `retry_inventory_matching`;写契约码仍保留防 400。 +已同步 `gate_side_recovery_actions` / `action_belongs_to_gate` / 前端 presentation 与相关测试。 + +**`has_formal_ot`(明细按钮前置)**:以 owner 为 `ShippingOrderTask` **或** 已冻结 +`order_snapshot_id` 判定,**禁止**用「有无 `current_match_rows`」代替(无匹配行时仍须下发行级 +重试/关闭按钮)。落点:`ui_state._build_stage_context`。 + +### 3.4 明细级按钮的数据源(§0 一句话结论的展开) +通知准备表格**每行**的明细级按钮(库存放行、关闭不可履约、行级重抓/重匹配、下载库存)由 +`ui_state.stage_context.preparation.lines[].{line_allowed_actions, inventory_allowed_actions, inventory_file_no, +release_required_fields, release_field_resolution_error, decision}` 驱动,**后端必须下发**到该数组。 +前端对应门禁:`formalPreparationLineAllows(line, action)`(`ShippingOrderReviewView.vue:2571`): +- `close_unfulfillable` / `release_inventory_shortage` → `line_allowed_actions.includes(action)` 且 + `release_inventory_shortage` 需 `!release_field_resolution_error`; +- `retry_inventory_preparation` / `retry_inventory_matching` → `inventory_allowed_actions.includes(action)`; +- 下载库存 → `inventory_file_no` 非空(`downloadFormalPreparationLineInventoryFile` `:2647`)。 + +> ~~**当前 BUG**:后端 `_build_stage_context` 生成 `preparation.lines[]`(`ui_state.py:837-862`)**未输出** +> 上述 `*_allowed_actions`/`inventory_file_no`/`release_*`/`decision` 字段(它们只存在于 Case 快照 +> `line_fulfillment.lines[]`,见 `order_review_fulfillment_decision_service.py:956-973`、`line_inventory_match_projection.py:667-694`), +> 导致 `formalPreparationLineAllows` 恒 false、明细级按钮全部不渲染。~~ +> **已修复(§1.5)**:`_build_stage_context` 现已在行循环内用内存 `match_row` 事实调用纯函数 +> `project_line_inventory_view` 下发 `line_allowed_actions`/`inventory_allowed_actions`/`inventory_file_no`/ +> `user_line_status`/`is_shortage` 等(零逐行 SQL,见 §6 落地清单)。短缺行另复用 +> `_shortage_release_required_fields` 下发 `release_template_fields`/`release_required_fields`; +> 解析失败时写 `release_field_resolution_error`(fail-closed,禁止只填原因)。`decision` 仍为 `null`。 +> +> **RPA 运行中(与 Case 同源)**:行循环外调用一次 `inventory_rpa_is_running(order_task)`(请求级 memo), +> 再传入各行 `project_line_inventory_view`;禁止逐行查 Attempt,也禁止用阶段 Job / 右卡 +> `userStatus` 推断。运行中 `inventory_allowed_actions=[]`。 +--- + +## 4. 前后端如何配合(冻结) + +1. **后端只读投影**:A(`shippingProcessingProjection`+`ui_state`)是唯一**展示+动作**合同; + C(`process_gate`)是唯一**写**裁决(`execution_no/evaluation_version/recovery_targets`); + B/D 只提供**工作面**事实。三者同一派生事实源,后端负责让它们同源不漂移。 +2. **前端轮询**:`startWorkflowProgressPolling`(`PROGRESS_POLL_MS`)→ `refreshShippingProcessing` + → `shippingProcessingProjection`(按 `progress_version` 单调合并)→ 刷新右卡 + 5 阶段页签; + 必要时再 `loadFormalTaskDetail` 拉工作面事实。 +3. **前端职责**:不用 `formalTaskDetail.ui_state` 推展示/动作;右卡与页签只用 A 的 `uiState`, + 工作面表格/编辑窗只用 B 的 `stage_context.preparation`。**禁止**把 `preparation.capabilities` + 渲成右卡按钮。不自行推导阶段/按钮;`stage` 码不与 `lifecycle_stage` 混淆。 + 正式 OT 页签读序见 §2.5.3(A-first / 甲′)。 + +--- + +## 5. 效能约束(必须遵守,与功能契约同权) + +> 核心:展示与按钮单源收敛**不得**以新增查询 / 渲染热路径为代价。`stage_context.preparation` +> 仍**只在任务详情**下发,不进轮询 / 轻量投影。 + +1. **明细级按钮零 N+1(§3.4)**:`_build_stage_context`(`ui_state.py:735`)已把该任务 + `ShippingNoticeLineInventoryMatch(is_current=True)` 全量加载进内存并建好 `match_by_snapshot_line_id`。 + `preparation.lines[]` 逐行的 `line_allowed_actions / inventory_allowed_actions / inventory_file_no / + release_required_fields / release_field_resolution_error / decision` 必须**在同一个循环内**、 + 复用上述**已加载内存事实**结算(调用 `line_inventory_match_projection.resolve_*_allowed_actions` + 等纯函数),**禁止逐行 SQL / 逐行调用重序列化器**。复杂度保持 O(行数)。 +2. **`stage_context.preparation` 只进任务详情**:不得下放到 `shippingProcessingProjection`(work-item / + 轮询 / 轻量投影),避免 N+1 与轮询膨胀。该限制已有(见 `technical.md`),本次收紧为契约级。 +3. **flatten C 复用单次 `project_user_gate_summary`**:A(`_order_task_current_gate`)与 B + (`_process_gate_user_summary_for_task`)必须**复用同一份 C 结果**,不得各自再调用 / 再推导 + `primary_action / blocking_reason / next_action`,保证单个 work-item 只调用一次、净减重复推导。 +4. **poll 热路径不变**:轮询 `PROGRESS_POLL_MS`(当前 `5000`,`useShippingOrderReview.ts:86`)与 + `refreshShippingProcessing()` 的调用序列**不因本次收敛改变**;前端读 A 只改读序、不增请求。 + (顺带修正过期的「2.5s/3s」注释为实际 `5000`。) +5. **验收护栏**: + - 改前 / 改后对 `GET /shipping-tasks/`(含 `stage_context`)做 SQL 查询次数对比,确认 + **不随行数线性增加**(加 `assert_num_queries` 类测试,或手工 `EXPLAIN` 对比)。 + - 确认单个 work-item 的 `project_user_gate_summary` 调用次数不变(仍 1 次)。 + +--- + +## 6. 落地清单(去冗余,不新增抽象) + +- [x] 前端:`lifecycleUiState` 正式 OT **优先读 A**(方案甲′:A 有 lifecycle 才认;A 未落位短暂降级 B; + 建单前保留 `reviewRun`/`reviewQueue`)。blocker 从 A.`blocking_reason` 解析(`i18nKey`→`te/t`,否则 `code`)。 + 已验证:`ShippingOrderReviewView.spec.ts` 103/103 全绿。 +- [x] 前端:右卡 `currentTaskPrimaryAction`/`currentTaskRecoveryActions` **只用** A 的 + `primary_action` / `secondary_actions`;**停止**叠加 `stage_context.preparation.capabilities`; + 按 code 剔除明细级(`LINE_SCOPE_INVENTORY_ACTIONS`)。i18nKey 统一映射到 + `workspace.shippingNotice.processGate.actionCodes.`。 +- [x] 前端:删除 `formalTaskActions` 对右卡的依赖;`manualUploadRegistrationAuthorized` 已收敛到 A。 +- [x] 前端:把「当前门禁」`--` 收敛为「投影未就绪 → 骨架占位」,禁止空阶段落 `'—'`。 +- [x] 前端:`LINE_SCOPE_INVENTORY_ACTIONS` 只保留 `override_line_inventory_source`(已删 `select_line_inventory_source`)。 +- [x] 后端:`_handle_retry_inventory_preparation` 按**已有动作码**映射 `ensure_inventory.mode` + (强制 RPA 仅 `retry_inventory_preparation` / `retry_inventory_from_preparation`;poll 只读; + 首次自动投递保持 `auto`)。零新动作码。守门:`test_inventory_preparation_mode_maps_by_action_code`。 +- [x] 后端:`_build_stage_context` 的 `has_formal_ot` 以 owner=`ShippingOrderTask` 或已冻结 + `order_snapshot_id` 判定(禁止用 `current_match_rows`)。守门:`test_stage_context_line_actions_without_match_rows`。 +- [x] **后端(明细级按钮,§1.5 / §5.1 零 N+1)**:`preparation.lines[]` 携带 + `line_allowed_actions`/`inventory_allowed_actions`/`inventory_file_no` 等;内存结算、禁止逐行 SQL。 + 短缺行复用 `_shortage_release_required_fields` 投影 `release_template_fields`/ + `release_required_fields`(解析失败写 `release_field_resolution_error`);`decision` 仍为 null。 + N+1 守门已绿。 +- [x] 后端:删除 `select_line_inventory_source`(已被 `override_line_inventory_source` 取代)。 +- [x] 后端:`apply_user_projection_fields` STEP8 条件化消费 C,A 的 `primary_action`/`blocking_reason` 与 C 同源 + (`test_shipping_projection_gate_equivalence.py`)。 +- [x] i18n:四语言 `actionCodes.*` 区分库存动作文案;删除 `select_line_inventory_source` 残留键。 + +### 6.1 按需 / 未强制项(不阻塞本契约) + +- [x] 行级点击在已有 `snapshot_line_id` 基础上,后端按行 `candidate.source_codes_json` 收窄 + `ensure_inventory` / RPA / 失效范围(`retry_inventory_preparation` 与 `retry_inventory_matching`); + 同行源可共享新快照,**已产生发货通知行**(`ShippingNoticeLine`)的匹配事实与 Notice Artifact + 不得被行级重抓改写。零新动作码。落点:`process_gate_executor._resolve_line_inventory_scope`、 + `recovery_invalidation_service.invalidate_inventory_downstream(source_codes=...)`。 +- capabilities 是否继续出现在 D 载荷:可保留供执行 bypass;**展示面不得再独立渲染**(已冻结)。 diff --git a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md index 6e800da2..62d8329f 100644 --- a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md +++ b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md @@ -259,7 +259,7 @@ ROUTE_DETECT_MODE.mode == "review" | --- | --- | ---: | --- | | `field_code` | String/Null | 否 | 可读字段编码,不作为身份真相 | | `field_id` | String | 是 | 冻结 Schema 稳定字段 ID | -| `line_key` | String/Null | 条件必填 | `scope=line` 时必须为非空字符串 | +| `draft_line_id` | String/Null | 条件必填 | `scope=line` 时必须为非空草稿行身份 | | `line_number` | Integer/Null | 否 | 可选显示行号 | | `scope` | String | 是 | 仅允许 `header` 或 `line` | @@ -296,8 +296,8 @@ def main(query: str, review_llm_contract: str = "") -> dict: raise ValueError("FIELD_ID_REQUIRED") if target.get("scope") not in ("header", "line"): raise ValueError("INVALID_SCOPE") - if target.get("scope") == "line" and not str(target.get("line_key") or "").strip(): - raise ValueError("LINE_KEY_REQUIRED") + if target.get("scope") == "line" and not str(target.get("draft_line_id") or "").strip(): + raise ValueError("DRAFT_LINE_ID_REQUIRED") if request.get("evidence_level") not in LEVELS: raise ValueError("INVALID_EVIDENCE_LEVEL") pack = request.get("evidence_pack") @@ -458,7 +458,7 @@ System Prompt: 规则: 1. field_id、scope 和 line_number 必须与 target_field_json 完全一致。 -2. line 字段只能处理目标 line_key 所对应的证据,不得串行。 +2. line 字段只能处理目标 draft_line_id 所对应的证据,不得串行。 3. suggested_value 必须能在该字段证据中逐字证明;quote 必须是证据中的逐字短引文。 4. 不得翻译、改写、格式化、补零、推算、合并或猜测字段值。 5. confidence 只是建议强度,不能替代逐字证据。 @@ -1080,7 +1080,7 @@ Dify 节点级错误使用 Fail Branch;画布不配置循环、自动重试或 | R01 | 合法 L1 单字段证据 | REVIEW | 返回一个建议或空建议 JSON | | R02 | 合法 L2/L3 请求 | REVIEW | 只使用命中表/页的最小证据 | | R03 | 两个 target_fields | REVIEW | `INVALID_REQUEST`,不调用 LLM | -| R04 | line 字段无 line_key | REVIEW | `INVALID_REQUEST` | +| R04 | line 字段无 draft_line_id | REVIEW | `INVALID_REQUEST` | | R05 | 模型返回非 JSON或错 field_id | REVIEW | `INVALID_MODEL_OUTPUT` | | R06 | 模型值不在字段证据中 | REVIEW | 后端 `validation_failed`,不能接受或修改 | | R07 | Dify 超时/不可用 | REVIEW | 后端 `provider_unavailable`,人工复核不中断 | diff --git a/docs/features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md b/docs/features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md index 1bd7c357..2f54274b 100644 --- a/docs/features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md +++ b/docs/features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md @@ -65,7 +65,7 @@ post-OT wave: ```text shipping_notice / OT -line_key +snapshot_line_id line_index inventory_snapshot_id match_result diff --git a/docs/features/shipping-notice/process-gate-recovery-contract.md b/docs/features/shipping-notice/process-gate-recovery-contract.md index 2c1b905b..1ec889d7 100644 --- a/docs/features/shipping-notice/process-gate-recovery-contract.md +++ b/docs/features/shipping-notice/process-gate-recovery-contract.md @@ -72,6 +72,7 @@ - **业务用户**仅可见 `PROCESS_GATE_BUSINESS_USER_ACTION_CODES`;技术重试不对业务投影。 - 库存源路由额外动作:`adopt_rule_suggestion`、`keep_manual_inventory_decision`。 - **禁止**业务用户人工选择/切换 PDF Profile;`open_profile_review` 仅导航至只读模板区。 +- **禁止跨 Gate 内嵌产物(2026-09-06)**:Worker Gate 的产物工作(生成 Excel、货代 RPA)必须在本 `gate_code` 的 Attempt 内执行;禁止在上游 Gate Attempt 内通过 `try_auto_chain_after_match` / 直接 workflow 调用完成下游职责。`_orchestrator_internal_dispatch` 仅表示「已在本 Attempt 内直跑本 Gate workflow」,不得用来在 `inventory_matching` Attempt 内生成 Excel。开心路径:`match pass → complete → enqueue → artifact_generation Attempt → generate_excel(_task_payload)`。`SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED` / `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 只控制是否自动入队对应 Attempt,不表示在 match 内直跑。 --- diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 6dbb8923..e64ec82f 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -19,6 +19,7 @@ - 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。 - `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。 - **OT 阶段随 Gate 推进回写(2026-08-26)**:`_refresh_execution_pointers`(Gate 状态/指针刷新的唯一收口)在 Execution 已绑定任务时补调 `sync_order_task_stage_for_notice`,使 `shipping_order_tasks.stage/status` 与当前 Gate 事实一致(如 `manual_upload_handoff` → `freight_uploading/blocked`),避免右侧「当前任务」主卡/批次投影停留在旧技术阶段(如 `excel_generating`)。建单前执行(无 task_id)不触发。 +- **履约 Gate 编排分离(2026-09-06)**:`inventory_matching` Attempt 只做匹配 + `sync`;`complete(passed)` 后由 `_enqueue_auto_progress_after_gate_pass` 入队独立 `artifact_generation` Attempt,再由 `_handle_regenerate_excel` / `_task_payload` 调用 `generate_excel`。禁止 `try_auto_chain_after_match` 在匹配 Attempt 内嵌 generate/upload;`AUTO_GENERATE_EXCEL` / `AUTO_UPLOAD` 仅控制自动入队。详见 [process-gate-recovery-contract.md](./process-gate-recovery-contract.md) 与计划 `docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md`。 ### Dify 配置边界(2026-08) @@ -29,17 +30,37 @@ - `Case/Draft.field_conflicts`、Candidate Qualification 和 Process Gate 必须读取同一份当前开放冲突事实;UI 不得用过滤后的空列表覆盖资格层仍未解决的冲突。真实冲突缺少可裁决值时必须保留为 Review Finding,不能降级为“无冲突”。 - “保存订单并校验”是唯一确认入口。后端先保存 Draft,再在同一业务链路重新计算必填、证据、冲突、重复、客户确认和自动建单策略门禁;只有 `auto_create_enabled=true` 且全部自动建单门禁通过时,才返回 `can_auto_create=true` 并进入建单,否则返回稳定阻断原因及可执行的 Review 动作。 - Review Gate 或字段冲突发生变化时,即使生命周期 `stage/status` 不变,也必须递增 `progress_version` 并写入对应审计事件。Review 工作台、聊天投影和任务详情均按该版本刷新,禁止以前端旧 Projection 推导按钮。 -- 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;`upload_status=uploaded` 是终态成功事实,投影不得被遗留的 `upload_rpa_pending`、失败或未知原因重新降级。 +- 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;Notice 面成功词唯一为 `uploaded`(经 `project_notice_upload_status`;Attempt 库内仍写 `succeeded`)。业务完成用 `has_verified_upload_success`;`facts.upload_state` 成功词为 `succeeded`(`project_facts_upload_state`)。禁止调用方再读 Attempt 原词或扩同义词集合。 - `resolve_field_conflicts` 仅在当前 Case 仍存在开放字段冲突时展示;Case 已无开放冲突时,旧 Projection 中残留的该动作必须被前端隐藏,同时以后端 `ui_state.actions` 为最终动作契约。 - Dify 的 Review 建议只能消费 HXOPS 下发的最小脱敏证据并返回候选建议,不能改变 Gate、Projection、Candidate 或 Task;建议不可用时人工复核和确定性主链仍可继续。 +### 状态契约统一(2026-09-06) + +原则与分期计划见 [`docs/superpowers/plans/2026-09-06-shipping-status-contract-unification.md`](../../superpowers/plans/2026-09-06-shipping-status-contract-unification.md)。**以 Phase A 为模板**:单一判词、单点投影、硬切无历史兼容;禁止在业务/前端用 frozenset 或 `includes([...])` 扩同义词。 + +| Phase | 主题 | 状态 | 规范做法摘要 | +|---|---|---|---| +| **A** | Notice `upload_status` / `facts.upload_state` | **已完成** | 投影成功词分别为 `uploaded` / `succeeded`;完成谓词 `has_verified_upload_success` | +| **B** | human-wait 跨层 | **已完成** | Wire `user_status` 只认 F2(含 `waiting_human`);停发 `idle`;`status_label` 不再发 `pending_review`;FE 删 LEGACY-UNIFY / idle 双认 | +| **C** | `match_status` 同名多域 | 待做 | 拆 `inventory_match_status` / `profile_match_status`;STP 禁用 `matched`/`shortage` 冒充履约;行级只发 `inventory_matched`;无旧字段双读 | +| **D** | reason / automation | **已完成(D1b+D2)** | 货代聚合停发/停读 `pending_human_reason`;`project_job_status_outcome` 为 Job→outcome 唯一 mapper | +| **E** | 入口卫生 + 门禁 | **已完成(最小门禁)** | `test_shipping_status_contract_hygiene` 禁 projector 外 synonym 袋;货代 FE 零 `pending_human_reason` 字符串 | + +**故意保留的双层**(勿当同义词债合并):Gate→`user_status`;五段 `lifecycle_stage` vs 15 段 processing stage;`lifecycle_status` vs runtime status;STP 诊断节点 ≠ UI 真源;FileAsset.`upload_status` 属另一产品面。 + ### Run 解析期紧凑进度(2026-08-23) - `serialize_lifecycle_progress()` 只复用既有 Run、Unit、workspace Progress Event 与健康提示,输出 `lifecycle_stage`、当前/已完成步骤、最后活动、健康和稳定提示键;不新建事件表、SSE/WebSocket、队列或状态机。`layout_parsing_completed` 等完成型 event code 即使为兼容实时实体状态记录为 `running`,也必须作为已完成步骤。 - `serialize_review_run()` 只读取轻量进度,禁止为首屏进度加载完整 documents、candidates 或 `handling_items`。有正式 Task/Case 生命周期投影时,工作台继续以现有 `ui_state/lifecycle_entries` 为权威,Run 进度只覆盖解析尚未产生 Case 的窗口。 -- 页面在标题下使用既有五阶段导航加一行紧凑当前步骤提示;失败、取消、排队和健康阈值提示显示稳定原因文案,禁止暴露 Worker/Provider 错误正文。不得新增独立状态卡或占整行黄色横幅。 +- (2026-08-31 v2 收口)五阶段导航下方不再渲染常驻进度横幅;Run 级动态说明由右栏 `ReviewCurrentProcessingCard` 状态块内嵌承载(仅 `lifecycle_status ∈ {running, waiting, failed, cancelled}` 白名单;无 Case 瞬态才在导航下保留单行轻提示),失败、取消、排队和健康阈值提示显示稳定原因文案,禁止暴露 Worker/Provider 错误正文。不得新增独立状态卡或占整行黄色横幅。 - 重新解析、解析重试、库存/RPA/Excel 等已启动异步任务,以及“重新识别客户”后门禁通过并由后端启动自动推进,都在轮询刷新中复用同一投影;只打开客户选择、确认客户或其他同步人工操作时不显示伪造自动进度。门禁未通过仅显示后端阻断原因。 +### 状态展示统一与动态说明(2026-08-31) + +- 前端展示口径收口:`shippingProcessingLabels.ts` 新增 `resolveRunLifecycleUserStatus`(`RUN_STATUS_FALLBACK_MAP`:review_required→waiting_human,queue_backlog/processing_slow/processing_attention→running;原因码只能补充/细化用户态,不能覆盖 failed/cancelled/completed)与 `resolveExtractionActivityMessage`(白名单 {running, waiting, failed, cancelled};仅 running 可声称自动处理,诊断原因优先于步骤句;failed/cancelled 强制原因 key,禁止复用 step 文案)。`currentTaskUserStatus` 既有链(正式 OT ui_state → Case automation)末尾追加 Run 级兑底;completed/cancelled/未知不映射。 +- 动态说明内嵌在「当前任务」卡状态行下方(弱文本一行);仅 `REDUNDANT_DETAIL_REASON_CODES`(当前仅 review_required)且映射结果等于当前状态时隐藏,排队/偏慢/需关注等诊断信息一律保留;未知原因默认保留;不做字符串匹配、不做模糊关键词判断。 +- `current_activity`(聊天页/任务中心消费的文件级快照)与 `lifecycle_progress`(工作台五阶段投影)保持后端双投影不变;聊天页与任务中心的阶段 key 改走 `resolveOrderExtractionRunStageKey` 唯一出口,文案仍为 `shippingOrderExtractionUserStage.*`/`shippingOrderExtractionCardTitle.*`,视觉零变化。设计详见 `docs/superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md`。 + ### 本次 Dify 手工核对(管理员执行) 本次无需新增 Dify 节点、变量、Prompt 或 Tool,也无需让 Dify 输出进度。管理员只需在发布前核对:`shipping_notice` Chatflow 未订阅 Run/Unit/ProgressEvent、未根据模型判断输出阶段或完成状态、仅保留只读 `get_task_status`(如启用)及隔离的最小 Review 建议分支;任何订单解析、门禁推进、客户确认、库存、Excel、RPA、人工上传确认或写入 Tool 均必须禁用。Dify 不可用不能阻断本次五阶段进度展示或订单主链。 @@ -53,6 +74,7 @@ - 原 PDF 是不可变源事实。`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口:当前 Layout -> Run 快照补缺 -> 原生 PDF -> OCR;返回合并后的当前 Layout。任一关键坐标无法取得时固定输出 `coordinate_evidence_unavailable` 并进入 `review_required`。 - **Reservation ID 专区动态锚点(2026-08-25)**:仅当已选中模板定义了 `reservation_id_region` 时启用。该配置不再以保存时的 `page_no/region` 作为正式取值位置,而是补齐全文页面坐标证据后,按阅读顺序从首次 `Vendor Comments` 标题之后累计到首次 `Terms and Condition` / `Terms and Conditions` 标题之前;区块可跨页。只在此封闭区块内解析带 `Reservation` 标签的合法 5/10 位数字,并复用既有行号归属和冲突规则。缺失任一起止锚点、边界顺序异常或值冲突均固定进入 Review,禁止自动猜测;未定义该专区的模板不扫描全文,原解析行为不变。 - `matching_features.v1` 在压缩 `page_glyphs` 前持久化页面结构、主表框、表头及顺序、列数/中心/宽度和静态字段关系。它是稳定匹配输入,不升级命名;缺少关键特征不得从评分分母剔除后形成 `hard_match`。 +- **坐标证据外置为 FileAsset(2026-08-26/30 决策)**:`coordinate_evidence` 不再内联在布局快照的 `payload_json` 中。`record_inline_layout_snapshot` / `complete_layout_version` 在证据含非空 `page_glyphs`/`tables` 时,将其外置为派生 `FileAsset`(`asset_role=layout_coordinate_evidence`、`application/json+gzip`),从 payload 移除 `coordinate_evidence` 并写入轻量 `coordinate_evidence_ref`(`{asset_no, checksum, size, schema_version}`)。PDF 布局仅当 `coordinate_evidence_ref.asset_no` 存在时才视为 ready:否则 `complete_layout_version` 回退 `failed` 并写入 `shipping_document_layout_coordinate_evidence_incomplete`;仅当外置资产持久化失败时才写入 `shipping_document_layout_coordinate_evidence_persist_failed`。读取侧 `current_layout_snapshot()` 经 `_hydrate_coordinate_evidence` 从该资产回填 `coordinate_evidence`;`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口,优先使用当前 Layout(坐标来自外置资产 hydration),缺页再从原 PDF 原生字形/OCR 补齐。原 PDF 始终是不可变源事实。 - Profile 只识别版式身份;Schema 是唯一业务字段契约。订单头由 `page_glyphs + Profile field layout + Schema` 取值,订单行由 `table_glyphs + Profile table layout + Schema` 重建;两者共享同一个 Profile、Layout、Schema 和 `CoordinateTransform`。 - `CoordinateTransform` 统一处理归一化坐标及受限平移、缩放、小角度旋转。锚点不足、残差超限、越界、共线、非法矩阵或局部非线性失真必须 fail-closed,禁止强行命中。 - **参考页坐标帧(2026-08-25)**:编辑器继续保存 0..1 的画布区域,但坐标模板保存时必须从 annotation sample 的冻结 `coordinate_evidence.pages` 写入每页 `CropBox` 点尺寸。盲测与正式解析先以“相对区域 × 标注页点尺寸”恢复 PDF 点框,再读取当前页的同一物理点框;不得直接按当前页高度重投影。该规则覆盖“分页页与未分页长页内容位置相同”的场景,不需要复制模板;缺少参考页框的历史模板保持兼容旧投影,重新保存标注样本后才获得新契约。真实整体缩放/平移仍只允许由显式 `anchor_frame` 的稳定文档匹配锚点处理,禁止以订单字段在运行时拟合。 @@ -637,6 +659,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - **并发与幂等**:服务端快照计算 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 可建单,旧版永远保留审计。 +- **重解析终态闭环不变式(2026-08-30)**:PDF 级重解析后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream,或旧版 Case 已恢复为可编辑状态;新版缺失或激活被拒时转入既有失败恢复链(`finalize_document_reparse`),禁止旧 Case 停留在 `reparse_pending` 被孤儿化。前端配套:重解析完成后工作台落在历史版本时自动跳转 Stream 当前版本(版本历史面板显式查看除外),跳转失败必有可见报错。 - **变更边界**:Run 冻结解析器版本、策略版本、超时和最大尝试次数;运行时版本漂移安全阻断旧 Run。用户态 Run API 不返回正文、解析快照、原始结果或内部配置。 ### 2026-07-21 文档级抽取优化历史阶段与 Review 门禁 @@ -765,9 +788,9 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open ### 阶段 3 客户指纹绑定与冻结(2026-07-22) -- `ShippingOrderCustomerMatch` 为 Bill-to/Ship-to 分别保存订单原文、标准化组件、`order-customer-fingerprint.v1`、候选快照及确认审计;客户主数据不覆盖订单原文。 -- Bill-to 作为正式订购客户。人工确认必须指定启用客户并填写理由;Ship-to 仍可独立匹配站点,但不替代订购客户。影子识别仅用于质量评测,不能直接冻结。 -- `freeze_order_snapshot` 不再接受请求任意传入的客户 ID/简码,只读取当前 Extraction 已确认 Bill-to;Snapshot 同时保存客户 ID、简码和匹配规则快照。客户后续变更不回写已冻结 Snapshot。 +- 动态订单字段保存 Bill-to/Ship-to 原文及地址、编码等可识别证据;`ShippingCustomerShadowResolution` 保存已发布 Identity Rule Set 的证据、候选和确认审计。客户主数据不覆盖订单原文。 +- Bill-to/Ship-to 不表示正式客户角色。人工确认必须指定启用客户;唯一候选仅在自动确认门禁满足时写入 Resolution。客户确认是 Resolution 的独立事实。 +- `freeze_order_snapshot` 不接受请求任意传入的客户 ID/简码,只读取当前 OT 的已确认 Resolution;Snapshot 同时保存客户 ID、简码和 Rule Set 确认快照。客户后续变更不回写已冻结 Snapshot。 - 阶段 3 Dify 手工配置:无需修改画布。客户指纹、候选排序、确认理由与 Snapshot 冻结均由 HXOPS 执行;Dify 不返回 customer_id、客户简码或匹配结论。 **L7 第 4 阶段工程补充验收(2026-07-22)**:人工编辑 Candidate 的业务摘要时,系统在 `structured_result_json.manual_review_history` 追加编辑前摘要、冲突、校验状态、编辑人和编辑时间,避免“修订后清空冲突”丢失审计。自动建单 Binding 和每次 Run 均冻结 `quality_batch_id`;创建 Run 与 Worker 开始执行时都重新校验该批次的 Owner、Schema、阈值和双人批准状态。`auto_create_enabled=true` 的生产 Run 禁止作为影子质量标签样本,防止用生产结果反向证明质量。该子阶段历史 head 为 `a77f8091a2c3`;当前部署还必须继续执行 Snapshot、质量、客户指纹、滚动履约和 Attempt 迁移至 `023a4b5c6d7e`。阶段回归为 `129 passed`,迁移往返和 `git diff --check` 通过。 @@ -966,7 +989,7 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏 **表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。 **模板版本中心契约 Review(2026-07-28)**:订单模板管理入口升级为按 `profile_code` 聚合的版本中心。`draft / published / retired` 仍是唯一生命周期,但“查看版本”和“创建新版本”分离:查看任意 `published/retired` 版本只进入独立详情路由 `/admin/shipping-order-document-profiles/:profileCode/versions/:version`,不得隐式创建草稿。默认版本选择顺序固定为 `published -> draft -> 最新 retired`;URL 指定不存在版本时必须返回 404,不允许前端或后端自动改跳其他版本。版本详情固定包含 `配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用` 五个页签,其中配置概览优先加载,PDF 画布、审计、使用情况按页签懒加载。 -**历史画布与盲测隔离 Review(2026-07-28)**:历史样本画布必须显式区分 `edit` 与 `readonly` 两种模式,不能靠隐藏保存按钮伪装只读。`published/retired` 详情只允许切换样本、翻页、缩放、查看区域详情和复制为新草稿,禁止新建/拖拽/删除区域、重绑字段、撤销重做、自动建议写入、保存、OCR 重跑及样本解除绑定。画布读取只能使用发布时冻结的 Sample 绑定、Layout 版本、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;缺任一证据时明确失败,不允许回读当前最新布局。普通版本详情 DTO 只返回盲测套件状态、样本数量、通过/失败数量、批准时间和最近运行摘要,不返回 `expected_rows_json`、`expected_order_fields_json`、人工真值、可推导答案的坐标或未执行盲测 PDF 的完整身份。 +**历史画布与盲测隔离 Review(2026-07-28)**:历史样本画布必须显式区分 `edit` 与 `readonly` 两种模式,不能靠隐藏保存按钮伪装只读。`published/retired` 详情只允许切换样本、翻页、缩放、查看区域详情和复制为新草稿,禁止新建/拖拽/删除区域、重绑字段、撤销重做、自动建议写入、保存、OCR 重跑及样本解除绑定。画布读取只能使用发布时冻结的 Sample 绑定、Layout 版本、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;冻结页数必须来自同一原 PDF 的完整物理页证据,不能退化为含业务表格的页数;缺任一证据或页数不一致时明确失败,不允许回读当前最新布局。普通版本详情 DTO 只返回盲测套件状态、样本数量、通过/失败数量、批准时间和最近运行摘要,不返回 `expected_rows_json`、`expected_order_fields_json`、人工真值、可推导答案的坐标或未执行盲测 PDF 的完整身份。 **模板版本语义差异 Review(2026-07-28)**:版本中心 `diff` 页签已落地,统一通过 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/diff?against_profile_id={id}` 由服务端计算。未显式指定对比版本时默认上一版本;显式比较只允许同一 `profile_code`,跨模板立即阻断。差异引擎按 `region_id / layout_id / field_id / anchor_id` 等稳定身份配对,坐标矩形统一使用 `0.001` 容差过滤浮点噪声,避免字段改名、排除区重排或序列化精度造成“删除+新增”误判。前端仅展示结构化 summary、变更项和折叠的安全 JSON 快照,不直接比较整份 definition,更不暴露正文、对象存储地址或盲测真值。 @@ -1150,7 +1173,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 #### 产品与状态边界 - 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 已有结果。EML 父卡只汇总子 Unit:`review_required` 的 PDF 保留自身 Review Case/`open_order_review`,`failed` 的 PDF 只显示自身稳定错误码和 `retry_order_extraction`,不得以 Run 终态撤销兄弟附件入口。 +- Unit 是 PDF 级处理单元,状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`;一份 PDF 的拒识或失败不得覆盖其他 PDF 已有结果。EML 父卡只汇总子 Unit:`review_required` 的 PDF 保留自身 Review Case/`open_order_review`,`failed` 的 PDF 只显示自身稳定错误码和 `retry_order_extraction`,不得以 Run 终态撤销兄弟附件入口。**聊天摘要与批次进度中心均按 PDF 状态 → EML → PDF 展示**:混合状态 EML 在对应状态区各显示一张只读聚合卡,每张仅含本区 PDF,并标注“本组 x/共 y”;状态区标题计数统一为文件数,不得用 EML 总体状态或 EML 卡数把未完成附件混入“已完成”或显示为“任务”。 - **取消是请求语义,不是即时伪造终态**:Run/Unit 记录 `cancellation_requested_at / cancellation_actor_* / cancellation_reason* / cancellation_completed_at`;排队 Unit 可立即 `cancelled`,执行中 Unit 投影为用户可见阶段 `cancellation_requested`,Worker 仅在文件边界与外部副作用前安全点生效。已完成 Unit 结果保留。 - 同一 `user_id + owner_agent_id + conversation_id` 同时最多一个 `queued / processing` Run;不同会话可并行。现有 Intake 单活跃约束继续生效。 - 用户卡片只显示后端事实投影:Run 汇总、当前文件、当前业务动作、可操作按钮,以及按 PDF 打开的详情抽屉。用户端不再展示 Workflow、节点、Provider、LLM、伪百分比或内部运行标识。 @@ -1210,6 +1233,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 - 用户工作台主接口固定返回 `summary / current_activity / available_actions`;详情接口固定返回按 PDF 归并的 `documents[]`。所有计数、当前活动和按钮权限均由后端计算,前端不得自行猜测。 - 计数必须以 Unit 事实为准,禁止依赖可能滞后的批次摘要自行重算。 +- 会话级 `summary` 存在两个口径,前端必须分开消费:`summary.submitted_files`(提交基主计数,来自冻结 `attachment_selection.selected_attachment_count` + 直传 PDF Intake 数,物化前即 ≥1、单调,用于「共 N 个文件」与批次总文件数卡)与 `summary.total_files`(已识别/活跃文件数,基于物化 `ShippingOrderDocument` 裁决,用作完成率分母与 `_*_files` 状态明细)。物化前 `total_files` 可为 0,此时前端显示「正在识别附件…」占位,并在「共 N 个文件」标签内联显示「已识别 n / N」,不得把 `total_files` 当作主计数误报「0 个文件」。 +- EML 聚合卡的子文件列表必须包含冻结选择计划中**已选但尚未物化/未识别**的附件(`facts.recognized=false` 诊断行),否则「已识别 n / N」会出现「少了一份文件」的排查盲区;未识别 PDF 显示「待识别」,`.xls/.xlsx` 显示「已忽略(非订单 PDF,不参与订单识别)」并从其父 EML 的处理中/待人工等状态卡剥离,进入只读「已忽略」分区(聊天摘要和批次进度中心均默认折叠,展开后显示对应 Excel 叶子);两者都只进列表与 `submitted_files`,**不进** `total_files` / `_*_files` 状态数。顶部摘要只要存在已忽略附件,均须在既有“共 x 个文件 · 已识别 n/N”后附加“y 个已忽略”;批次进度中心概览须单列已忽略数,并保持完成率及“已处理 N/M”仅以 `total_files` 的订单文件为分母;若其余订单 PDF 均完成,即使会话 `ui_state.status` 尚未收口,聊天摘要卡也必须显示完成、隐藏当前阶段,并改用“订单文件 x 个已完成 · y 个已忽略”;该展示例外不回写、不改变后端状态。 - 事件必须是已经发生并持久化的事实,前端只根据 `event_code` / `user_visible_stage` 做 i18n 文案映射;不允许把 Dify 节点标题或自定义显示文本当作业务阶段。 #### 事件、健康与恢复 @@ -1390,7 +1415,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 - 客户合并使用源客户的 `merged_into_customer_id` 和快照审计表 `shipping_customer_merges`。`GET /api/admin/shipping-customers/{source_id}/merge-impact` 返回历史保留引用与可迁移配置;提交合并需目标客户、源简码二次确认和原因。合并事务只迁移 `shipping_customer_identifiers` 与 `shipping_customer_external_refs`,业务单、业务流水、导入行、影子候选和人工标签均保持原引用;源客户状态设为 `merged`,新选客与识别入口只接受 `active` 客户。 - 客户创建、编辑、启停、简码变更及识别证据创建/审核/停用/自动匹配授权均写入 `ShippingCustomerLifecycleEvent` 快照;简码、状态和自动匹配授权属于高风险变更,服务端强制要求 `reason`。管理员通过 `/lifecycle-timeline` 查询单客户时间线。 - 自动确认除 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED` 外,还须通过 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES`(默认 20)及 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY`(默认 0.98)门禁。统计分母仅包括当前强规则会唯一命中的已人工真值样本;未达标返回降级状态、不绑定客户、不生成业务号。`/governance-quality` 和影子报告均返回门禁状态及阈值快照。 -- 识别规则发布快照同时冻结订单 Schema 的 `id/version/checksum`。影子解析证据保存 `field_value_id/decision_id/extraction_id/context_field_id/order_schema_version_id`;自动确认时重新读取并校验 FieldValue、accepted/corroborated Decision、Extraction 与历史规则集/Schema 快照,按冻结字段规则重新标准化。影子 JSON、当前 Schema 或当前定义表均不能单独授权自动确认。 +- 识别规则发布快照同时冻结订单 Schema 的 `id/version/checksum`。影子解析证据保存 `field_value_id/decision_id/extraction_id/context_field_id/order_schema_version_id`;自动确认时重新读取并校验 FieldValue、accepted/corroborated Decision、Extraction 与历史规则集/Schema 快照,按冻结字段规则重新标准化。自动确认规则集自身仍按 `id/version/checksum` 强一致(防篡改);Schema 锚点则从「版本级强一致」放宽为「语义契约一致」——仅要求解析所用 Schema 版本真实存在(published/retired)且规则集冻结定义在新 Schema 中`field_code/scope/value_type/normalizer_key/available_for_customer_identity` 语义兼容,从而容忍 Schema 常规重发布造成的版本错位,但拒绝字段语义变化(此时自动确认 fail-closed 回人工复核)。影子 JSON、当前 Schema 或当前定义表均不能单独授权自动确认。 - 业务编号直接归属于 `ShippingNotice`,不再存在独立业务单聚合或 `ShippingCase`;一个 PO 可产生多个 Notice,每个 Notice 持有唯一 `business_no` 并只关联一个 Excel。 - 流水表按 `(business_type, customer_id, business_date)` 唯一,使用 PostgreSQL 原子 upsert/returning 分配,`business_no` 唯一约束提供最终保护。 @@ -1424,11 +1449,11 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 | 3 | 客户影子识别 | 只记录候选不阻断;真实历史样本形成准确率报告;误自动匹配为 0 | | 4 | 客户人工确认 Gate | 所有后续副作用入口均不可绕过;客户确认事件完整审计 | | 5 | 业务编号生成、查询和展示 | PostgreSQL 并发无重复;修订继承、强制新建重新编号;双号查询通过 | -| 6 | 有限自动识别、监控和纠错 | 仅已审核强规则自动放行;可降级;质量指标与纠错审计可查询 | +| 6 | 有限自动识别与监控 | 仅已审核强规则自动确认 OT 客户;可降级;质量指标可查询 | 每一阶段完成前必须执行本阶段代码 Review,按严重度列出全部发现、修复后重跑对应测试,并逐条核对验收标准;存在未处理高风险问题时不得进入下一阶段。 -阶段 6 的客户纠错仅限管理员:已编号且尚未上传货代的业务单保留原号并标记 `voided`,创建 `replaces_case_id` 指向原单的替代业务单并按正确客户申请新流水;任务版本链迁移到替代单,旧号查询跟随替代链返回当前版本,纠错原因与新旧编号写入 `ShippingTaskEvent`。已上传货代的任务必须先完成外部作废流程,系统内纠错接口明确阻断。 +阶段 6 的自动确认仅发生在 OT:满足已审核强规则、唯一命中及质量门禁时写入客户确认结果;不创建 Notice、不分配业务编号。正式 Notice 创建是客户不可变边界,创建后不提供客户替换或重建能力。 ### 第三阶段:业务去重与任务版本(实现摘要) @@ -1764,10 +1789,10 @@ GET /api/admin/shipping-order-schema/published-contract - **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。 - **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。 - **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。 -- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以页面提示或上传历史证据判定 → 回调。 +- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。 - **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。 -发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改,`field_code` 重命名仅影响后续草稿,历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。 +发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改;**同一 field_id 的 `field_code` 一经发布不可变更**(改名 = 退役旧字段 + 新建字段,允许同一 `field_code` 漂移到新 `field_id`),历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。 # 发货 Excel 模板 @@ -1808,7 +1833,7 @@ GET /api/admin/shipping-order-schema/published-contract - 业务人员只看到五阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。 - 用户点击删除时,服务端以任务行锁重算资格并写入 `ShippingTaskEvent` 审计(操作者、请求 ID、原因和处置前后事实)。纯误建任务仅进入回收站;已有业务单、Candidate 消费、库存链接或导出 Artifact 的任务同时设为 `voided` 后进入回收站。存在修订后继的任务禁止 delete/void,只允许 archive,避免破坏版本链。 -- `upload_status` 为 queued/pending/running/uploading/uploaded/succeeded/success、存在货代参考号/回执时,平台禁止 delete/void,只允许 archive。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。 +- Notice 面 `upload_status`(经 `project_notice_upload_status`)为 pending/uploading/uploaded/failed/unknown 等契约词、或存在货代参考号/回执时,平台禁止 delete/void,只允许 archive;判定成功只认 `uploaded`,禁止再认 Attempt 原词 `succeeded`/`success`。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。 - 回收站只允许恢复仍为 `active` 的纯误建任务;已作废或已归档任务不得恢复,必须走受控新建/修订业务流程。永久删除仅在第五阶段实现,并重新检查全部引用。 - `POST /api/workspace/shipping-tasks/batch-purge` 仅管理员可调用;只允许清除回收站内、仍为 `active` 的纯误建任务。清除前事务内统计业务单/批次/来源文件/Intake/Candidate/Extraction/订单行/冲突/库存链接/Artifact/临时库存会话/修订与重复引用/外部上传事实/非处置事件;任一存在返回 `SHIPPING.TASK_PURGE_BLOCKED`。成功后写入无 `task_id` 外键的 `shipping_task_purge_audits` 快照,再物理删除 Task。 - 后台编排器、通用 Job worker、库存 RPA 触发与库存/上传 RPA 回调均先读取 `task_execution_block_reason`。非活动任务作为 `skipped` 收口,迟到的库存回调只完成原始回调文件消费/归档,不能再创建任务库存链接、生成 Excel 或写上传结果。 @@ -1817,9 +1842,11 @@ GET /api/admin/shipping-order-schema/published-contract # SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true # SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true # SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true +# 是否在 match pass 后自动入队独立 artifact_generation Attempt(禁止在匹配 Attempt 内直跑 generate)。 # SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true # 真实上传 Worker 默认关闭。先配置 URL、文件/提交/成功 selector,并在非生产环境 dry-run。 # 只有成功标识出现才回调成功;最终提交还须由 Worker 的二次确认开关控制。 +# 是否在 artifact pass 后自动入队 freight Attempt(禁止在匹配 Attempt 内直跑 upload)。 # SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false # SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true # 当已发布 Excel 模板未定义 filename_pattern 时使用;模板规则优先。 @@ -1873,7 +1900,7 @@ GET /api/admin/shipping-order-schema/published-contract $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" -python scripts/rpa/freight_rpa_worker.py +python scripts/rpa/inventory/inventory_rpa_worker.py ``` ### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端) @@ -1941,24 +1968,24 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { 从项目仓库复制以下文件到 Windows RPA 主机: ```text -scripts\rpa\freight_rpa_worker.py -scripts\rpa\dsv_report_parameters.py -scripts\rpa\dsv_login_smoke.py -scripts\rpa\run_inventory_batch_trigger.py +scripts\rpa\inventory\inventory_rpa_worker.py +scripts\rpa\connectors\dsv\dsv_report_parameters.py +scripts\rpa\connectors\dsv\dsv_login_smoke.py +scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 放置为: ```text -C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py -C:\HxopsRpaTest\scripts\rpa\dsv_report_parameters.py -C:\HxopsRpaTest\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaTest\scripts\rpa\run_inventory_batch_trigger.py +C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaTest\scripts\rpa\inventory\run_inventory_batch_trigger.py -C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py -C:\HxopsRpaProd\scripts\rpa\dsv_report_parameters.py -C:\HxopsRpaProd\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaProd\scripts\rpa\run_inventory_batch_trigger.py +C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaProd\scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 @@ -2037,6 +2064,9 @@ $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\brow $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" +$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" @@ -2093,7 +2123,7 @@ cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount 先验证 DSV 登录: ```powershell -python scripts\rpa\dsv_login_smoke.py +python scripts\rpa\connectors\dsv\dsv_login_smoke.py ``` 成功时会看到: @@ -2105,7 +2135,7 @@ SUCCESS — DSV session ready 库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: ```powershell -python scripts\rpa\run_inventory_batch_trigger.py +python scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 @@ -2275,27 +2305,30 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 sudo systemctl restart hxops-backend ``` -如果使用 Docker Compose,需把挂载目录映射进容器: +如果使用 Docker Compose,需把挂载目录映射进**写 RPA trigger 的容器**(`hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker`;按需库存准备由 shipping-worker 写入): ```yaml +# 三个服务均需: volumes: - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data ``` -容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。 +容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。变更挂载后须 `--force-recreate` 相关服务,否则旧容器仍写本地假目录。 #### 1.5.10 Windows RPA 主机:进程级环境与自启动 同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。 -DSV 库存导出默认使用一次性浏览器 Profile。仅在一个对应环境 Worker 运行时,启动命令可显式追加 `-ReuseDsvSession`:Worker 只为 DSV 库存任务保留独立 `dsv360_session` Profile,后续任务会优先复用登录态;会话失效仍回落现有登录流程。Crane 与上传任务保持一次性 Profile,且不得并发启动两个共享同一 WorkerRoot 的 Worker。 +库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`;旧参数 `-ReuseDsvSession` 仍兼容。 + +Worker 本机磁盘保留(`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。 Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass: ```powershell -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1" -Environment test -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" -Environment prod +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment test +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment prod ``` 若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。 @@ -2306,8 +2339,8 @@ Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和 ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod ``` 默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。 @@ -2320,7 +2353,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" ` + "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2330,8 +2363,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 若脚本来自网络或压缩包,先确认路径并按需解除文件阻止: ```powershell -Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" -Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" +Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ``` `-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问: @@ -2346,7 +2379,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 连通性确认后,也可以使用仓库原始命令: ```powershell -.\scripts\rpa\start_rpa_worker.ps1 ` +.\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment test ` -ApiBase "http://测试后端:端口" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2356,7 +2389,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 手工启动 prod: ```powershell -C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 ` +C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment prod ` -ApiBase "http://正式后端:端口" ` -WorkerRoot "C:\HxopsRpaProd" ` @@ -2367,7 +2400,7 @@ C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 ` #### 1.5.11 端到端验证 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 -2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。 +2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py`。 3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。 5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。 @@ -2435,7 +2468,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log" -\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope: @@ -2450,14 +2483,15 @@ Get-ChildItem "$rpaDataRoot\inventory_drop" ##### 1.5.13.2 Linux 测试服务器:部署、启动与停止 -以下操作在**测试服务器的项目根目录**执行。首次部署按 `1.5.6` 至 `1.5.9` 完成 Windows 测试共享 `hxops-rpa-test-data` 的访问、`/mnt/hxops-rpa-test-data` 挂载及 `.env.test` 配置;不应使用正式共享目录。启动前确认 `docker-compose.yml` 的 `hxops-backend` 已 bind mount 测试目录到同一路径,否则宿主机虽已挂载,容器内仍无法写入 trigger 或读取导出文件。 +以下操作在**测试服务器的项目根目录**执行。首次部署按 `1.5.6` 至 `1.5.9` 完成 Windows 测试共享 `hxops-rpa-test-data` 的访问、`/mnt/hxops-rpa-test-data` 挂载及 `.env.test` 配置;不应使用正式共享目录。启动前确认 `docker-compose.yml` 的 `hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker` 均已 bind mount 测试目录到同一路径;只挂 backend 时,按需库存 Gate Job(shipping-worker)会写到容器本地假目录,Windows 共享盘看不到 trigger。 ```yaml +# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需: volumes: - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data ``` -确认挂载、设置 Compose 环境文件并启动后端及知识库 Worker: +确认挂载、设置 Compose 环境文件并启动后端、shipping-worker 及知识库 Worker: ```bash mountpoint -q /mnt/hxops-rpa-test-data @@ -2465,10 +2499,12 @@ test -d /mnt/hxops-rpa-test-data/inventory_triggers export COMPOSE_ENV_BASENAME=.env.test export COMPOSE_SHARED_ENV_BASENAME=.env.shared -docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker +docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker docker compose --env-file .env.test ps docker compose --env-file .env.test exec -T hxops-backend \ sh -lc 'test -d /mnt/hxops-rpa-test-data/inventory_triggers && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers' +docker compose --env-file .env.test exec -T hxops-shipping-worker \ + sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers' ``` 随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=test`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。 @@ -2485,9 +2521,10 @@ docker compose --env-file .env.test stop hxops-kb-worker hxops-backend ##### 1.5.13.3 Linux 正式服务器:部署、启动与停止 -正式环境步骤与测试环境相同,但全部路径、scope、Windows Worker、API Base 和密钥必须是正式环境值。首次部署按 `1.5.6` 至 `1.5.9` 配置 Windows 正式共享 `hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data`;仅在测试导出、账号、文件结构和回调均验收后才开启正式 RPA。启动前确认 `docker-compose.yml` 的 `hxops-backend` 具有正式共享的 bind mount: +正式环境步骤与测试环境相同,但全部路径、scope、Windows Worker、API Base 和密钥必须是正式环境值。首次部署按 `1.5.6` 至 `1.5.9` 配置 Windows 正式共享 `hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data`;仅在测试导出、账号、文件结构和回调均验收后才开启正式 RPA。启动前确认 `docker-compose.yml` 的 `hxops-backend`、`hxops-schedule-worker`、`hxops-shipping-worker` 均具有正式共享的 bind mount: ```yaml +# hxops-backend / hxops-schedule-worker / hxops-shipping-worker 均需: volumes: - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data ``` @@ -2500,10 +2537,12 @@ test -d /mnt/hxops-rpa-prod-data/inventory_triggers export COMPOSE_ENV_BASENAME=.env.prod export COMPOSE_SHARED_ENV_BASENAME=.env.shared -docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker +docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker docker compose --env-file .env.prod ps docker compose --env-file .env.prod exec -T hxops-backend \ sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers' +docker compose --env-file .env.prod exec -T hxops-shipping-worker \ + sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers' ``` 再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`;该参考仅作为受信 RPA 成功回调的外部参考,不要求人工录入或上传回执。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false`、`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工按业务单号确认已上传作为受控降级路径。 @@ -2832,18 +2871,16 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui ### STP 阶段 0:字段契约冻结(2026-07-30,项次派生 Phase 0 纠偏) - 标准资产 **58** 项;`shipping_order_fields` 唯一键为 `(field_code, scope)`,允许 Header/Line 同名 `reservation_id`。 -- 运行时投影:`line_key`、`effective_reservation_id = line.reservation_id ?? header.reservation_id`(经 `validated_reservation_id`);`line_no` 为可识别内部项次,不再由 `position+1` 覆盖。 -- `line_no` / `customer_po_line_no` 均在 `TABLE_FIELD_CODES`;可进入 LLM/坐标抽取。 -- Excel:废除 `system_fact:line_no`;导出行号为 `system_fact:export_sequence`(最终导出集上连续 1..N)。 -- Schema `definition_json.derivation_rules`(及 checksum):首期仅 `copy_if_empty`,目标仅 `line_no`;新草稿预置关闭规则 `customer_po_line_no → line_no`。 -- Snapshot 扩展约定:`rule_versions_json.derivation_rules_*`、`source_manifest_json.field_lineage`;审计事件词典见 `LINE_DERIVATION_AUDIT_EVENT_TYPES`。 +- 草稿行使用 `draft_line_id`;冻结档/库存准备使用 `snapshot_line_id` 与系统生成的 `line_no`;正式通知使用 `ShippingNoticeLine.line_no`。 +- `line_no` 不在 `TABLE_FIELD_CODES`,不进入 LLM/坐标抽取;`customer_po_line_no` 仍作为原始客户项次事实保留。 +- Excel 导出项次只读取 `ShippingNoticeLine.line_no`,每张通知单从 1 开始重新编号。 +- Schema 不提供派生规则;Snapshot 只保存字段来源血缘,不保存派生规则快照或校验和。 - 迁移:`4e7a1c9b2d3f_align_shipping_order_line_contract.py`(含内部项次语义纠偏);`5f8b2d4e6a1c_restore_shipping_context_field_assets.py`(恢复 `general_context` / `deterministic_context` 与 sender 种子)。 ### 项次派生 Phase 1–4(2026-07-30) -- **规则引擎**:`order_schema/derivation_engine.apply_derivation_rules_to_lines`;Admin `POST .../simulate-derivation` 写 `DERIVATION_SIMULATED`(路由层 commit);支持 `sample_ref=extraction:` 加载历史明细,以及 `GET .../derivation-simulate-samples`。 -- **运行时**:标准化后执行派生,写 `FIELD_DERIVED` / `FIELD_DERIVATION_SKIPPED`(含来源字段 `evidence_refs`),`normalized_result_json.field_lineage`;required 门禁在派生之后。 -- **复核覆盖**:`line_no` 须 `override_reason_code`;写入 `manual_override`+`locked` 与 `LINE_NO_OVERRIDDEN`;恢复清除锁定并写 `LINE_NO_RESTORED`(回退 machine_fields 识别/派生投影,不重跑引擎)。 +- **项次规则**:不再提供 Schema 派生、模拟、项次覆盖或恢复;订单解析/冻结/通知写路径分别按所属单据顺序生成不可变 `line_no`。 +- **字段血缘**:只保留原文字段来源与人工修改审计,不记录派生规则校验和。 - **复核投影**:`order_review_projection` 附加 `field_meta.value_source`;UI `ReviewLineNoOverrideDialog` + 来源徽章。 - **冻结与永久审计**:Snapshot 血缘快照;`append_shipping_audit_event` 新写入 `retention_expires_at=None`;迁移 `6a9c3e5f7b2d` 清空历史到期时间。 @@ -2857,7 +2894,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 路由引擎 `can_build` / `block_reason` 与历史 `status` 解耦:多候选 `ambiguous` 允许建单;零候选或 `require_manual_review` 阻断。 - `order_build_eligibility_service` 在 Draft 校验与确认前投影行级候选;人工选择须填写原因且库存源已启用。 -- API:`PUT .../order-review-cases/{case_no}/draft/lines/{line_key}/inventory-candidates`;Draft 投影含 `build_eligibility`。 +- API:草稿字段编辑使用 `draft_line_id`;通知准备库存源覆写使用冻结档 `line_no` 定位行;Draft 投影含 `build_eligibility`。 ### 门禁恢复阶段 0:库存源路由独立重算(2026-07-31) @@ -2874,9 +2911,9 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - `keep-manual` 明确保留人工值并清除 `suggestion_pending`; - 无人工决定且规则唯一可用命中时,建议直接成为有效结果。 - **API**: - - `POST .../draft/inventory-routing/reroute`(可选 `line_key`、`idempotency_key`) - - `POST .../draft/lines/{line_key}/inventory-routing/adopt-suggestion` - - `POST .../draft/lines/{line_key}/inventory-routing/keep-manual` + - `POST .../draft/inventory-routing/reroute`(可选 `draft_line_id`、`idempotency_key`) + - `POST .../draft/lines/{draft_line_id}/inventory-routing/adopt-suggestion` + - `POST .../draft/lines/{draft_line_id}/inventory-routing/keep-manual` - **审计**:`inventory_routing_*` 事件写入操作人、规则版本、前后候选与幂等键;同一幂等键只产生一次有效副作用;409 版本冲突不执行副作用。 - **前端**:复核台 `ReviewInventoryCandidatesPanel` 提供「重新匹配路由 / 采用规则结果 / 保留人工结果」。 @@ -2906,7 +2943,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - `prepare_candidate_inventory_lines` / `match_order_lines_across_candidates` / `apply_line_inventory_resolutions`。 - `ensure_inventory` 多候选合并准备;`match_inventory` STP 分支禁止回读路由;头级 Reservation 从 Snapshot Schema Header 字段读取。 -- Excel:`ALLOWED_SYSTEM_FACTS` 含 `export_sequence`;导出注入 `__export_sequence=1..N`(基于最终导出行集);自动链止于 `wait_manual_upload`。 +- Excel:导出注入已持久化的 `ShippingNoticeLine.line_no`(每张通知单从 1 开始);自动链止于 `wait_manual_upload`。 - 多源行级命中:`multi_source_excel_block`,首期不生成单一 Excel。 - **多源恢复入口(闭环)**:`shortage_review` + 多源/多文件冲突时 `ui_state` 前置 `confirm_inventory_source`;写入 `forced_match_source_code` 后过滤库存行并立即重匹配。`stp_facts.recovery_source_codes` 供工作台候选对话框种子;多源阻断时前端**禁止**回退展示 `inventory_source_resolution` 全部冻结候选。首期仍不提供自动拆单 API。 - 人工确认库存源与随后重匹配:工作台 `_trusted_user_id` 写入任务事件 `actor_id` 与统一审计;`match_inventory` 兼容 `operator_id` / `actor_id` / `_trusted_user_id`。 @@ -2961,7 +2998,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui | # | 场景 | 工程证据 | 状态 | |---|---|---|---| -| 1 | 可信直通停在待人工上传 | `auto_progress` / `try_auto_chain_after_match` 早停 + `forbidden_next_tools` | 工程通过 | +| 1 | 可信直通停在待人工上传 | `auto_progress` 早停 + `forbidden_next_tools`;匹配→Excel 经独立 `artifact_generation` Attempt(禁止 `try_auto_chain` 内嵌 generate) | 工程通过 | | 2 | 多 PDF 独立推进 | Unit/Case/Task 隔离;批次无履约门禁(既有抽取回归) | 工程通过 | | 3 | 人工复核后 auto_progress | 复核确认复用同一 `auto_progress` | 工程通过 | | 4 | 歧义/解析待办 | `must_human` + `todo_category=review` | 工程通过 | @@ -3110,7 +3147,7 @@ API 层 | `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | -| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | +| `scripts/rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | --- @@ -3147,7 +3184,7 @@ API 层 - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 -- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger` +- Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready` - **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts//`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 - **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。 @@ -3240,11 +3277,10 @@ API 层 匹配顺序: -1. Bill-to:`source_system + ShippingCustomerExternalRef.legacy_customer_key` → 标准名称 → 已审核名称别名。 -2. Ship-to:`source_system + ShippingCustomerSiteIdentifier(external_code)` → `ShippingCustomerSite.site_code` → 站点标准名称 → 已审核站点名称别名。 -3. 结果按角色写入 `shipping_order_customer_matches`,状态为 `unmatched / unique_candidate / ambiguous / confirmed`;Ship-to 人工确认必须同时校验站点属于所选启用客户。 -4. Candidate API 返回 `customer_matches` 供界面展示原文、标准客户、简称、站点与状态;确认接口为 `POST /api/workspace/shipping-order-extractions/{extraction_id}/customer-matches/{role}/confirm`,并校验 Extraction 所属 Intake 的用户权限。 -5. 唯一候选不绕过既有客户质量门禁。Task 建立后仍由客户确认链决定是否绑定业务归属客户和生成业务编号。 +1. 已发布 Identity Rule Set 从订单字段、邮件上下文和其他受控来源提取可识别证据,并按定义匹配客户主数据。 +2. 识别结果写入每个 Candidate 唯一的 `ShippingCustomerShadowResolution`,状态为 `unmatched / unique_candidate / ambiguous / confirmed`;`confirmed_customer_id` 是唯一确认事实。 +3. Candidate/复核 API 返回 Resolution 的候选、证据和状态;人工确认仅写入该 Resolution,并校验 Candidate 所属 Intake 的用户权限。 +4. 唯一候选不绕过既有自动确认质量门禁。OT 建立后仍由已确认 Resolution 决定是否冻结订单和生成业务编号。 #### Dify 手工配置要求 @@ -3452,3 +3488,96 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D | `POST /api/admin/receipt-rpa-units/{unit_id}/retry` | 管理员 | 仅 `failed/cancelled`,必填 `reason` | `shipping_receipt_rpa_unit_retried` | | `POST /api/admin/receipt-report-files/{file_id}/resend` | 管理员 | 仅重发归档文件企微消息,不触发 RPA | `shipping_receipt_report_notification_resent` | | `GET /api/admin/receipt-rpa-units?status=failed` | 管理员 | 只查询失败单元,供人工补偿;不返回凭据、对象键或 trigger 内容 | `shipping_receipt_rpa_units_listed` | + +# 2026-08-29 库存源自动探测与数据自证(一期) + +> 关联设计:`docs/superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md` +> 范围:多候选库存源订单在「通知准备」内的自动批次 RPA 探测、匹配数据自证反写、行级歧义兜底与人工选源;锁定边界统一为 Excel 生成。 + +## 结论摘要(决策 D1–D12) + +- 源裁决发生在**通知准备**,不阻断建单、不改订单复核契约;`inventory_source_routing` Gate 保持 `fulfillment_prep` 面。 +- 粒度=**行级**;任务级源=各行所选并集。 +- 主路径=**多候选自动批次 RPA**:单批次 trigger 文件含全部缺失候选源;已有 ready 快照的源跳过;逐源 Attempt 记录保留(身份/超时/重试/审计)。 +- 匹配=**数据自证**:全部候选源快照按行打 `__source_code` 标签参与匹配,按行反写 源/可用量/缺口。 +- 歧义兜底=行级:同一行在多源命中 → `multi_file_conflict` 阻断,该行出**源下拉**(候选 + 首选高亮 + 命中规则提示,写 `override_by_id/override_reason`,方法 `user_confirmed`)→ 该行重匹配;其余行照常。 +- 零候选行:不提供下拉,提示「规则未命中」,沿用 `retry_with_latest_rules`。 +- **锁定边界唯一:Excel 生成(Export Artifact 落库)**。此前(含匹配完成后)行源可改 = 换标签重匹配该行(候选快照已在本地,不重新 RPA);此后转只读,纠错走既有撤销/人工流程。 +- 波次通知(D8,已实现):`post_ot_fulfillment_wave_service` 创建波次通知**不再继承**首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,行级无规则命中时回退到订单级 task 候选集(与首单 `_collect_order_line_candidates` 行为一致,避免「无规则命中的波次行」卡死),随后走同一套自动探测/匹配/反写。测试:`tests/test_shipping_wave_rerouting.py`。 +- 订单复核确认/自动建单逻辑不变(多候选照常建单并自动推进)。 +- 原则边界:编辑窗仅覆盖「确认后、Excel 前」的人工纠错;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销。 + +## 通知准备内状态流转 + +``` +inventory_preparation Gate + ├─ 全部候选源有 ready 快照 → 直接加载匹配(现状) + ├─ 部分缺失 → 自动批次 RPA(仅缺失源)→ status=running「已触发库存获取」 + │ ├─ 批次回调逐源成功 → 加载 → 匹配 → 反写 → 续跑(匹配/Excel 门禁) + │ ├─ 部分源失败 → 成功源照常匹配;失败源相关行停等,沿用 + │ │ inventory_rpa_timeout/exhausted 恢复动作(reload/retry) + │ └─ 行歧义 → 行级 multi_file_conflict + 该行下拉 → 选定重匹配 + └─ 行级零候选 → 维持现状阻断 + retry_with_latest_rules +``` + +`inventory_file_missing` 不再是多候选的终态阻断原因(降为瞬态;RPA 失败仍走既有 `inventory_rpa_timeout`/`inventory_rpa_exhausted` 重试原因)。 + +## 实现要点 + +- `inventory_workflow.ensure_inventory`(`mode='auto'` 的 STP 多候选分支):删除「缺文件不隐式触发 RPA」,改为自动批次探测。`missing_files`/`partial_missing` 返回改为触发后 `running` + 「已触发库存获取,等待各库存源回调」;无候选集时维持 `needs_human`(`inventory_candidates_missing`)。 +- `per_source_rpa_service.ensure_all_required_sources_prepared`:不再逐源写 trigger,而是把全部 pending 源合并写入**一个** `inventory_export_batch_*.json`,逐源身份键(`task_no/attempt_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id/expected_warehouse_id`)进入 `inventory_sources[]`;批次写入失败时本轮新建 Attempt 统一置 `failed/trigger_not_written`。 +- `stp_line_inventory_match.match_order_lines_across_candidates`:按行打 `__source_code` 标签参与匹配;同一行命中多源 → 行 `disposition=multi_file_conflict` + `candidate_hit_source_codes`,`resolved_inventory_source_code=None`;唯一源命中按行反写 `resolved_inventory_source_code/available_qty/shortage_qty`;人工选源通过行 `allowed_source_codes` 钉住单一源后重匹配该行。 +- `process_gate_executor` 提供通知准备能力 `override_line_inventory_source`(参数 `line_no/source_code/reason`):校验行处于冲突、源启用、**通知未生成 Excel**(`task.export_file_path` 为空,否则 `SHIPPING.LINE_SOURCE_LOCKED`);写冻结档行覆写 + 仅该行重匹配 + 审计 `review_line_source_overridden`。 +- `ui_state._build_stage_context` 的 `preparation`:下发 `source_locked`(`task.export_file_path` 非空即锁定)、`lines[].source_ambiguous`(`multi_file_conflict`)、`lines[].source_candidates`(候选编码去重)、`artifact.status`。前端 fail-closed 消费。 +- 错误解释契约/原因码:行级冲突对应 `inventory_multi_file_conflict`,Owner 动作 `select_line_inventory_source`;「同一明细在多个库存源命中,请选择实际库存源」。 +- 前端 `ShippingOrderReviewView.vue`:阶段自动跳转成功后一次性 toast(`lifecycle.autoAdvanced`);清理 `workbenchMode==='reparse'` 死守卫;通知准备歧义行渲染源下拉 + 首选高亮 + 确认按钮,`source_locked` 行只读徽标。 + +## 既有能力与契约(不新增开关) + +- 沿用 `SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED` 总开关与既有批次开关;无新增配置开关。 +- RPA Worker 无需修改(batch v2 契约已支持多源逐源身份)。 +- 存量终态/已 `uploaded` 通知零影响;非终态停挡单首次进入工作台自动探测续跑(老单治愈)。 +- 无强制数据迁移:行级覆写复用候选行 `override_by_id/override_reason`;歧义状态入匹配结果 JSON/行决定。 + +# 2026-08-29 确认后订单编辑窗(二期) + +> 关联设计:`docs/superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md` §3。 +> 范围:确认后、首通知 Excel 生成前的订单人工纠错窗;锁定边界统一为 Excel 生成(D7/D10/D12)。 + +## 可编辑矩阵(谓词服务) + +- 谓词收敛于单一服务 `backend/app/services/shipping_notice/order_edit_window_service.py`(`editable_scope` / `order_has_active_attempt` / `assert_field_editable`),前端 fail-closed 渲染,后端保存守卫复用同一谓词(D12 原则边界集中化)。 +- **头字段**:该订单**任一通知**(含波次)无 Export Artifact **且** 无活动 Gate Attempt → `header=True`。 +- **行字段**:逐行——行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。 +- `ui_state.build_task_ui_state` 在 `include_stage_context` 时下发顶层 `edit_window`(同构 `{header, lines}`);前端 `ShippingOrderReviewView.vue` 据此禁用锁定字段/行源下拉。 + +## 保存守卫与失效重跑 + +- 正式字段编辑走既有 `task_workflow.update_notice_fields` / `update_notice_line` / `add_notice_line` / `remove_notice_line`(不新增 Case 状态);写路径保留 `_assert_order_data_version` 乐观锁(409 语义不变)。 +- **新增编辑窗守卫**:`_edit_window_busy_error`——订单任一通知有活动 Gate Attempt(库存 RPA / 匹配 queued|running)时返回 `SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`(「系统处理中,请稍后再修改」);活动 Attempt 结束后恢复可编辑。 +- **失效分类重跑**:沿用 Schema `task_edit_policy.change_effect` → `_apply_notice_edit_change_effects`: + - 头部路由字段 → `rerun_inventory_source_resolution`:清候选/匹配/导出、`clear_inventory_source_confirmation`、重裁库存源、OT 同步 `inventory_fetching`(快照复用,无新 RPA 当快照可用)。 + - 行字段(料号/数量/预约号)→ `rerun_inventory_matching`:仅清匹配并 OT 同步 `inventory_matching`。 + - 导出相关 → `regenerate_excel`;需重解析 → `require_revision`。 + - 无路由引用 → `none`(仅保存 + `order_data_version` 递增 + 审计)。 +- 被失效的匹配结果/缺口标记 superseded,界面显示「重新匹配中」;不产生新 Excel(Excel 尚未生成)。 +- 审计 `_record_formal_task_edit_audits` 写入 `applied_effects`(失效动作链)与字段 old→new + 操作人 + 证据(D10「不强填原因」)。 + +## 前后端契约 + +- 新增错误码:`SHIPPING.EDIT_WINDOW_FIELD_LOCKED`(字段超出编辑窗)、`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`(系统处理中);四语言 `locales/*/errors.json` 已补齐。 +- 前端类型 `ShippingTaskUiState.edit_window`(`ShippingOrderEditWindow{header,lines}`);`formalHeaderEditable()`/`formalLineEditable(lineKey)` 供模板绑定 `:disabled`。 +- **原则边界(D12)**:编辑窗仅覆盖「确认后、Excel 前」的人工纠错;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销。用户不修改原始订单的原则不被扩大解释。 + +## 验收对照(§3.4) + +1. 首通知 Excel 前改目的地(路由字段)→ 自动重路由+重探测+重匹配,指纹/审计/候选集版本正确(`rerun_inventory_source_resolution`)。 +2. 改未入波次行的数量/预约号 → 仅该行重匹配;该行已入已出 Excel 的波次 → 拒绝编辑(该行所属通知 Excel 冻结)。 +3. 匹配运行中保存 → `SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`;活动 Attempt 结束后可编辑。 +4. Excel 生成后头/行全部只读(`assert_formal_task_not_excel_frozen` / `is_excel_ready_for_task`)。 +5. 乐观锁版本冲突 409 行为不变(`_assert_order_data_version`);审计含失效动作链(`applied_effects`)。 + +## 二期状态补充 + +- 一期规划中的「快照重冻结 + `order_data_version` 递增」由既有 `update_notice_*` ⇒ `_commit_notice_edit` ⇒ `_apply_notice_edit_change_effects` 链路承担(编辑落库后依赖 `change_effect` 失效下游);`order_data_version` 由乐观锁 `_assert_order_data_version` 保护,避免重复冻结引入二次状态机。 +- 波次通知「按自身行重跑路由」(D8)已实现(见一期章节):不再继承首通知源,`freeze_wave_notice_routing` 按波次自身行冻结候选集;本二期不新增二次波次状态机,与一期波次路由冻结复用同一套链路。 diff --git a/docs/funclist.md b/docs/funclist.md index b0a603c1..994c5708 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -86,84 +86,98 @@ ### 货代发货通知(shipping-notice) -| 功能项 | 状态 | 说明 | -| -------------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 | -| 发货通知技术手册 | 已文档化 | 见[docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | -| 发货通知业务说明 | 已文档化 | 见[docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | -| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | -| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 | -| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake 快览:只解析邮件正文、白名单 HTML 表格快照和附件目录;上传阶段不抽取附件全文、不创建附件 FileAsset/Document、不生成 Candidate、不判订单重复;解析失败、超时、取消保持幂等 | -| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 | -| 版面解析并发与耗时诊断 | 已实现 | 独立 `hxops-shipping-worker` 默认双进程并行领取同批版面 Job;PDFium 先轻量预读字符但不裁决表格,MinerU 始终作为 PDF 表格结构首选 Provider;仅 MinerU 空表/失败时允许严格 PDFium 回退。Job `result` 平级保存脱敏 `timings`+`counts`(含 OCR/OpenCV/对齐细分与 `ocr_engine_warm`),worker 日志同步输出;诊断字段不进 layout snapshot,不记录原文/HTML/OCR 原始响应(PR-0)。PR-1:`SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED` 控制同 Job 整页 OCR 复用;PR-2:`SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED` 字符预读复用+按需补图,OpenCV geometry Job 内缓存;PR-3:`SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED` 表格裁剪 OCR(prod 默认关) | -| 对话输入框多附件统一提交 | 已实现 | 用户可分多次选择 EML/PDF;当前输入框内全部已就绪 Intake 在一次发送中冻结为同一个订单抽取 Run。`uploadBatchId` 仅用于单次上传幂等与状态关联,不再截断发送范围 | -| 无框订单明细表原生 PDF 回退 | 已实现 | 仅当 MinerU 未输出表格、PDF 原生文字坐标完整且同页命中多个通用明细表头时,从表头到合计行生成待配置候选表;正常 MinerU 表格路径不变,解析器修订 `v4` 防止复用旧零表格缓存 | -| 点击发送完整订单抽取 | 已实现(终态分阶段) | Run 冻结文档、Schema、模板 Profile、路由/评分/门禁与解析器版本;Worker 执行异型模板或通用确定性解析;完整性门禁与紧急停止控制自动冻结;Dify 仅提供复核最小证据建议且不得自动冻结;上线清单见 order-extraction-go-live-checklist.md | -| 相同附件跨批次 Workflow 复用 | 已实现 | 同会话完整附件 `content_hash` 集合与 Schema 版本相同时,复用活跃或未关闭 Run/Workflow Item;新上传批次、Intake/Document ID 或文件名不再导致重复 Workflow | -| 订单识别生命周期反馈 | 已实现 | Run 状态卡按真实确定性解析进度和终态计数更新并持久化到 `ChatLog.payload`;聊天历史可恢复,侧栏显示未查看终态提醒,处理中不伪造百分比 | -| 处理进度细化与全链路审计 | 已实现 | 阶段 0–5 + 正式评审整改:排队/处理中分列、文档级健康提醒与最后活动、管理员取消任意 Run(代取消必填原因)、审计完整筛选(含 conversation/session_item/review_case/owner)、敏感访问审计、取消 operation_id 串联、进度事件真实状态、库存/RPA/导出双写统一审计。Run 级 `handling_items`/`primary_notice` 拆分待补信息/冲突/自动冻结受阻/PDF 复核/技术失败/预算停扩,聊天卡与右侧「本次处理」按原因展示并跳转。灰度开关 `PROGRESS_UI_V3`/`ORDER_EXTRACTION_CANCEL`/`AUDIT_EXPORT`;审计保留 `SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095`。Dify 无需改画布 | -| 会话 PDF 工作项(阶段 0–4) | 已退役 | 已由 Workflow 台账替换;旧验收文档已删除 | -| Workflow 阶段 0–2 底座与投影 | 已实现 | 删除 session work items;Workflow/Item/Version/Event;进度投影与会话轮询;见 `workflow-stage0-acceptance.md` 与 technical.md | -| Workflow 阶段 3 确认后自动进度 | 已实现 | 五门禁(批准模板/字段完整/证据/冲突重复/质量)失败仅 Review Case;确认返回 `shipping_notice_no`/`order_task_no` 并推进履约;复核页 `ReviewWorkflowProgressPanel` 读统一 OT 投影;建单后取消 Task `pending_void`+Excel 只读;移除工作台 upload-inventory/mark-manual-uploaded/retry-upload 写入口 | -| Workflow 阶段 4 任务中心与审计闭环 | 已实现 | 任务中心进行中 2s/8s 自动刷新;时间线合并 Workflow Event;审计关联链/敏感读权限/哈希日检;删除复核监管台 | -| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 | -| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | -| 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序 | -| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) | -| **XFA 数据路径 Profile(统一回退)** | 代码收口(2026-08-18) | datasets + 拆分规则为首选;失败进入普通 PDF 共用 PDFium/Widget/OCR 证据链,保留 `fallback_from`、原因码与 `value_source`,回退候选固定 Review、禁止 STP;Dify 主链:**NONE**。 | -| **XFA 统一视觉标注 + 字段拆分** | 统一入口已收口 | 普通 PDF/XFA 共用 Editor、`/pdf-automark` Job、保存、验证和发布 DTO;`value_binding` + `visual_binding`、RE2、统一 CQ/STP;XFA 仅在首选 datasets 取值与拆分规则上保留适配器差异。 | -| **旧 XFA 合成预览/OCR 专用入口** | 已废弃 | 浏览器不得调用 `/xfa/automark`;内部 XFA 多源执行器由统一 `/pdf-automark` 调用,原生 PDF 页是统一画布。 | -| **XFA 字段拆分映射(历史)** | 已被统一方案接管 | 早期 `stages[]` 流水线与独立映射页能力将在统一方案阶段 1/4 对齐并收口;对照文档:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。 | -| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 | -| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 | -| **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF**默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 | -| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(正式 OT 后分层已落地) | Case 切换请求代次 + 瞬态清理;正式 OT 后右侧主卡切自动处理、订单检查折叠、系统等待不冒充人工待办;`profile_match` 四态 + `field_completeness`;`completed_checks` 后端投影;`automation.phase` 区分建单前/后文案。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 | -| **OT 后行级自动履约(明细合并 + 匹配事实)** | P0+P1+P2+布局/动作分域已落地;flag 默认关 | 明细只读库存源;库存浮层仅 preparation/matching;关闭在更多操作;Case 兜底仅无行投影失败;15 阶等宽+布局清理。flag 保持 false。冻结:[post-ot-line-auto-fulfillment-freeze.md](features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md)。 | -| **双工作台架构 + Candidate Qualification(阶段 0–6)** | 阶段 0–6 达标(评审整改后) | **已完成**:双工作台边界;Candidate Qualification(追加式快照 + 审计);模板审批不再硬阻断自动建单;对话「本次处理中」轻量侧栏;复核返回对话;货代上传 RPA 可按 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 接入自动链;Process Gate 对话内恢复;审计事件字典含 chat_* / qualification / upload_rpa。权威:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 | -| **对话侧 Task 进度与「本次处理中」** | 阶段 2–5 已实现 | 侧栏以用户可见任务(OT)分组为主路径;`ShippingConversationProcessingCard` + processing API;`WF-...` 下沉;发送走统一提交无确认框。 | -| **会话多任务聚合与统一提交(阶段 0–5)** | 整改中 | 契约冻结(§1.6.1);统一提交 + 独立 submission 幂等;同 PDF 指纹继承 OT(跨 Schema);投影按「当前有效最新 Run」;未查看 completed 仍可见;任务级取消/重试均走 Run API;状态四语言 + 更新时间。权威:technical.md §1.6.1。 | -| **多 EML / 直接 PDF / PDF 优先全链路重构(阶段 0–7)** | 蓝图 §六 表层基本对齐;workflow/batches DROP 推迟 | `co4`–`co7`:接入层、Notice/履约、`order_tasks`/evidences/notice_lines/document_versions、`processing_runs/units/plans/route_decisions`。待:DROP batches/workflows、FE 去旧 Workflow。 | -| **Candidate 统一自动建单资格** | 阶段 1 已实现 | 新增 `candidate_qualification_contract/service`、表 `shipping_order_candidate_qualifications`;三种解析来源统一门禁;模板批准仅 parser_trace;移除 LLM 天然阻断;STP 自动建单前持久化资格快照。 | -| **后台顺序自动推进 + Process Gate 对话恢复** | 已实现 | 自动链:库存准备→匹配→库存 RPA→Excel;货代上传 RPA 须 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 显式 true 且通过就绪校验。RPA 中投影 `upload_rpa_pending` / `is_waiting_manual_upload=false`。对话侧 ProcessGateRecoveryCard;技术重试上限 3。 | -| **建单前统一恢复协调器(Gate/资格/auto_gate)** | 进行中(P0 缺陷已修,待正式验收) | `order_review_resume_service` + 行级履约 fail-closed(库存重校验、task 行不可 reopen、审计 before/after);复核侧栏置顶业务阻断,履约表格在库存模式;业务审计含白名单快照。权威:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md)。 | -| **双工作台审计闭环** | 已实现(阶段 6) | 事件字典冻结 chat_* / review_* / process_gate_* / qualification / workflow_node;对话恢复写 `chat_process_gate_*`;审计中心分组与 Candidate/Gate 筛选;普通账本脱敏 + 敏感快照独立鉴权;覆盖率举证见 AUDIT_COVERAGE_MATRIX。 | -| **复核字段精确高亮(阶段 0–5)** | 已完成(盲测样本集另立) | 冻结 `shipping-field-highlight-v1`;原生唯一 glyph / OCR candidate / Cell 来源分级;证据 API 全量 `highlight_quality`;工作台 verified 实线 / candidate 虚线;坐标诊断与 list/focus/restore/version 审计齐全;`review_coordinate_corrected` 事件已冻结(人工改框写路径待模板标注扩展)。权威契约:[field-highlight-contract.md](features/shipping-notice/field-highlight-contract.md)。 | -| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。**阶段 0–5 已落地**:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。**项次派生 Phase 0–4**:`line_no`=内部项次、`export_sequence`=导出行号、Schema 派生模拟、运行时派生审计、复核覆盖锁定与 `field_meta` 投影、冻结血缘。**库存源路由独立恢复(门禁恢复阶段 0)**:复核台可按最新已发布规则与库存源启停重算路由(不重识别 PDF);人工决定优先且不被静默覆盖;支持采用规则建议 / 保留人工结果;幂等键与审计前后快照齐全。首期不触发货代 RPA 上传、不改 Dify | -| **全门禁级中断恢复(契约冻结)** | 已实现(P0–P4 代码与自动化;P5 外部条件待签署) | **RecoveryPlan → Attempt → Job → Worker/RPA → 幂等回调 → AutoProgress → Projection** 已收口;20 Gate 均有运行时实施状态,跨阶段恢复、精确失效、多源库存准备、组合指纹、未知上传状态和前端 `recovery_targets` 已覆盖。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md);最终报告:[process-gate-recovery-final-compliance.md](features/shipping-notice/process-gate-recovery-final-compliance.md)。生产双 Worker、真实 RPA、Dify 手工核对、视觉/E2E 与人工签署仍为发布前条件;不引入 Temporal/Celery。 | -| **错误可解释性(阶段 0–4)** | 完全达标 | 分层原因码冻结且主路径全量 EMITTED(仅预留 `inventory_uom_conversion_failed`);`AUDIT_COVERAGE_MATRIX` 统一覆盖率 100%;审计中心业务/技术分层且无强制横滚;库存源复核始终展示 `source_code`;四语言对齐。权威契约:[error-explainability-contract.md](features/shipping-notice/error-explainability-contract.md)。 | -| **订单项次派生与血缘审计** | 已实现(Phase 0–4 + 评审纠偏) | 统一 `customer_po_line_no` / `line_no` / `export_sequence`;Schema 派生模拟支持历史 Extraction 样本;运行时派生含 `evidence_refs`;复核覆盖/恢复(`LINE_NO_OVERRIDDEN`/`LINE_NO_RESTORED`);货代统一审计新写入永久保留(`6a9c3e5f7b2d`) | -| 模板发布与自动冻结资格分离(阶段 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` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | -| 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 | -| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | -| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | -| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | -| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | -| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | -| 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 | -| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | -| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | -| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` | -| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | -| 库存源至外部系统仓库映射 | 已实现 | 维护精确与 Source 默认映射;当前仅后台维护和后端内部 Service,不开发 Tool API 或调拨逻辑 | -| 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | -| 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` | -| 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 | -| 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 | -| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;Schema 普通升级造成字段 UUID 变化时,按冻结语义安全映射新版 Header 字段;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 | -| 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 | -| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 | -| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 | -| 字段资产治理与 Schema 契约解耦(阶段 0–5) | 已实现 | 全局标准**58** + 扩展资产库(Header/Line 可共享 `reservation_id`);**唯一**发货订单 Schema(`STANDARD_SHIPPING_NOTICE`)多版本采用/发布门禁;**自动建单总开关随 Schema 版本 definition 冻结**(草稿保存 + 发布生效,含审计);管理端双入口(字段资产库 / 订单 Schema);Run 冻结含 schema_code;表结构保留 `schema_code` 但不开放多族治理。见 [field-governance-plan.md](features/shipping-notice/field-governance-plan.md)。生产切换须停写→迁移→手动勾选建议项发布 V1。 | -| 履约治理 UI 重构 | 待续 | 本轮从 Schema 页移出策略卡;库存/Excel/RPA/策略工作台另案 | -| 客户识别证据源与订单字段彻底分域(G2/G3) | 待续 | 本轮仅 G1 边界:禁止 mail context 进入订单字段资产;身份 UI 不重做 | -| 滚动履约领域契约(阶段 0) | 实施中 | 冻结 `SHIP_AVAILABLE_ROLLING`、预置核心字段与可配置扩展字段、Snapshot 正式真相、预约单全局注册、Artifact/Attempt 拆分、LLM 人工复核门禁;扩展字段是否进入库存/Excel/RPA 由已发布业务配置决定;Excel 命名由已发布模板规则优先、环境变量受控回退,最终规则在 Artifact 审计冻结。 | -| 订单冻结就绪门禁(阶段 6) | 已完成 | 冻结前聚合校验已接受抽取、客户确认、字段冲突、最小履约字段、正数数量和版本;Task 行锁与 Snapshot 的 `task_id` 唯一约束保证重复确认只返回同一快照;来源清单冻结字段裁决、文档 hash、证据定位和人工复核历史。 | -| 重发版本替代与货代撤销(阶段 7) | 已完成 | 身份固定为客户+PO、内容变化单独版本化;未上传旧版立即作废,已上传旧版必须登记撤销回执后才能解除新版本履约阻断;新旧任务关系和撤销审计永久保留。 | -| 库存、Excel 与上传入口门禁(阶段 8) | 已完成 | 履约入口及其底层服务均要求活动的冻结订单,替代/作废/撤销待处理版本无法匹配或导出;人工上传强制货代回执号、私有回执文件和服务端当前用户。 | -| 安全 Chatflow(阶段 9) | 已完成 | 仅允许一个启用货代 Chatflow;Dify OpenAPI 只保留短效能力令牌保护的任务/批次状态查询,所有写操作改由 HXOPS 确认卡与服务端状态机执行。 | -| 产品原型 | 已文档化 | 见[docs/features/shipping-notice/shipping_notice_agent_prototype.md](features/shipping-notice/shipping_notice_agent_prototype.md) | +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 | +| 订单生命周期工作台状态展示统一(v2) | 已实现 | 五阶段下方横幅移除;右栏「当前任务」卡为唯一状态宿主:状态行=user_status 短标签(Run 级 lifecycle_status 受控兑底映射)+ 状态块内嵌动态说明(`RUN_STATUS_FALLBACK_MAP`/`REDUNDANT_DETAIL_REASON_CODES` 双常量裁决,诊断信息不隐藏);无 Case 瞬态保留单行白名单轻提示;聊天页/任务中心同源接入零视觉变化。设计:[2026-08-31 状态展示统一设计](superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md) | +| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | +| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | +| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | +| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 | +| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake 快览:只解析邮件正文、白名单 HTML 表格快照和附件目录;上传阶段不抽取附件全文、不创建附件 FileAsset/Document、不生成 Candidate、不判订单重复;解析失败、超时、取消保持幂等 | +| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 | +| 版面解析并发与耗时诊断 | 已实现 | 独立 `hxops-shipping-worker` 默认双进程并行领取同批版面 Job;PDFium 先轻量预读字符但不裁决表格,MinerU 始终作为 PDF 表格结构首选 Provider;仅 MinerU 空表/失败时允许严格 PDFium 回退。Job `result` 平级保存脱敏 `timings`+`counts`(含 OCR/OpenCV/对齐细分与 `ocr_engine_warm`),worker 日志同步输出;诊断字段不进 layout snapshot,不记录原文/HTML/OCR 原始响应(PR-0)。PR-1:`SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED` 控制同 Job 整页 OCR 复用;PR-2:`SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED` 字符预读复用+按需补图,OpenCV geometry Job 内缓存;PR-3:`SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED` 表格裁剪 OCR(prod 默认关) | +| 对话输入框多附件统一提交 | 已实现 | 用户可分多次选择 EML/PDF;当前输入框内全部已就绪 Intake 在一次发送中冻结为同一个订单抽取 Run。`uploadBatchId` 仅用于单次上传幂等与状态关联,不再截断发送范围 | +| 批次进度中心混合状态 EML 展示 | 已实现 | 状态以 PDF Unit 为准,聊天摘要与批次进度中心均按“状态 → EML → PDF”展示;同一 EML 可在多个状态区出现,但每张卡仅显示本区 PDF,并标注本组/总附件数;所有状态分组标题统一显示本组文件数;未物化附件以工作项标识去重,Excel 诊断附件进入只读“已忽略”分区,不混入处理中或已完成;聊天摘要与批次进度中心均默认折叠已忽略分区,展开后保留 Excel 明细;批次中心顶栏单列已忽略数,与提交文件总数对账,完成率和“已处理 N/M”仅按订单文件计算;其余订单 PDF 全部完成时,对话摘要显示完成且不再展示阶段 | +| 无框订单明细表原生 PDF 回退 | 已实现 | 仅当 MinerU 未输出表格、PDF 原生文字坐标完整且同页命中多个通用明细表头时,从表头到合计行生成待配置候选表;正常 MinerU 表格路径不变,解析器修订 `v4` 防止复用旧零表格缓存 | +| 点击发送完整订单抽取 | 已实现(终态分阶段) | Run 冻结文档、Schema、模板 Profile、路由/评分/门禁与解析器版本;Worker 执行异型模板或通用确定性解析;完整性门禁与紧急停止控制自动冻结;Dify 仅提供复核最小证据建议且不得自动冻结;上线清单见 order-extraction-go-live-checklist.md | +| 相同附件跨批次 Workflow 复用 | 已实现 | 同会话完整附件 `content_hash` 集合与 Schema 版本相同时,复用活跃或未关闭 Run/Workflow Item;新上传批次、Intake/Document ID 或文件名不再导致重复 Workflow | +| 订单识别生命周期反馈 | 已实现(2026-08-23) | Run 状态卡与复核工作台复用 Run/Unit/ProgressEvent 的轻量 `lifecycle_progress`:解析/重解析/门禁通过后的自动推进期间,五阶段常驻可见,并显示当前阶段内步骤、已完成步骤及稳定失败/排队/卡住原因;无 Case 时不再只剩黄色横幅。已有正式任务仍以 Process Gate 投影为准;同步人工客户选择不伪造自动处理中;不新增 SSE、进度表或第二状态机。 | +| 处理进度细化与全链路审计 | 已实现 | 阶段 0–5 + 正式评审整改:排队/处理中分列、文档级健康提醒与最后活动、管理员取消任意 Run(代取消必填原因)、审计完整筛选(含 conversation/session_item/review_case/owner)、敏感访问审计、取消 operation_id 串联、进度事件真实状态、库存/RPA/导出双写统一审计。Run 级 `handling_items`/`primary_notice` 拆分待补信息/冲突/自动冻结受阻/PDF 复核/技术失败/预算停扩,聊天卡与右侧「本次处理」按原因展示并跳转。灰度开关 `PROGRESS_UI_V3`/`ORDER_EXTRACTION_CANCEL`/`AUDIT_EXPORT`;审计保留 `SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095`。Dify 无需改画布 | +| 会话 PDF 工作项(阶段 0–4) | 已退役 | 已由 Workflow 台账替换;旧验收文档已删除 | +| Workflow 阶段 0–2 底座与投影 | 已实现 | 删除 session work items;Workflow/Item/Version/Event;进度投影与会话轮询;见 `workflow-stage0-acceptance.md` 与 technical.md | +| Workflow 阶段 3 确认后自动进度 | 已实现 | 五门禁(批准模板/字段完整/证据/冲突重复/质量)失败仅 Review Case;确认返回 `shipping_notice_no`/`order_task_no` 并推进履约;复核页 `ReviewWorkflowProgressPanel` 读统一 OT 投影;建单后取消 Task `pending_void`+Excel 只读;移除工作台 upload-inventory/mark-manual-uploaded/retry-upload 写入口 | +| Workflow 阶段 4 任务中心与审计闭环 | 已实现 | 任务中心进行中 2s/8s 自动刷新;时间线合并 Workflow Event;审计关联链/敏感读权限/哈希日检;删除复核监管台 | +| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 | +| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | +| 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序;标注 Reservation ID 专区的模板跨页以 `Vendor Comments` 至首次 `Terms and Condition(s)` 作为语义边界读取预约单号,未标注模板保持原解析路径 | +| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) | +| **XFA 数据路径 Profile(统一回退)** | 代码收口(2026-08-18) | datasets + 拆分规则为首选;失败进入普通 PDF 共用 PDFium/Widget/OCR 证据链,保留 `fallback_from`、原因码与 `value_source`,回退候选固定 Review、禁止 STP;Dify 主链:**NONE**。 | +| **XFA 统一视觉标注 + 字段拆分** | 统一入口已收口 | 普通 PDF/XFA 共用 Editor、`/pdf-automark` Job、保存、验证和发布 DTO;`value_binding` + `visual_binding`、RE2、统一 CQ/STP;XFA 仅在首选 datasets 取值与拆分规则上保留适配器差异。 | +| **XFA 可见值回读补偿** | 已实现(2026-08-25) | 编辑器在原生坐标、服务端 OCR 与唯一 Widget 无值后,OCR 同一 PDF.js XFA 画布的受控裁剪图(`xfa_rendered_ocr`);仍无值保留值框并提示诊断,可继续绑定 datasets。裁剪图不持久化,datasets 仍为唯一正式值源。 | +| **PDF 订单解析证据链与冻结 Parse Plan** | 已验收(2026-08-23) | 原 PDF 为不可变事实,`matching_features.v1` 仅用于稳定版式匹配;坐标统一经按需恢复入口取得。普通 PDF 以页级 PDFium glyph 为取值事实,MinerU 仅作结构候选;无起行锚点、坐标缺失、漂移、歧义、引擎冲突和 XFA fallback 均 fail-closed 至 Review,禁止把表头伪装成明细。无真实标签的固定订单字段仅在唯一匹配模板的正式运行或盲测回放中,以原生 PDF 坐标确认;其余场景仍进入 Review。Schema 是唯一业务契约;Dify 主链 NONE。见 `technical.md`。 | +| **旧 XFA 合成预览/OCR 专用入口** | 已废弃 | 浏览器不得调用 `/xfa/automark`;内部 XFA 多源执行器由统一 `/pdf-automark` 调用,原生 PDF 页是统一画布。 | +| **XFA 字段拆分映射(历史)** | 已被统一方案接管 | 早期 `stages[]` 流水线与独立映射页能力将在统一方案阶段 1/4 对齐并收口;对照文档:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。 | +| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。自动标注另经统一 Draft 样本就绪门禁:当前 ready Layout、唯一视觉主表、内容/hash/checksum/parser 身份均可验证时才幂等冻结样本证据并入队;保存、轮询、入队和 Worker 复验使用同一契约,失败展示可操作原因且不影响其他 Profile。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 | +| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 | +| **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF **默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 | +| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(正式 OT 后分层已落地) | Case 切换请求代次 + 瞬态清理;正式 OT 后右侧主卡切自动处理、订单检查折叠、系统等待不冒充人工待办;`profile_match` 四态 + `field_completeness`;`completed_checks` 后端投影;`automation.phase` 区分建单前/后文案。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 | +| **OT 后行级自动履约(明细合并 + 匹配事实)** | 已实现 | 明细只读库存源;库存浮层仅 preparation/matching;短缺单条放行后异步创建独立 Notice 并生成其唯一 Excel;多条开放明细仍必须人工勾选后合并创建,暂不支持批次放行。冻结:[post-ot-line-auto-fulfillment-freeze.md](features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md)。 | +| **双工作台架构 + Candidate Qualification(阶段 0–6)** | 阶段 0–6 达标(评审整改后) | **已完成**:双工作台边界;Candidate Qualification(追加式快照 + 审计);模板审批不再硬阻断自动建单;对话「本次处理中」轻量侧栏;复核返回对话;货代上传 RPA 可按 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 接入自动链;Process Gate 对话内恢复;审计事件字典含 chat_* / qualification / upload_rpa。权威:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 | +| **对话侧 Task 进度与「本次处理中」** | 阶段 2–5 已实现 | 侧栏以用户可见任务(OT)分组为主路径;`ShippingConversationProcessingCard` + processing API;`WF-...` 下沉;发送走统一提交无确认框。 | +| **会话多任务聚合与统一提交(阶段 0–5)** | 整改中 | 契约冻结(§1.6.1);统一提交 + 独立 submission 幂等;同 PDF 指纹继承 OT(跨 Schema);投影按「当前有效最新 Run」;未查看 completed 仍可见;任务级取消/重试均走 Run API;状态四语言 + 更新时间。权威:technical.md §1.6.1。 | +| **多 EML / 直接 PDF / PDF 优先全链路重构(阶段 0–7)** | 蓝图 §六 表层基本对齐;workflow/batches DROP 推迟 | `co4`–`co7`:接入层、Notice/履约、`order_tasks`/evidences/notice_lines/document_versions、`processing_runs/units/plans/route_decisions`。待:DROP batches/workflows、FE 去旧 Workflow。 | +| **Candidate 统一自动建单资格** | 阶段 1 已实现 | 新增 `candidate_qualification_contract/service`、表 `shipping_order_candidate_qualifications`;三种解析来源统一门禁;模板批准仅 parser_trace;移除 LLM 天然阻断;STP 自动建单前持久化资格快照。 | +| **邮件补充冲突可解释性与历史重评估** | 已实现(2026-08-21) | 新 Finding 展示 PDF/邮件双方原值、规范化值与证据;金额语义比较、精确 `PO + MPN` 行关联;管理员可按 Candidate/Run 或受确认的全量操作重评估历史旧冲突,证据不足显示重新识别 PDF 恢复动作并保留阻断/审计。 | +| **复核保存校验自动入队反馈** | 已实现(2026-08-21) | Draft validate 保留后端 `resume_outcome`;`auto_create_enqueued`、已排队或运行中统一显示已入队,实际后续节点仅消费后端处理投影。 | +| **后台顺序自动推进 + Process Gate 对话恢复** | 已实现 | 自动链:库存准备→匹配→库存 RPA→Excel;货代上传 RPA 须 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 显式 true 且通过就绪校验。RPA 中投影 `upload_rpa_pending` / `is_waiting_manual_upload=false`。对话侧 ProcessGateRecoveryCard;技术重试上限 3。 | +| **建单前统一恢复协调器(Gate/资格/auto_gate)** | 进行中(P0 缺陷已修,待正式验收) | `order_review_resume_service` + 行级履约 fail-closed(库存重校验、task 行不可 reopen、审计 before/after);复核侧栏置顶业务阻断,履约表格在库存模式;业务审计含白名单快照。权威:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md)。 | +| **双工作台审计闭环** | 已实现(阶段 6) | 事件字典冻结 chat_* / review_* / process_gate_* / qualification / workflow_node;对话恢复写 `chat_process_gate_*`;审计中心分组与 Candidate/Gate 筛选;普通账本脱敏 + 敏感快照独立鉴权;覆盖率举证见 AUDIT_COVERAGE_MATRIX。 | +| **复核字段精确高亮(阶段 0–5)** | 已完成(盲测样本集另立) | 冻结 `shipping-field-highlight-v1`;原生唯一 glyph / OCR candidate / Cell 来源分级;证据 API 全量 `highlight_quality`;工作台 verified 实线 / candidate 虚线;坐标诊断与 list/focus/restore/version 审计齐全;`review_coordinate_corrected` 事件已冻结(人工改框写路径待模板标注扩展)。权威契约:[field-highlight-contract.md](features/shipping-notice/field-highlight-contract.md)。 | +| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 OT 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。阶段 0–5 已落地:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Notice/NoticeLine→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。订单项次由各单据写路径按顺序生成且不可编辑;库存准备失败停留在通知准备阶段。| +| **全门禁级中断恢复(契约冻结)** | 已实现(P0–P4 代码与自动化;P5 外部条件待签署) | **RecoveryPlan → Attempt → Job → Worker/RPA → 幂等回调 → AutoProgress → Projection** 已收口;20 Gate 均有运行时实施状态,跨阶段恢复、精确失效、多源库存准备、组合指纹、未知上传状态和前端 `recovery_targets` 已覆盖。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md);最终报告:[process-gate-recovery-final-compliance.md](features/shipping-notice/process-gate-recovery-final-compliance.md)。生产双 Worker、真实 RPA、Dify 手工核对、视觉/E2E 与人工签署仍为发布前条件;不引入 Temporal/Celery。 | +| **错误可解释性(阶段 0–4)** | 完全达标 | 分层原因码冻结且主路径全量 EMITTED(仅预留 `inventory_uom_conversion_failed`);`AUDIT_COVERAGE_MATRIX` 统一覆盖率 100%;审计中心业务/技术分层且无强制横滚;库存源复核始终展示 `source_code`;四语言对齐。权威契约:[error-explainability-contract.md](features/shipping-notice/error-explainability-contract.md)。 | +| **订单项次与字段血缘审计** | 已实现(硬切换) | `customer_po_line_no` 作为原始客户事实保留;订单解析行、冻结档行、发货通知行各自在所属单据内从 1 编号;不提供 Schema 派生、项次覆盖或恢复。| +| 模板发布与自动冻结资格分离(阶段 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` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | +| 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 | +| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | +| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | +| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | +| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | +| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | +| 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 | +| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | +| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | +| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready`;回调以 `ShippingOrderTask` 为唯一任务模型,收件与业务处理分离,事务失败必须收口为失败;库存等待使用单一 Gate Attempt 与 30→60→120→240→300 秒退避 Job,不为每次轮询新增 Attempt。 | +| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | +| 库存源至外部系统仓库映射 | 已实现 | 维护精确与 Source 默认映射;当前仅后台维护和后端内部 Service,不开发 Tool API 或调拨逻辑 | +| 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | +| 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` | +| 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 | +| 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 | +| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;Schema 普通升级造成字段 UUID 变化时,按冻结语义安全映射新版 Header 字段;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 | +| 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 | +| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 | +| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 | +| 字段资产治理与 Schema 契约解耦(阶段 0–5) | 已实现 | 全局标准 **58** + 扩展资产库(Header/Line 可共享 `reservation_id`);**唯一**发货订单 Schema(`STANDARD_SHIPPING_NOTICE`)多版本采用/发布门禁;**自动建单总开关随 Schema 版本 definition 冻结**(草稿保存 + 发布生效,含审计);管理端双入口(字段资产库 / 订单 Schema);Run 冻结含 schema_code;表结构保留 `schema_code` 但不开放多族治理。见 [field-governance-plan.md](features/shipping-notice/field-governance-plan.md)。生产切换须停写→迁移→手动勾选建议项发布 V1。 | +| 履约治理 UI 重构 | 待续 | 本轮从 Schema 页移出策略卡;库存/Excel/RPA/策略工作台另案 | +| 客户识别证据源与订单字段彻底分域(G2/G3) | 待续 | 本轮仅 G1 边界:禁止 mail context 进入订单字段资产;身份 UI 不重做 | +| 滚动履约领域契约(阶段 0) | 实施中 | 冻结 `SHIP_AVAILABLE_ROLLING`、预置核心字段与可配置扩展字段、Snapshot 正式真相、预约单全局注册、独立 Shipment 通知号、Artifact/Attempt 拆分、LLM 人工复核门禁;全项满足自动生成一张通知,部分满足停人工多选,Excel 编号与通知号一致;扩展字段是否进入库存/Excel/RPA 由已发布业务配置决定。 | +| 订单冻结就绪门禁(阶段 6) | 已完成 | 冻结前聚合校验已接受抽取、客户确认、字段冲突、最小履约字段、正数数量和版本;Task 行锁与 Snapshot 的 `task_id` 唯一约束保证重复确认只返回同一快照;来源清单冻结字段裁决、文档 hash、证据定位和人工复核历史。 | +| 重发版本替代与货代撤销(阶段 7) | 已完成 | 身份固定为客户+PO、内容变化单独版本化;未上传旧版立即作废,已上传旧版须由受权人员登记外部撤销已确认后才能解除新版本履约阻断;新旧任务关系和撤销审计永久保留。 | +| 库存、Excel 与上传入口门禁(阶段 8) | 已完成 | 履约入口及其底层服务均要求活动的冻结订单,替代/作废/撤销待处理版本无法匹配或导出;人工上传仅按业务单号确认,服务端从当前用户会话取得操作人并创建 Attempt 审计。 | +| 安全 Chatflow(阶段 9) | 已完成 | 仅允许一个启用货代 Chatflow;Dify OpenAPI 只保留短效能力令牌保护的任务/批次状态查询,所有写操作改由 HXOPS 确认卡与服务端状态机执行。 | +| 产品原型 | 已文档化 | 见 [docs/features/shipping-notice/shipping_notice_agent_prototype.md](features/shipping-notice/shipping_notice_agent_prototype.md) | +| **多候选库存源自动批次探测(一期)** | 已实现 | `ensure_inventory` STP 多候选分支:缺文件不再隐式阻断为 `needs_human`,改为自动单批次 RPA 探测(仅缺失源,已有 ready 快照复用)并返回 `running`;逐源 Attempt/超时/重试保留。设计:[2026-08-29-shipping-inventory-source-selection-design.md](superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md) §2。 | +| **库存匹配数据自证 + 行级歧义兜底(一期)** | 已实现 | 全部候选源快照按行打 `__source_code` 标签匹配,按行反写源/可用量/缺口;同一行命中多源 → 行 `multi_file_conflict` 阻断 + `candidate_hit_source_codes`(禁止静默选源)。设计 §2.3。 | +| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 | +| **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 | +| **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 | +| **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 | +| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | +| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | ### 排程平台任务契约中心(schedule) @@ -199,22 +213,13 @@ ### 立账凭证检核(accounting-voucher-check) -| 功能项 | 状态 | 说明 | -| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| | | | -| 需求、规格与技术设计 | 需求更新中 | [需求说明](features/accounting-voucher-check/demand.md) · [技术设计](features/accounting-voucher-check/technical-design.md);销售一期每周增量检核上月,按 Profile 从 ERP、OA、目录等来源获取并归档资料,采购二期待配置 | -| 共享盘文件存在性检核 | 已实现 | platform Job `accounting-voucher-check`;默认 `vouche/{YYYY}/{MM}/{invoice_no}/`;暂定必检「核价单.pdf」「采购单.pdf」;不读内容、不用 LLM | -| 增量批次与异常告警 | 已实现 | 齐全且目录元数据指纹未变更可跳过;共享盘不可用整批失败并告警;缺资料企微 textcard(同票同日节流) | -| 日批排程 | 已实现 | 预置 `SCH-ACCOUNTING-VOUCHER-CHECK`,Cron `0 6 * * *`(Asia/Shanghai) | -| Tool / 工作台查询 | 已实现 | 启动复用 `/api/file-check/tools/tasks/run` + `run_options`;查询 `/api/accounting-voucher-check/tools/*`;工作台 `/workspace/accounting-voucher-check` 仅管理员可见和访问 | -| Dify Chatflow 编排 | 待完成 | Tool API 已就绪,Chatflow 意图映射与部署手册另开 | - -| 销售一期需求、规格与技术设计 | 已文档化 | [销售一期需求](features/accounting-voucher-check/demand.md) · [技术规格](features/accounting-voucher-check/technical.md) · [技术设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个自然月 | -| 通用 Profile + Adapter 架构 | 待实施 | `document_check` 通用引擎加载销售、采购及后续业务方 Profile;文件规则决定来源、命名、路径和归档,Adapter 封装 ERP、OA、固定目录等差异 | -| 单一共享盘旧检核 | 已实现,待迁移 | platform Job `accounting-voucher-check`;当前月 `vouche/{YYYY}/{MM}/{invoice_no}/` 和固定必检文件的旧模型,仅作为销售 Profile 迁移参考 | -| 增量、归档与缺件通知 | 待重构 | 单文件级指纹和状态支持每周增量;同 invoice 集中归档;缺失必检文件发送企业微信,接收人待确认 | -| Tool / 工作台查询 | 已实现,待兼容迁移 | 现有 `/api/accounting-voucher-check/tools/*` 和工作台保留兼容;新通用 API 按 `profile_code` 提供批次和明细查询 | -| Dify Chatflow 编排 | 待完成 | 迁移后按 `profile_code` 发起和查询;旧 Tool 映射在销售迁移期保留 | +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月,按 Profile 从 ERP、OA、目录获取并归档 | +| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;ERP PO / OA 销货放行单打印仅占位 | +| 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` | +| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 | +| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;「强制重检上月」;`/runs`、`/notifications` 只读引擎表 | ### 采购合同审查 @@ -733,3 +738,33 @@ 详细目标架构、接口契约、测试矩阵与验收标准见 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md)。 --- + +## 在途仓自动调拨 Agent + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | ackend/app/models/in_transit_transfer.py(Run/SourceJob/Precheck/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e;13 状态服务端门禁(services/in_transit_transfer/status.py) | +| 收料文件准备与只读预检 | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/预检快照 Hash/进度恢复 | +| 确认与 ERP 原子调拨 | 后端已实现 | 直接生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) | +| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | +| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | +| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/预检/结果/待处理)与 admin 模块按计划实施 | + +--- + +## 外部系统连接器框架(Integration Connector) + +> 平台级外部系统集成抽象(连接器/能力契约/绑定/AI 工具暴露)。首个消费者为在途仓自动调拨的 `query_inventory`。设计文档 [docs/platform/integration-connector-framework-design.md](platform/integration-connector-framework-design.md);完整愿景见 [enterprise-integration-center-prototype.md](platform/enterprise-integration-center-prototype.md)。 + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 配置实体 + 迁移 | 后端已实现 | `models/integration_connector.py`(CredentialReference/ClientInstance/InterfaceDefinition/Binding/Call)+ 迁移 ic1a2b3c4d5f | +| Capability 强类型契约 | 后端已实现 | 代码注册(输入/输出 Schema/幂等语义/是否写);在途调拨 3 能力 query_inventory/create_transfer/verify_duplicate | +| REST/SOAP 传输 | 后端已实现 | `transports/`(fail-closed:缺 endpoint/wsdl 抛 INTEGRATION.TRANSPORT_NOT_FROZEN) | +| 声明式映射引擎 | 后端已实现 | 点路径/数组下标 + 白名单转换函数 + 最小 Schema 校验(禁任意 Python/JS/SQL) | +| 凭据引用 + 脱敏 | 后端已实现 | 只存 secret_ref 引用;sanitize 脱敏;credential_summary 不回显明文 | +| Binding 版本化解析 | 后端已实现 | (capability, context, environment) → 客户端+接口+映射版本;默认+来源覆盖+优先级+生效区间;冻结快照 | +| CapabilityGateway 引擎 | 后端已实现 | resolve→validate→build→call→map→classify→落 IntegrationCall;result_unknown 不自动重试 | +| Admin API | 后端已实现 | `/api/integration-connector/*`(配置 CRUD + 能力清单/调用 + 连接测试;拒绝 interface_id;require_admin) | +| 调拨 query_inventory 接线 | 后端已实现 | `services/in_transit_transfer/gateway_adapter.py` 把 ERP 访问收敛到 gateway(P1 用默认绑定,来源专属绑定待 P2/P3) | +| 配置作业 UI / MCP / Dify 暴露 / RPA/SQL 传输 | 待实施 | 属 P2/P3(AI 只暴露 Capability;RPA 为独立异步 Transport) | diff --git a/docs/openapi/accounting_voucher_check_tools_openapi.json b/docs/openapi/accounting_voucher_check_tools_openapi.json deleted file mode 100644 index 67a7eea2..00000000 --- a/docs/openapi/accounting_voucher_check_tools_openapi.json +++ /dev/null @@ -1,518 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "HXOPS Accounting Voucher Check Tool API", - "description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://127.0.0.1:5052", - "description": "HXOPS_TOOLS_API_BASE" - } - ], - "security": [ - { - "BearerAuth": [] - }, - { - "IntegrationKey": [] - } - ], - "paths": { - "/api/accounting-voucher-check/tools/tasks/{task_id}/missing": { - "get": { - "operationId": "list_voucher_missing", - "summary": "查询缺资料发票(最新状态)", - "description": "按账套与月份查询 status=missing 的发票;默认当前自然月。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "task_id", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "example": 12 - }, - "description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { - "type": "string", - "example": "2026-08" - }, - "description": "检核月份 YYYY-MM;缺省为当前自然月" - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { - "type": "string", - "default": "HXJM", - "example": "HXJM" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 200, - "minimum": 1, - "maximum": 1000 - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MissingListResponse" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - }, - "/api/accounting-voucher-check/tools/runs/{run_id}/items": { - "get": { - "operationId": "list_voucher_run_items", - "summary": "查询批次发票明细", - "description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "run_id", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "example": 1001 - } - }, - { - "name": "result", - "in": "query", - "required": false, - "schema": { - "type": "string", - "enum": [ - "complete", - "missing", - "skipped", - "technical_error" - ], - "example": "missing" - } - }, - { - "name": "page", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 1, - "minimum": 1 - } - }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 50, - "minimum": 1, - "maximum": 200 - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RunItemsResponse" - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - }, - "/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": { - "get": { - "operationId": "get_voucher_invoice_latest", - "summary": "查询指定发票最新检核状态", - "description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "invoice_no", - "in": "path", - "required": true, - "schema": { - "type": "string", - "example": "INV-20260803001" - }, - "description": "发票号(apa08 原值)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { - "type": "string", - "example": "2026-08" - } - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { - "type": "string", - "default": "HXJM" - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InvoiceLatestResponse" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - } - }, - "components": { - "securitySchemes": { - "BearerAuth": { - "type": "http", - "scheme": "bearer", - "description": "Authorization: Bearer " - }, - "IntegrationKey": { - "type": "apiKey", - "in": "header", - "name": "X-Integration-Key", - "description": "与 Bearer 二选一" - } - }, - "schemas": { - "MissingMaterial": { - "type": "object", - "properties": { - "code": { - "type": "string", - "example": "price_check_sheet" - }, - "name": { - "type": "string", - "example": "核价单" - } - } - }, - "InvoiceState": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "scope_code": { - "type": "string" - }, - "period_month": { - "type": "string", - "nullable": true - }, - "invoice_no": { - "type": "string" - }, - "invoice_date": { - "type": "string", - "nullable": true - }, - "status": { - "type": "string", - "enum": [ - "complete", - "missing" - ] - }, - "folder_path": { - "type": "string", - "nullable": true - }, - "folder_exists": { - "type": "boolean" - }, - "matched_files": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "missing_materials": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MissingMaterial" - } - }, - "last_checked_at": { - "type": "string", - "nullable": true - } - } - }, - "MissingListResponse": { - "type": "object", - "required": [ - "ok", - "items", - "count" - ], - "properties": { - "ok": { - "type": "boolean", - "example": true - }, - "task_id": { - "type": "integer", - "nullable": true - }, - "scope_code": { - "type": "string" - }, - "period": { - "type": "string", - "example": "2026-08" - }, - "count": { - "type": "integer" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/InvoiceState" - } - } - } - }, - "RunItem": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "schedule_run_id": { - "type": "integer" - }, - "invoice_no": { - "type": "string" - }, - "result": { - "type": "string", - "enum": [ - "complete", - "missing", - "skipped", - "technical_error" - ] - }, - "folder_path": { - "type": "string", - "nullable": true - }, - "matched_files": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "missing_materials": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MissingMaterial" - } - }, - "error_code": { - "type": "string", - "nullable": true - }, - "error_message": { - "type": "string", - "nullable": true - } - } - }, - "RunItemsResponse": { - "type": "object", - "required": [ - "ok", - "items", - "total" - ], - "properties": { - "ok": { - "type": "boolean" - }, - "run_id": { - "type": "integer" - }, - "run_no": { - "type": "string" - }, - "page": { - "type": "integer" - }, - "page_size": { - "type": "integer" - }, - "total": { - "type": "integer" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RunItem" - } - } - } - }, - "InvoiceLatestResponse": { - "type": "object", - "required": [ - "ok", - "state" - ], - "properties": { - "ok": { - "type": "boolean" - }, - "state": { - "$ref": "#/components/schemas/InvoiceState" - }, - "recent_run_items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RunItem" - } - } - } - }, - "ToolError": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "example": false - }, - "error_code": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": { - "type": "object" - } - } - } - }, - "responses": { - "BadRequest": { - "description": "参数错误", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "Unauthorized": { - "description": "鉴权失败", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "NotFound": { - "description": "资源不存在", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "MissingAuth": { - "description": "服务端未配置 Tool API Key", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - } - } - } -} diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index 7e74bc62..7f6c036e 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -14,8 +14,8 @@ "/tools/get_task_status": { "post": { "operationId": "get_task_status", - "summary": "查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构", - "description": "返回 inventory_source_code、inventory_connector_type、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。", + "summary": "查询任务当前状态与 human_options;响应含库存源状态与候选结构", + "description": "返回 inventory_source_code、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint,以及 step_payload.inventory_source_resolution.candidates。", "parameters": [], "requestBody": { "required": true, diff --git a/docs/platform/README.md b/docs/platform/README.md index 7f633316..cf45214b 100644 --- a/docs/platform/README.md +++ b/docs/platform/README.md @@ -10,3 +10,5 @@ | [agent_progress_prototype.md](agent_progress_prototype.md) | Agent 进度管理通用底座(`async_batch` 等) | | [agent_runtime_context_prototype.md](agent_runtime_context_prototype.md) | Runtime Context 协议原型 | | [progress_contract_platform_prototype.html](progress_contract_platform_prototype.html) | 进度契约平台 HTML 原型 | +| [enterprise-integration-center-prototype.md](enterprise-integration-center-prototype.md) | 企业集成中心蓝图(完整愿景,含 HTML 原型) | +| [integration-connector-framework-design.md](integration-connector-framework-design.md) | Integration Connector Framework 设计(首期最小可行收敛版) | diff --git a/docs/platform/integration-connector-framework-design.md b/docs/platform/integration-connector-framework-design.md new file mode 100644 index 00000000..f8c73153 --- /dev/null +++ b/docs/platform/integration-connector-framework-design.md @@ -0,0 +1,502 @@ +# Integration Connector Framework:连接器、能力契约、绑定与 AI 工具暴露设计 + +| 项目 | 说明 | +| --- | --- | +| 文档版本 | v1.0(首期最小可行设计) | +| 日期 | 2026-08-27 | +| 状态 | 设计评审中(未实现) | +| 读者 | 平台研发、后端、前端、Agent/集成负责人、ERP/RPA 管理员 | +| 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) | +| 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) | + +> 本文是既有《HXOPS 企业集成中心与在途仓自动调拨原型设计》(`enterprise-integration-center-prototype.md`)的可落地设计。目标是直接建设通用连接器配置能力,同时控制边界:不引入低代码流程编排、任意脚本执行等与当前业务无关的 iPaaS 能力。蓝图中的高级能力(Saga 补偿、Schema Registry、灾备等)保留为后续演进项。 + +--- + +## 0. 三条设计原则 + +1. **配置替换外部系统,不替代领域业务规则。** 连接器/接口/字段映射可配置;但"数量必须相等""当天收料不调拨""`result_unknown` 不得重试"等规则永远属于领域层,不允许管理员通过配置改变。 +2. **AI 调用业务能力,不调用原始接口。** 对 AI Agent 与外部应用只暴露治理过的 Capability(如 `query_inventory`),不暴露 ERP 地址、SOAP Action、凭据、请求模板或接口编号。 +3. **所有配置与调用均版本化、可测试、可审计、fail-closed。** 配置缺项即拒绝,不猜测;一次 Run 冻结全部相关版本;每次调用留痕。 + +--- + +## 1. 背景与问题 + +### 1.1 现状 + +在途仓自动调拨当前把 ERP 访问**写死**在代码里: + +- `app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层,`query_inventory` / `create_transfer` / `verify_duplicate` 三个操作硬编码; +- `app/services/in_transit_transfer/deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键并固定构造 SOAP 传输; +- 没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。 + +### 1.2 目标 + +建设一个**系统无关**的连接器框架:同一业务能力(如"查库存")在不同外部系统(ERP / WMS / OA / PLM / HR / RPA 等)上,只通过配置切换客户端实例、接口定义与字段映射,业务代码零改动。同时把治理过的能力暴露给 AI Agent 与其他应用调用。 + +> 命名约定:框架不使用 `ErpAdapter` 之类 ERP 专属命名。ERP 只是框架接入的**一个外部系统示例**。通用抽象统一称为 **Connector / Transport / Capability / InterfaceDefinition / Binding**。 + +### 1.3 "零改代码"的边界 + +- **已注册的业务能力**更换外部系统、接口或字段映射时,业务代码零改动; +- **新增全新业务能力**仍需注册能力契约(输入/输出 Schema、幂等语义、是否写)并实现领域处理逻辑。 + +配置不能替代领域业务规则(见原则 1)。 + +--- + +## 2. 三层最小架构 + +```text +┌─────────────────────────────────────────────────────────┐ +│ 领域层(Domain) │ +│ 业务规则、状态机、幂等、写前复查、来源隔离、审计 │ +│ 只调用标准 Capability,不感知协议/地址/凭据/字段路径 │ +└────────────────────────┬────────────────────────────────┘ + │ CapabilityGateway.call(capability, ctx, params) +┌────────────────────────▼────────────────────────────────┐ +│ 连接器层(Connector) │ +│ Transport 实现(首期 REST / SOAP)+ 声明式请求/响应映射 │ +│ resolve → build → call → map → classify → audit │ +└────────────────────────┬────────────────────────────────┘ + │ Transport.call(interface, client, request) +┌────────────────────────▼────────────────────────────────┐ +│ 配置层(Configuration) │ +│ ClientInstance / InterfaceDefinition / Binding / 版本 │ +│ CredentialReference(Secret 引用,非明文) │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## 3. 核心概念与实体 + +### 3.1 配置实体(5 个核心表 + 代码注册能力) + +| 实体 | 存哪 | 职责 | +| --- | --- | --- | +| **ConnectorType 连接器类型** | 代码常量 | Transport 实现:首期 `REST`、`SOAP`;后置 `RPA`、`SQL`、`FILE`,不单独建表 | +| **ClientInstance 客户端实例** | DB | 一份连接配置:连到哪、凭据引用、超时/TLS、默认 org/租户 | +| **InterfaceDefinition 接口定义(按版本存储)** | DB | 一个可调操作;每个版本一行,包含请求/响应配置、消息配置、映射、Schema、测试配置和发布状态 | +| **Binding 绑定** | DB | `(Capability, context_selector) → (ClientInstance + InterfaceDefinition 版本)`,含版本/生效区间/优先级/状态 | +| **CredentialReference 凭据引用** | DB | 仅存 `secret_ref` + 元数据;真实凭据由 Secret 服务注入,不回显 | +| **Capability 业务能力** | 代码注册 + DB 目录 | 强类型契约(见 §4),不依赖连接器配置表动态生成业务逻辑 | + +> 当前不单独建立 `Connector`、`MessageProfile`、`MappingVersion`、`Fixture` 表,也不把每个 Header、XML 节点或映射字段拆成关系表。接口版本是配置冻结边界:稳定身份、版本、状态、路由、安全和审计字段使用关系列;协议细节、模板、映射和测试引用使用 JSONB。未来只有在出现跨接口复用、独立权限/查询或统计需求时再拆表。 + +### 3.2 运行时实体(2) + +| 实体 | 职责 | +| --- | --- | +| **IntegrationCall** | 一次调用实例:能力、绑定版本、请求摘要、响应摘要、状态、耗时、trace_id | +| **IntegrationAsyncTask** | RPA/Webhook/MQ 等异步任务的提交、等待、回调与恢复状态(后置) | + +> 审计事件可关联以上两个实体,但**审计表不承担运行状态**;运行状态归 IntegrationCall / IntegrationAsyncTask。 + +### 3.3 关系字段与 JSONB 边界 + +**必须使用独立列**:主键、业务编码、外键、能力、连接器类型、端点、环境、版本、状态、启用标记、凭据引用、优先级、生效时间、超时、创建/更新时间,以及需要索引、唯一约束、权限、路由、统计或审计的字段。 + +**放入接口版本 JSONB**:REST 请求头/路径/Body 模板,SOAP 版本、命名空间、操作包装、`SOAPAction`、CDATA 和响应解码规则,请求/响应字段映射、白名单转换、成功/失败规则、输入输出 Schema、分页/分片/大小限制和协议扩展参数。 + +**大报文与 Golden Fixture**:真实请求/响应样例不直接塞入接口表;首期使用受控文件或对象存储,并在接口版本 JSON 中保存样例引用、校验和及场景标识。只有需要在线维护、权限管理或测试统计时才独立建 Fixture 表。 + +接口版本建议至少包含以下 JSONB 字段: + +```text +request_config_json +response_config_json +input_schema_json +output_schema_json +test_config_json +``` + +--- + +## 4. Capability 强类型契约 + +`Capability` **不能完全由数据库动态定义**,否则会退化为"管理员写业务逻辑"。 + +- **代码注册**:能力名称、输入 Schema、输出 Schema、幂等语义、是否允许写,由代码注册(如 `@register_capability`)。 +- **DB 只维护**:启用状态、版本、展示描述、绑定关系。 +- **领域只调标准能力**,例如: + +```text +query_inventory(input) -> InventoryResult +create_transfer(input) -> TransferResult +verify_duplicate(input) -> TransferResult +``` + +外部系统差异全部在 Connector 层(Transport + 映射)解决,不进入领域层。 + +> 能力命名规范:`.`,如 `in_transit_transfer.query_inventory`。本文其余处以短名 `query_inventory` 等指代,均属于 `in_transit_transfer` 域。 + +--- + +## 5. Binding 版本化与发布 + +Binding 至少包含: + +```text +capability +context_selector # 来源/组织/租户/环境等路由条件(含默认绑定) +client_instance # 版本引用 +interface_definition # 版本引用 +priority +environment +effective_from / effective_to +status # draft / published / retired +``` + +- 配置修改**不能影响运行中的任务**。 +- 一次 Run 创建时必须冻结:`ClientInstance 版本`、`InterfaceDefinition 版本(含消息与映射 JSON)`、`Binding 版本`、`Credential 引用版本`。 + +--- + +## 6. 表达式与映射限制 + +请求模板与返回映射**禁止**执行任意 Python / JavaScript / SQL。仅允许: + +- JSONPath / JMESPath(JSON) +- XPath(XML) +- SQL 命名参数(仅限预注册模板,见 §12) +- 白名单转换函数(`cast` / `decimal` / `date` / `default` / `fallback` / `enum-map` / `list-map` / `if-else`) +- 有限条件表达式 +- 变量占位符 + +所有表达式执行须有**超时、深度、长度、函数白名单**限制;输出经 JSON Schema 校验,不合法即 fail-closed 报错。 + +--- + +## 7. 运行时调用引擎(同步管线) + +``` +resolve(capability, context) → Binding → (client, interface, credential, mapping) +build_request(interface, params) → 该接口的原始请求 +transport.call(connector_type, client, request) → 原始响应 +map_response(mapping, raw) → 统一结果 DTO(经输出 Schema 校验) +classify(result) → success / business_failed / technical_failed / timeout / result_unknown +audit(IntegrationCall) +``` + +统一结果 DTO: + +```text +IntegrationCallResult(status, data, error_code, error_message, document_no?, trace_id) +``` + +首期 Transport 契约(同步): + +```text +rest.call(interface, client, request) -> raw_response +soap.call(interface, client, request) -> raw_response +``` + +### 7A. 标准 DTO 到目标系统请求的映射模型 + +领域层只传入能力定义的标准 DTO。连接器运行时按以下顺序完成转换: + +```text +标准 Capability DTO + → 输入校验/规范化 + → 声明式字段映射(标准字段 → 目标字段) + → Target Request Model(目标请求模型) + → Message Profile + Serializer(报文包装与序列化) + → Transport(SOAP/REST/...) +``` + +- **简单字段**:例如 `lot` → `img04`、`warehouse` → `img02`,通过路径映射和类型转换完成。 +- **数组/重复节点**:例如多个批号映射为多个 `Record`,由映射引擎按集合展开,禁止领域层拼接 XML。 +- **受控业务转换**:批号集合拼接、分片、日期/数量格式化等只能调用代码注册的白名单函数(如 `controlled_lot_condition`),不能执行任意脚本、SQL 或模板代码。 +- **缺失与冲突**:必填字段缺失、类型不符、映射产生非法结构时立即失败(fail-closed),并返回可定位的字段错误。 +- **输出**:目标响应先按协议解码,再按声明式映射转成标准输出 DTO,并通过 Capability 输出 Schema 校验。 + +映射配置建议采用结构化 JSON,而非自由文本表达式。例如: + +```json +{ + "fields": [ + {"source": "warehouse", "target": "img02", "required": true}, + {"source": "lots", "target": "img04", "expand": "record", "required": true} + ] +} +``` + +### 7B. Message Profile 与 Transport 分离 + +SOAP Transport 只负责 HTTP/SOAP 通讯(URL、TLS、超时、认证、响应状态),不写死任何供应商的操作名或 XML 结构。接口版本 JSON 中的 `message` 配置(逻辑上的 Message Profile,不单独建表)负责协议消息细节: + +- SOAP 版本、Envelope/Body 命名空间; +- 操作元素名称及命名空间; +- `SOAPAction`(包括必须为空字符串的场景); +- 请求参数承载方式(元素、属性、CDATA、纯文本或 JSON); +- body wrapper、内层根节点、重复节点规则; +- 响应外层路径、转义字符串二次解析规则及错误定位。 + +因此 `GetItemStockListRequest`、`RequestContent`、`img01` 等均属于接口版本的消息配置,不属于通用代码。REST 也采用同样的“请求模板 + 序列化器”模型,以便未来接入非 TIPTOP SOAP 服务。配置引擎必须能够从标准 DTO 完整生成最终 HTTP 报文,而不是要求领域层预先拼接目标 XML/JSON。 + +### 7C. WSDL 自动发现、确认与版本冻结 + +WSDL 仅用于生成接口草稿,不能直接作为生产运行时的唯一真相: + +1. 导入 WSDL,发现 service/port/binding/operation、命名空间、SOAP 版本和默认 action; +2. 生成可编辑草稿,并标出 WSDL 无法确定的字段承载方式(如 CDATA 内嵌 XML); +3. 使用真实测试报文进行连接测试和试运行,人工确认请求/响应路径及映射; +4. 发布后生成不可变版本,后续修改必须创建新版本并重新测试; +5. 运行中的 Run 固定引用的版本,禁止配置热变更影响执行。 + +### 7D. TIPTOP Gateway Profile 示例(非通用约束) + +当前 TIPTOP Gateway 可建为 `tiptop_gateway_v1` Message Profile,仅作为一个外部系统适配示例: + +- SOAP 1.1,`SOAPAction` 按对方要求配置(成功样例为空字符串); +- Body 操作包装名由接口定义/WSDL 草稿确认,例如 `GetItemStockListRequest`; +- `request` 参数承载 CDATA 内嵌业务 XML; +- 业务 XML 包含 `Access`、`RequestContent/Parameter/Record/Field`; +- 响应的 `response` 可能是 XML 转义字符串,需先 XML decode,再解析 `Response/Execution/Status` 和 `Document/RecordSet`; +- `Field[@name,@value]` 转换为标准库存记录,具体 `img` 字段字典必须在接口映射中维护。 + +用户名、密码、应用 ID 等只引用 Secret,占位符或 Secret 引用不得在文档、日志和配置快照中保存明文。 + +### 7E. 批号库存批量查询与分片 + +自动调拨输入是收料文件中的批号集合,标准输入示例: + +```json +{"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25071403"]} +``` + +连接器必须支持一次请求携带多个批号,不能按批号逐条调用。由于外部系统存在报文大小、网关超时和 XML/JSON 解析限制,接口定义应配置: + +- 最大批号数、最大请求字节数、最大响应字节数; +- 超限时按稳定顺序自动分片; +- 分片并发上限、单片超时、失败策略(是否整体失败); +- 分片结果按批号/料号等业务键去重、合并并保持可追溯的 `trace_id`。 + +分片不是领域规则,属于连接器执行策略;数量核对、来源隔离和调拨决策仍由领域层负责。 + +### 7F. 配置测试与发布门禁 + +每个接口版本至少通过以下测试后才能发布: + +- schema 校验:标准输入、必填项、数组边界、非法类型; +- golden request:生成报文与已确认样例逐项比对(命名空间、wrapper、SOAPAction、CDATA); +- golden response:覆盖成功、业务失败、技术失败、空结果和 XML 转义响应; +- 大批量测试:验证分片、合并、超时和大小上限; +- 安全测试:凭据脱敏、禁止任意表达式、禁止客户端覆盖 `interface_id`; +- 回归测试:输出 DTO 与领域层契约保持兼容。 + +连接测试只证明网络和认证可用;接口试运行还必须证明请求结构、响应解析和业务映射均正确。任何一项失败都不得发布。 + +--- + +## 8. RPA 与异步执行(后置,但契约先定) + +RPA **不是 FILE 的别名**,也不是普通同步调用。它必须拥有独立 Transport Contract: + +```text +submit_trigger # 写 trigger 文件/信号,原子提交 +callback_authentication # 回调签名/防重放 +heartbeat # Worker 心跳与能力声明 +timeout_recovery # 超时恢复与反查 +artifact_locator # 结果产物定位(文件/共享目录) +result_file_mapping # 结果文件 → 标准数据(复用 FILE 映射) +``` + +即:**RPA = 异步 Transport + 文件结果适配器**,不能只配置成"触发一个文件,然后按 FILE 读取"。 + +异步管线(预留): + +``` +resolve → submit(trigger) → 注册 IntegrationAsyncTask → 等待(心跳/回调) → 结果落盘 → map → classify → audit +``` + +首期**不实现** RPA 通用连接器内核;继续复用现有收料 RPA 能力(`shipping_notice/receipt_rpa.py` + `rpa_worker_heartbeat.py`)。待框架稳定后再将 RPA 接入为异步 Transport。 + +--- + +## 9. AI / 外部应用暴露面 + +### 9.1 只暴露 Capability,不暴露原始接口 + +AI 与其他应用只能看到: + +```text +query_inventory +create_transfer +verify_duplicate +get_transfer_status +download_receipt_file +``` + +不应知道:ERP 地址、SOAP Action、凭据、原始请求模板、外部系统接口编号、`interface_id`。 + +### 9.2 治理门禁 + +- 能力级 RBAC(复用 `app/core/decorators.py` + `action_registry.py` 的 `ACTION_AGENT_CODES` 模式) +- 租户 / 组织范围校验 +- 写操作确认门禁 +- 幂等键 +- 调用额度与超时 +- `result_unknown` 禁止自动重试 +- 高风险操作的人工确认或策略开关 + +### 9.3 通用 REST 网关(谨慎) + +`POST /api/integration/call` 灵活但风险高,约束如下: + +- 对外默认使用**能力白名单**; +- **不允许**客户端直接传 `interface_id` 覆盖 Binding; +- `interface_id` 仅作后台诊断参数,普通 Agent / 外部应用不可传; +- 推荐生成**能力专用端点**或统一工具名,例如: + +```text +POST /api/integration/capabilities/query_inventory +``` + +### 9.4 多面暴露(一次定义、多面复用) + +每个 InterfaceDefinition 自动生成**工具描述**(name / 描述 / 入参 Schema / 出参 Schema / 鉴权): + +1. **REST 网关**(其他应用) +2. **MCP Server**(对标 MCP 的 Agent,后置) +3. **Dify 自定义工具**(接入现有 `action_registry.py`) + +--- + +## 10. 凭据模型(引用 + Secret 元数据) + +DB **不保存真正凭据内容**,只保存: + +```text +secret_ref +secret_provider +credential_type +version +status +last_verified_at +``` + +- ClientInstance 引用 `secret_ref`; +- 切换凭据通过版本更新,**不能覆盖运行中的调用**; +- 凭据不回显、不写日志、不进配置快照(复用调拨 `sanitize_snapshot` 思路)。 + +--- + +## 11. 配置作业完整生命周期 + +客户端配置页不是简单 CRUD,而是: + +```text +草稿 +→ 参数校验 +→ 连接测试 +→ 接口试运行 +→ 返回映射预览 +→ 发布 +→ 生效 +→ 停用 +``` + +- 试运行必须使用**脱敏样本或测试环境**; +- "测试连接成功"不代表业务映射正确——试运行须同时校验成功响应与业务错误响应的映射结果。 + +--- + +## 12. SQL 连接器限制(后置) + +SQL 连接器除"默认只读"外,还须: + +- 只允许**预注册查询模板**; +- 禁止 AI 直接生成 SQL; +- 禁止多语句、DDL、DML、存储过程调用; +- 限制表、字段、行数、执行时长; +- 返回结果必须经输出 Schema 校验与脱敏。 + +--- + +## 13. 与在途调拨的接入(首个消费者) + +### 13.1 责任分层 + +| 层 | 负责 | 不负责 | +| --- | --- | --- | +| 领域层 | 数量严格匹配、D+1、幂等、写前复查、`result_unknown`、来源隔离、审计 | 协议、地址、凭据、字段路径 | +| 连接器层 | `query_inventory` / `create_transfer` / `verify_duplicate` 的请求/响应映射与 SOAP/REST 传输 | 是否该调拨、数量判定 | + +### 13.2 接入方式 + +- 领域代码改为通过 `CapabilityGateway` 调能力 `in_transit_transfer.query_inventory / create_transfer / verify_duplicate`; +- 现有 `RouteResolver`(按来源解析 org/仓库)**不替换**,其输出的来源上下文作为 `context_selector` 喂给 Binding; +- 预置绑定:`(query_inventory, DBS-AWSBI)` → 当前 ERP 客户端 + 查询接口;将来 `(query_inventory, CRANE-SZ)` → 新 WMS 客户端 + 接口,只加配置行; +- 移除 ERP 专属 `ErpAdapter` 作为通用层;ERP 仅作为框架接入的外部系统实例。 + +--- + +## 14. MVP 范围与分期 + +### 14.1 首期最小可行(MVP) + +实体:5 个核心配置/运行表(`ClientInstance`、按版本存储的 `InterfaceDefinition`、`Binding`、`CredentialReference`、`IntegrationCall`);`Capability` 由代码注册,`ConnectorType` 由代码实现。 + +Transport:仅 `REST`、`SOAP`。 + +能力:仅注册 3 个: + +```text +query_inventory # 查询外部系统库存 +create_transfer # 创建/审核/过账调拨单 +verify_duplicate # 确认重复 Invoice 对应原单 +``` + +### 14.2 分期 + +| 阶段 | 内容 | 明确不做 | +| --- | --- | --- | +| **P0** | 连接器内核与通用配置闭环:`CapabilityGateway` + REST/SOAP Transport + ClientInstance/InterfaceDefinition/Binding + 版本化配置 + Secret 引用 + 连接测试/接口试运行;`query_inventory` 首个配置绑定消费者 | 任意脚本转换、低代码流程编排 | +| **P1** | 配置作业 UI(草稿→校验→测试→试运行→预览→发布→回滚/停用)+ AI 暴露(只暴露治理后的能力) | interface_id 直传、原始接口暴露 | +| **P2** | 异步与更多协议:RPA / FILE / Webhook / MQ / MCP / SQL 只读查询 | 不受控的通用脚本执行 | + +--- + +## 15. 落地文件与数据迁移(P1 起) + +- 模型:`app/models/integration_connector.py`(ClientInstance / 按版本存储的 InterfaceDefinition / Binding / CredentialReference / IntegrationCall;异步能力启用后再增加 IntegrationAsyncTask) +- 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`) +- API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单) +- Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业) +- 迁移:Alembic 新迁移,挂在当前 head 后 + +--- + +## 16. 安全 / 审计 / fail-closed 总则 + +- 能力级 RBAC;SQL 默认只读、写操作须显式标记 + 强制审计; +- 凭据仅 Secret 引用,日志脱敏; +- 缺端点 / 缺凭据 / 映射不合法 → fail-closed 拒绝,绝不猜测; +- 每次调用落 `IntegrationCall`;配置创建/测试/发布/停用记前后快照审计; +- 写操作必须携带幂等键,`result_unknown` 禁止自动重试。 + +--- + +## 17. 首期验收标准 + +- 新增外部系统实例(换系统)无需修改调拨领域代码; +- 修改外部字段路径需发布新的 `InterfaceDefinition` 版本; +- 一次 Run 能追溯到冻结的全部配置版本; +- 原始 SOAP/REST 报文不进入调拨领域表; +- 凭据不回显、不写日志、不进快照; +- AI / 外部应用只能调用治理过的 Capability,无法传入 `interface_id` 或原始接口参数; +- 数量严格匹配、D+1、写前复查、`result_unknown` 禁重试等规则仍在领域层生效。 +- SOAP 报文可由配置完整生成并解析:支持命名空间、wrapper、SOAPAction、CDATA/内嵌 XML、XML 属性字段及转义响应。 +- 多批号库存查询支持单次批量请求、大小限制下自动分片及结果合并,不产生逐批号调用风暴。 +- WSDL 导入可生成草稿;人工确认后发布冻结版本,golden request/response 和边界测试全部通过。 + +--- + +## 18. 相关文档 + +- [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) +- 在途仓自动调拨实现(Phase 0/1):`backend/app/services/in_transit_transfer/` +- Chat Action Registry(Agent 挂载点):`backend/app/services/chat/action_registry.py` diff --git a/docs/platform/integration-connector-prototype.html b/docs/platform/integration-connector-prototype.html new file mode 100644 index 00000000..ef447661 --- /dev/null +++ b/docs/platform/integration-connector-prototype.html @@ -0,0 +1,94 @@ + + + +HXOPS 集成连接器配置中心 +
平台管理 / 集成连接器
测试环境曹慧鹏曹
Integration connector

集成连接器配置中心

管理外部系统连接、接口报文和能力绑定。接口编辑、测试和发布都在接口定义详情内完成。

42 个生产 · 2 个测试
1210 个已发布
1,284成功率 99.7%
2需要试运行或验证
+

配置总览

当前环境的连接和发布状态
连接实例健康4 / 4 正常
已发布接口10 / 12
能力绑定覆盖8 个来源上下文
最后一次发布今天 09:42

待处理

配置作业
库存查询 v4 草稿待试运行
DBS 凭据轮换待确认

配置原则

关系字段保存身份、版本、状态和路由。JSON 配置保存协议细节、模板和映射。

最近变更

时间对象动作结果
09:42get_item_stock_list v3发布接口版本成功
09:18TIPTOP-TEST连接测试成功
+
客户端实例
连接地址、协议、环境、超时和凭据引用
实例协议环境地址超时凭据状态操作
TIPTOP-TEST
TIPTOP 测试客户端
SOAP 1.1测试topgp.../web/ws/r60stiptop-test连接正常 
WMS-PROD
仓储管理系统
REST生产wms-api.../v230swms-prod连接正常 
DBS-RPA
DBS 收料文件
RPA生产共享目录120sdbs-rpa待验证
+
接口定义
接口编辑、测试、发布都在接口详情内完成
接口编码能力客户端协议版本状态最近测试操作
get_item_stock_list
批号库存查询
query_inventoryTIPTOP-TESTSOAPv3已发布今天 09:18
create_transfer
创建调拨单
create_transferTIPTOP-TESTSOAPv2已发布昨天 16:02
wms_inventory_query
仓库库存查询
query_inventoryWMS-PRODRESTv1草稿未测试
+
1
基本信息接口身份和客户端
2
请求映射DTO 到目标报文
3
响应映射返回标准结果
4
测试与发布验证后冻结版本

get_item_stock_list · 请求映射

草稿 v4 · TIPTOP-TEST · SOAP

标准输入 DTO

领域层只传标准结构,不了解 XML 节点、SOAPAction 或外部字段名。

消息配置与请求映射

SOAP 特有的命名空间、包装节点和 CDATA 规则都属于接口版本。

+
能力绑定
按来源、组织和环境选择客户端与接口版本
能力来源上下文客户端接口版本优先级状态操作
in_transit_transfer.query_inventoryDBS-AWSBI / TGHXTIPTOP-TESTget_item_stock_list v310已发布
in_transit_transfer.create_transferDBS-AWSBI / TGHXTIPTOP-TESTcreate_transfer v210已发布
+
凭据引用
只保存 Secret 引用,不保存密码和 Token
编码Secret 引用提供方类型版本状态操作
tiptop-testsecret://integration/tiptop-testVaultbasic_auth3有效 
wms-prodsecret://integration/wms-prodVaultbearer2有效
+
能力清单
AI 和外部应用只能调用治理后的业务能力
能力用途写操作幂等语义绑定数对外暴露操作
query_inventory查询外部库存否可重复读取3允许
create_transfer创建并提交调拨是必须幂等键2需确认
+
调用记录
展示脱敏摘要,原始报文按权限和保留周期管理
时间Trace ID能力客户端接口版本耗时结果操作
09:42:18tr_8f31c0query_inventoryTIPTOP-TESTv3684 ms成功
09:16:52tr_8f201dcreate_transferTIPTOP-TESTv220.0 s结果未知
+
+ diff --git a/docs/superpowers/plans/2026-08-20-shipping-notice-five-stage-lifecycle.md b/docs/superpowers/plans/2026-08-20-shipping-notice-five-stage-lifecycle.md deleted file mode 100644 index 43cc960c..00000000 --- a/docs/superpowers/plans/2026-08-20-shipping-notice-five-stage-lifecycle.md +++ /dev/null @@ -1,176 +0,0 @@ -# Shipping Notice Five-Stage Lifecycle Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Make `接收解析 -> 订单复核 -> 通知准备 -> 货代上传 -> 通知完成` the only user-visible Shipping Notice lifecycle, where completion means verifiable freight-upload success. - -**Architecture:** Keep Process Gate, Intake, Run/Unit, upload attempt and technical progress as execution facts. Extend the existing shared read-model projection with `freight_upload`; inject `upload_complete` only when the canonical success predicate confirms task status, every reservation and an audit-backed succeeded upload attempt. API consumers receive `lifecycle_nodes`; `four_stage_nodes` remains a one-release compatibility alias. - -**Tech Stack:** Flask, SQLAlchemy, pytest, Vue 3, TypeScript, Vue I18n, Vitest. - ---- - -### Task 1: Define the server-side lifecycle and success predicate - -**Files:** -- Modify: `backend/app/services/shipping_notice/lifecycle_projection.py` -- Modify: `backend/app/services/shipping_notice/ui_state.py` -- Modify: `backend/app/services/shipping_notice/process_gate_contract.py` -- Test: `backend/tests/test_shipping_notice_ui_state.py` - -- [ ] **Step 1: Add failing assertions for the new stage and completion boundary** - -```python -assert state['lifecycle_stage'] == 'freight_upload' -assert [entry['code'] for entry in state['lifecycle_entries']][-2:] == [ - 'freight_upload', 'upload_complete', -] -assert completed_state['lifecycle_stage'] == 'upload_complete' -``` - -- [ ] **Step 2: Run the focused UI-state test** - -Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py` -Expected: failing assertions because the current implementation has four lifecycle stages. - -- [ ] **Step 3: Implement one canonical predicate and five-stage projection** - -```python -def has_verified_upload_success(task: ShippingNotice) -> bool: - return ( - task.upload_status == 'uploaded' - and reservations_are_uploaded(task) - and has_succeeded_upload_attempt(task) - ) - -if has_verified_upload_success(task): - lifecycle_stage = 'upload_complete' -elif gate_code in LIFECYCLE_STAGE_BY_GATE: - lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] -``` - -Map `freight_upload_rpa`, `manual_upload_handoff`, and all upload-pending/failure/unknown reasons to `freight_upload`. Map only a verified success to `upload_complete`; update Gate `ui_placement.target_surface` to `freight_upload`. - -- [ ] **Step 4: Re-run the focused UI-state test** - -Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py` -Expected: PASS. - -### Task 2: Evolve batch projection without breaking callers - -**Files:** -- Modify: `backend/app/services/shipping_notice/shipping_processing_projection.py` -- Modify: `backend/tests/test_shipping_processing_projection.py` -- Modify: `backend/tests/test_shipping_processing_projection_stage4.py` - -- [ ] **Step 1: Add failing batch-node assertions** - -```python -assert [node['code'] for node in payload['lifecycle_nodes']] == [ - 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', -] -assert payload['four_stage_nodes'] == payload['lifecycle_nodes'] -``` - -- [ ] **Step 2: Implement `lifecycle_nodes` and compatibility alias** - -```python -lifecycle_nodes = _batch_lifecycle_nodes(work_items) -payload['lifecycle_nodes'] = lifecycle_nodes -payload['four_stage_nodes'] = lifecycle_nodes # deprecated compatibility field -``` - -Use the shared success predicate when deriving an item lifecycle so technical `completed`, a PDF candidate, a reference number, cancellation, or archive cannot make an item complete. - -- [ ] **Step 3: Run the projection tests** - -Run: `cd backend; pytest -q tests/test_shipping_processing_projection.py tests/test_shipping_processing_projection_stage4.py tests/test_shipping_projection_cross_surface.py` -Expected: PASS. - -### Task 3: Make all frontend surfaces consume five lifecycle stages - -**Files:** -- Modify: `frontend/src/features/chat/types/shipping.api.types.ts` -- Modify: `frontend/src/features/chat/shipping/shippingStepper.ts` -- Modify: `frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue` -- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue` -- Modify: `frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue` -- Modify: `frontend/src/features/shipping-progress/components/WorkbenchProgressGrouped.vue` -- Test: `frontend/src/features/chat/shipping/shippingStepper.spec.ts` -- Test: `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts` -- Test: `frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts` - -- [ ] **Step 1: Add failing five-stage type and rendering tests** - -```ts -expect(resolveShippingWorkflowSteps({ ui_state: { steps } })).toHaveLength(5) -expect(wrapper.text()).toContain('货代上传') -expect(wrapper.text()).toContain('通知完成') -``` - -- [ ] **Step 2: Update shared types and Stepper** - -Add `'freight_upload'` to `LifecycleWorkbenchStage`, stage-node DTOs and the five label-key array. Prefer `lifecycleNodes`; retain the old field only as an API fallback. - -- [ ] **Step 3: Split the lifecycle workbench surfaces** - -`freight_upload` hosts Excel download, RPA retry/poll, manual evidence registration and unknown-result reconciliation. `upload_complete` becomes read-only success evidence: uploaded time, freight receipt/reference, succeeded attempt and reservation summary. Do not move action authorization into the frontend. - -- [ ] **Step 4: Ensure polling does not stop at freight-upload** - -Keep polling while `lifecycleStage === 'freight_upload'`; stop only after verified `upload_complete`, cancellation, archive, or explicit terminal failure. - -- [ ] **Step 5: Run focused frontend tests** - -Run: `cd frontend; npm run test:unit -- shippingStepper.spec.ts ShippingOrderReviewView.spec.ts ShippingConversationProcessingCard.spec.ts` -Expected: PASS. - -### Task 4: Synchronize i18n and documentation - -**Files:** -- Modify: `frontend/src/locales/zh-CN/chat.json` -- Modify: `frontend/src/locales/zh-TW/chat.json` -- Modify: `frontend/src/locales/en/chat.json` -- Modify: `frontend/src/locales/th/chat.json` -- Modify: `frontend/src/locales/zh-CN/workspace.json` -- Modify: `frontend/src/locales/zh-TW/workspace.json` -- Modify: `frontend/src/locales/en/workspace.json` -- Modify: `frontend/src/locales/th/workspace.json` -- Modify: `docs/demand.md` -- Modify: `docs/tec.md` -- Modify: `docs/funclist.md` -- Modify: `docs/features/shipping-notice/technical.md` -- Modify: `docs/features/shipping-notice/business.md` - -- [ ] **Step 1: Add all four-language stage and work-surface labels** - -Add `freightUpload` and descriptions for upload in progress, manual upload pending, failure, and unknown result. Retain `uploadComplete` text as `通知完成`; its description must require verified success. - -- [ ] **Step 2: Update the authoritative business and technical contracts** - -Replace four-stage wording with the five-stage order. Document the single success predicate, unknown-result handling, `lifecycle_nodes` compatibility period, and the rule that completed lists/statistics use verified success only. - -- [ ] **Step 3: Validate locale JSON** - -Run: `Get-ChildItem frontend/src/locales/*/{chat,workspace}.json | ForEach-Object { Get-Content -Raw $_ | ConvertFrom-Json | Out-Null }` -Expected: no output and exit code 0. - -### Task 5: Full verification - -**Files:** -- Verify all modified files. - -- [ ] **Step 1: Run focused backend regression** - -Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py tests/test_shipping_upload_attempt.py tests/test_shipping_manual_upload_evidence.py tests/test_shipping_upload_unknown_state.py tests/test_shipping_processing_projection.py tests/test_shipping_processing_projection_stage4.py tests/test_shipping_projection_cross_surface.py` -Expected: PASS. - -- [ ] **Step 2: Build frontend** - -Run: `cd frontend; npm run build` -Expected: PASS. - -- [ ] **Step 3: Check diff integrity** - -Run: `git diff --check; git status --short` -Expected: no whitespace errors; status lists only the planned files plus pre-existing user changes. diff --git a/docs/superpowers/plans/2026-08-21-shipping-profile-anchor-frame.md b/docs/superpowers/plans/2026-08-21-shipping-profile-anchor-frame.md deleted file mode 100644 index fa0ed42e..00000000 --- a/docs/superpowers/plans/2026-08-21-shipping-profile-anchor-frame.md +++ /dev/null @@ -1,264 +0,0 @@ -# Shipping Profile Anchor Frame Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 让坐标 Profile 能在同一稳定版式因动态内容导致主表纵向平移时,使用冻结的锚点坐标框架完成确定性匹配和取值,而不影响未启用该能力的模板。 - -**Architecture:** 在现有 `OrderCoordinateProfile` 中增加可选的扁平 `coordinate_model` 声明(`type`、`anchors`、`max_translate_x`、`max_translate_y`)。matcher 从当前 Layout 的唯一锚点和主表结构计算受限的平移变换;同一变换贯穿表头观测、主表定位、订单头字段和值框、订单行坐标重建,禁止建立第二套偏移估算机制。 - -**Tech Stack:** Flask、Pydantic、SQLAlchemy JSON Profile、pytest、Vue 3、TypeScript、Vue I18n、Vitest。 - -## Global Constraints - -- 原 PDF 是不可变事实;匹配和解析所需的页级坐标必须通过 `ensure_on_demand_coordinate_evidence()` 获取。 -- 未声明 `coordinate_model.type = anchor_frame` 的 Profile 必须逐位保持现有 matcher、取值、阈值和候选排序行为。 -- 不允许按订单号、客户名、文件名或固定偏移量写代码;不建立按 PDF 的坐标变体。 -- 仅允许平移;锚点不存在、不唯一、位移超过模板上限、关键结构冲突或多个 Profile 合格时必须 `review_required`。 -- Schema 是唯一业务字段契约;Dify 不参与模板选择、坐标变换或正式值取值。Dify 配置由用户维护,本项目仅在收尾文档说明其边界。 -- 不改数据库表结构、不新增依赖、不修改其他 Profile 数据;FOX MX Profile 现版数据在后端能力通过回归后再单独受控更新。 - ---- - -### Task 1: 冻结 Profile 契约与变换审计输出 - -**Files:** -- Modify: `backend/app/services/shipping_notice/document_layout/order_profile.py` -- Modify: `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py` -- Test: `backend/tests/test_shipping_order_profile_matcher.py` - -**Interfaces:** -- Produces `CoordinateModel` / `AnchorFrameCoordinateModel`,作为 `OrderCoordinateProfile.coordinate_model`。 -- Produces `CoordinateTransform`,包含 `status`、`translate_x`、`translate_y`、`anchor_ids`、`reason_codes`;仅含配置身份与数值,不含正文。 -- Extends `ProfileMatchCandidate` with optional `coordinate_transform`. - -- [ ] **Step 1: 写入失败用例** - -```python -def test_anchor_frame_matches_same_structure_after_bounded_vertical_translation(): - profile = _with_signature(_profile('PO_A', coordinate_model={ - 'type': 'anchor_frame', - 'anchors': [{'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'region': {'x0': .1, 'y0': .05, 'x1': .9, 'y1': .15}}], - 'max_translate_x': .01, 'max_translate_y': .04, - }), _layout()) - result = match_frozen_coordinate_profiles(profiles=[profile], layout=_translated_layout(.03)) - assert result.status == 'unique_match' - assert result.candidates[0].coordinate_transform['translate_y'] == .03 -``` - -- [ ] **Step 2: 验证 RED** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k anchor_frame` - -Expected: FAIL,因为 Profile 契约尚不接受 `coordinate_model`,且 matcher 未输出变换。 - -- [ ] **Step 3: 最小实现** - -```python -class AnchorFrameCoordinateModel(OrderProfileModel): - type: Literal['anchor_frame'] - anchors: list[AnchorRule] = Field(min_length=1, max_length=4) - max_translate_x: float = Field(default=.03, ge=0, le=.15) - max_translate_y: float = Field(default=.06, ge=0, le=.20) - -class CoordinateModel(OrderProfileModel): - type: Literal['legacy', 'anchor_frame'] = 'legacy' - anchor_frame: AnchorFrameCoordinateModel | None = None -``` - -在 matcher 中仅当 `anchor_frame` 明确启用时从唯一静态锚点计算一致的 X/Y 平移;超界、缺失、歧义或多个锚点不一致必须为硬失败原因。对当前观察表头和主表 bbox 应用该平移后才评分;`legacy` 路径不改。 - -- [ ] **Step 4: 验证 GREEN 与旧逻辑回归** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py` - -Expected: PASS;新增用例覆盖受限平移、缺锚点、歧义锚点、超界平移和 legacy 不变。 - -### Task 2: 让已选变换贯穿 Profile 行重建 - -**Files:** -- Modify: `backend/app/services/shipping_notice/order_extraction_workflow.py` -- Modify: `backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py` -- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py` -- Test: `backend/tests/test_shipping_generic_order_gate.py` - -**Interfaces:** -- Consumes `ProfileMatchResult` 中唯一选中 Profile 的 `coordinate_transform`。 -- Extends `reconstruct_coordinate_profile_rows(..., coordinate_transform: dict | None = None)`。 -- Produces仅以同一运行时平移投影后的表区/行区重建结果。 - -- [x] **Step 1: 写入失败用例** - -```python -def test_reconstruction_uses_selected_anchor_frame_translation_for_all_subrows(): - rows = reconstruct_coordinate_profile_rows( - characters=_translated_rows(.03), table_bbox=_page_bbox(), - table_region=_legacy_region(), line_layouts=_layouts(), - coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .03}, - ) - assert rows[0].fields['customer_po_line_no'] == '00010' -``` - -- [x] **Step 2: 验证 RED** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py -k anchor_frame` - -Expected: FAIL,因为重建函数没有接收或应用运行时变换。 - -- [x] **Step 3: 最小实现** - -为坐标重建增加仅限 `status=applied` 的平移投影;校验平移数字有限且投影框仍在页内,非法变换返回现有的不可重建结果。工作流必须从共同 matcher 的唯一结果传递同一 `coordinate_transform`,不能重新计算、不能按 raw table 猜测偏移。 - -- [x] **Step 4: 验证 GREEN 与路由门禁** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_generic_order_gate.py` - -Expected: PASS;缺失/非法变换保持 `coordinate_evidence_unavailable → review_required`,其他 Profile 路由不变。 - -### Task 3: 管理端声明与复核端审计展示 - -**Files:** -- Modify: `frontend/src/features/admin/types/shipping-order-document-profile.types.ts` -- Modify: `frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue` -- Modify: `frontend/src/features/chat/types/shipping.api.types.ts` -- Modify: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.vue` -- Modify: `frontend/src/locales/zh-CN/chat.json` -- Modify: `frontend/src/locales/zh-TW/chat.json` -- Modify: `frontend/src/locales/en/chat.json` -- Modify: `frontend/src/locales/th/chat.json` -- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts` - -**Interfaces:** -- Admin payload accepts optional `coordinate_model`,默认 `legacy`,只有管理员显式确认时才提交 `anchor_frame`。 -- Review DTO exposes `coordinate_transform` only for the selected/current candidate and reason codes only. - -- [x] **Step 1: 写入失败的前端展示用例** - -```ts -it('shows anchor-frame translation only in the technical template-match detail', () => { - const wrapper = mount(ReviewProfileMatchPanel, { props: { profileMatch: anchorFrameMatch } }) - expect(wrapper.text()).toContain('锚点坐标框架') - expect(wrapper.text()).toContain('纵向平移') -}) -``` - -- [x] **Step 2: 验证 RED** - -Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts` - -Expected: FAIL,因为 DTO 和面板尚未呈现坐标框架诊断。 - -- [x] **Step 3: 最小实现** - -在现有 Profile 编辑器增加受控的“相对锚点坐标框架”选项:默认关闭,启用时要求至少一个唯一静态 AnchorRule 与 X/Y 上限。复核面板只展示模式、是否应用、X/Y 平移和稳定 reason code;不显示原始字符、不显示完整 PDF 坐标、不新增终端用户操作。 - -- [x] **Step 4: 验证 GREEN、四语一致和构建** - -Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build` - -Expected: PASS;所有新增 i18n key 存在于四种语言,构建无 TypeScript 错误。 - -### Task 4: 当前 FOX MX 现版数据、端到端回归与正式文档 - -**Files:** -- Modify: `docs/demand.md` -- Modify: `docs/tec.md` -- Modify: `docs/funclist.md` -- Modify: `docs/features/shipping-notice/technical.md` -- Modify: `docs/features/shipping-notice/business.md` -- Modify: current database Profile `61` only after Task 1-3 pass -- Test: `backend/tests/test_shipping_order_profile_matcher.py` -- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py` -- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts` - -**Interfaces:** -- FOX MX current Profile uses `coordinate_model.type = anchor_frame`; it has no order-number-specific rule and no stored A/B variant. -- Dify document only explains that Dify must not participate in this deterministic path; it contains no credentials or platform mutation. - -- [ ] **Step 1: 增加真实 Layout 回归测试** - -```python -def test_fox_mx_anchor_frame_matches_baseline_and_dynamic_vertical_shift(app): - assert _match_profile_layout(profile_id=61, layout_id=124).status == 'unique_match' - assert _match_profile_layout(profile_id=61, layout_id=346).status == 'unique_match' - assert _match_profile_layout(profile_id=61, layout_id=344).status == 'unique_match' -``` - -- [ ] **Step 2: 验证 RED** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k fox_mx_anchor_frame` - -Expected: FAIL,直到当前 Profile 明确声明 `anchor_frame` 且现版签名/定义一致。 - -- [ ] **Step 3: 受控更新现版 Profile 数据** - -只在 Task 1-3 的全量相关测试通过后,事务更新 Profile 61 的 `definition_json`、结构指纹、checksum、matching signature 及其 validation run;不新建版本。变换锚点仅取固定标题/表头等静态文本,基线为 `4210007483.pdf`,回归样本为 `4210012208.pdf` 和 `4210012210.pdf`。 - -- [ ] **Step 4: 完成端到端验证和正式文档** - -Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_order_field_extraction.py tests/test_shipping_generic_order_gate.py` - -Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build` - -Run: `git diff --check` - -Expected: 全部 PASS;正式文档包含架构、失败闭环、其他模板隔离、FOX MX 校准规则及 Dify 手动配置边界。 - -## Phase Review Gates - -| 阶段 | 关键节点 | 放行证据 | -| --- | --- | --- | -| 1 | 范围/数据基线/既有能力 | 本计划、Profile 61 回滚校验、2208/2210 差异证据、未影响其他 Profile 的 DB 查询 | -| 2 | 契约/Matcher/行重建 | RED→GREEN 测试、legacy 回归、缺锚/歧义/超界 fail-closed 测试 | -| 3 | 管理端/复核端/i18n | Vitest、四语言 JSON 解析、前端 build、无新增用户端越权动作 | -| 4 | 数据/全链路/文档 | 三份 FOX PDF 真实 Layout 回归、相关后端测试、前端 build、`git diff --check`、文档一致性检查 | - -## Phase 1 Review Record - -- [x] 原因确认:2026-08-20 将 Profile 61 的表格/表头/行布局整体下移 `0.0124703088`,使 Layout 344 命中但 Layout 346 发生 `profile_header_signature_conflict`。 -- [x] 基线恢复:Profile 61 与 validation run #150 已恢复至 `4210007483.pdf` 对应的历史冻结定义;Layout 124 和 346 已复算为 `unique_match`。 -- [x] 范围确认:不采用按 PDF 的 A/B 变体,不改变全局 matcher 阈值,不改 Dify,不新增数据库表。 -- [x] 影响确认:本阶段仅修改计划文档;已有数据库恢复仅涉及 Profile 61,其他 6 个 Profile 未写入。 -- [x] 下一阶段准入:已具备最小契约、测试和隔离边界,可进入后端 TDD。 - -## Phase 2 Review Record - -- [x] 契约/Matcher:`legacy` 默认路径保持 `coordinate_transform=None`;`anchor_frame` 仅由唯一静态锚点计算有限平移,缺失、歧义、不一致、超界均 fail-closed。 -- [x] 评分一致性:matcher 对当前观察和七维结构评分均使用不回写冻结签名的平移副本;签名校验仍使用冻结签名原文。 -- [x] 行重建:共同 matcher 选中的变换只经 Profile 身份校验后传入工作流;页级裁剪、表区、物理行、字段区、终止/排除区使用同一内存投影。 -- [x] Fail-closed:非法/缺失变换不回退旧绝对坐标,保持 `order_profile_coordinate_reconstruction_unavailable -> coordinate_evidence_unavailable`。 -- [x] 回归证据:matcher 24 passed;坐标重建 40 passed;通用路由门禁 22 passed。 -- [x] 范围 Review:未新增数据库表、依赖、Profile 版本或 Dify 配置;未改变订单头第二套取值机制;其他 legacy Profile 调用点默认行为不变。 -- [x] 下一阶段准入:后端变换闭环已完成并通过阶段验收,进入管理端/复核端/i18n 实现。 - -## Phase 3 Review Record - -- [x] DTO 契约:前端与后端统一使用扁平 `coordinate_model`(`type`、`anchors`、`max_translate_x`、`max_translate_y`),不保留嵌套变体。 -- [x] 管理端:默认 `legacy`;仅显式选择 `anchor_frame` 才提交配置;锚点为空、无坐标或 X/Y 上限越界时保存门禁阻断;legacy 不写新字段。 -- [x] 复核端:仅管理员技术详情展示模式、应用状态、X/Y 平移和 reason code;普通用户不显示坐标框架诊断;不输出原始正文或完整坐标。 -- [x] 四语言:zh-CN、zh-TW、en、th 均补齐 `coordinateModel` 与管理端配置文案。 -- [x] Header 闭环:订单头字段读取消费 matcher 已选同一 `coordinate_transform`,订单号/日期/币种不再独立使用旧绝对框。 -- [x] 自动化证据:后端相关测试 123 passed;复核投影测试 3 passed;前端 ReviewPanel 5 passed;`npm run build` passed。 -- [x] 范围 Review:未新增数据库表、依赖、Dify 配置或用户端动作;legacy Profile 和其他模板默认路径保持不变。 -- [x] 下一阶段准入:阶段 3 合规 Review 通过,可进入现版 FOX MX Profile 61 受控数据校准。 - -## Phase 4 Review Record - -- [x] 数据基线复核:Profile 61 当前 `definition_json` 与历史 revision 51 逐项一致;附件 `4210007483.pdf` 的表头、订单号标签、订单号值框与现版坐标一致,未发现需要恢复的坐标。 -- [x] 订单号根因:PDFium 原生字符将 `ORDER NO.:` 嵌在整行文本中;旧的锚点匹配将整行作为 `exact` 比较对象,导致锚点无法命中,根因不是 Profile 坐标偏移。 -- [x] 最小修复:matcher 在视觉行内定位锚点子串并使用锚点自身 bbox;未改变 Profile 61 的定义、字段/表格坐标、版本号或其他 Profile 数据。 -- [x] 真实回归:Layout 124 为 `unique_match`(0.985938),Layout 346 为同 Profile `unique_match`(0.889008),Layout 344 为 `evidence_insufficient` 并进入 Review;禁止证据不足时高分自动命中。 -- [x] 订单头取值:Layout 124 确定性读出 `customer_po_number=4210007483`,状态 `confirmed`,来源 `pdf_coordinate`;日期、币种、目的地等绑定字段均通过。 -- [x] 范围与数据隔离:未新建 Profile 版本、未更新 Profile 61 数据、未修改其他 Profile、未修改 Dify 配置;数据库写入范围为零。 -- [x] 下一阶段准入:后端 matcher、订单头/订单行相关回归及前端构建完成后,进入最终阶段验收报告。 - -## Final Phase Acceptance Report - -| 阶段 | 验收结果 | 证据 | -| --- | --- | --- | -| 4A 基线核验 | 通过 | Profile 61 当前定义与 revision 51 一致;PDF 实测坐标未支持坐标回写 | -| 4B matcher 修复 | 通过 | `tests/test_shipping_order_profile_matcher.py`:25 passed;行内 `ORDER NO.:` 锚点可定位自身字符框 | -| 4C 影响 Review | 通过 | Layout 124/346 唯一匹配;Layout 344 `evidence_insufficient`;订单号 `4210007483` confirmed | -| 4D 数据边界 | 通过 | version=1 保持不变;未新建版本、未修改其他 Profile、未写入 Profile 61 数据、未修改 Dify | -| 5 全链路验收 | 通过 | 后端 124 passed;ReviewPanel 5 passed;前端 `npm run build` 通过;`git diff --check` 通过 | - -结论:该阶段工作满足“原 PDF 不可变、Schema 唯一契约、证据不足进入 Review、无坐标变体、其他模板隔离”的要求。订单号识别问题由行内锚点匹配修复解决,不通过修改现版 Profile 坐标规避。 diff --git a/docs/superpowers/plans/2026-08-25-delayed-notice-number-and-inventory-reload.md b/docs/superpowers/plans/2026-08-25-delayed-notice-number-and-inventory-reload.md deleted file mode 100644 index bbd3e15f..00000000 --- a/docs/superpowers/plans/2026-08-25-delayed-notice-number-and-inventory-reload.md +++ /dev/null @@ -1,182 +0,0 @@ -# 延后发货通知单号与库存结果重读 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 仅在首次发货 Excel 成功生成时为既有 `ShippingNotice` 分配业务单号,并提供不触发 RPA 的库存结果重读 Gate 动作。 - -**Architecture:** `ShippingNotice` 继续作为建单、库存和匹配阶段的内部流程载体;新 Notice 在 Excel 前保持 `business_no=None`。首次 Excel Artifact 生成时,同一事务内锁定明细归属、生成 Artifact 并为该 Notice 分配编号。库存重读复用既有快照查询、身份校验、挂接和库存加载函数,不写 RPA trigger。 - -**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、pytest、Vue 3、TypeScript、Vitest。 - -## Global Constraints - -- 不新增发货通知单实体、平行表或第二套编号体系。 -- 一个 Notice 可通过既有 Reservation/Artifact 明细关联覆盖多条订单明细;有效 Reservation 不得重复归属其他 Notice。 -- 新 Notice 仅在首个 Excel 成功生成的事务中分配 `business_no`;历史数据兼容读取不变。 -- `reload_inventory_result` 不得调用 `retry_rpa`、写 trigger 或新建 RPA Attempt。 -- 新增前端文案同步 zh-CN、zh-TW、en、th 四语言;后端业务错误遵循 `AppError` envelope。 -- 保留并避开工作区与本需求无关的未提交改动。 - ---- - -### Task 1: 延后 Notice 编号至首个 Excel 生成 - -**Files:** -- Modify: `backend/app/services/shipping_notice/customer_identity_gate.py` -- Modify: `backend/app/services/shipping_notice/export.py` -- Modify: `backend/app/services/shipping_notice/business_numbering_service.py` -- Modify: `backend/tests/test_shipping_customer_identity_gate.py` -- Modify: `backend/tests/test_shipping_excel_template.py` - -**Interfaces:** -- Consumes: `confirm_task_customer(task, customer_id, actor_id)`、`generate_shipment_excel(task)`。 -- Produces: 客户确认后 `task.business_no is None`;首个成功 Artifact 创建后 `task.business_no` 非空且可由既有货代接口使用。 - -- [ ] **Step 1: 写入失败测试** - -```python -def test_confirm_customer_does_not_assign_business_number(app): - with app.app_context(): - task, customer, user = _seed_task() - confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) - assert confirmed.customer_id == customer.id - assert confirmed.business_no is None - - -def test_first_export_assigns_notice_business_number(app, tmp_path): - with app.app_context(): - task = _seed_exportable_task_without_business_number(tmp_path) - artifact = generate_shipment_excel(task) - assert task.business_no is not None - assert artifact.task_id == task.id -``` - -- [ ] **Step 2: 验证失败原因正确** - -Run: `cd backend; pytest tests/test_shipping_customer_identity_gate.py::test_confirm_customer_does_not_assign_business_number tests/test_shipping_excel_template.py::test_first_export_assigns_notice_business_number -q` - -Expected: FAIL,因为客户确认路径仍分配编号,或导出路径未分配编号。 - -- [ ] **Step 3: 最小实现** - -```python -# customer_identity_gate.py -# 仅写入客户确认事实;不得调用 assign_notice_business_number。 - -# export.py,在首个 Artifact 持久化的同一事务中: -if not task.business_no: - assign_notice_business_number(task) -``` - -保留已有 `assert_notice_has_no_export_artifact` 约束,确保同一 Notice 的首个 Artifact 是唯一编号触发点;分批导出必须由既有波次服务创建新 Notice,禁止在同一 Notice 重生成第二个有效 Artifact。 - -- [ ] **Step 4: 验证通过** - -Run: `cd backend; pytest tests/test_shipping_customer_identity_gate.py tests/test_shipping_business_numbering.py tests/test_shipping_excel_template.py -q` - -Expected: PASS。 - -### Task 2: 增加无 RPA 的库存结果重读 Gate 动作 - -**Files:** -- Modify: `backend/app/services/shipping_notice/process_gate_contract.py` -- Modify: `backend/app/services/shipping_notice/process_gate_executor.py` -- Modify: `backend/app/services/shipping_notice/process_gate_projection.py` -- Modify: `backend/app/services/shipping_notice/error_explainability_contract.py` -- Test: `backend/tests/test_shipping_process_gate_contract.py` -- Test: `backend/tests/test_shipping_process_gate_retry_cap.py` - -**Interfaces:** -- Consumes: `reload_inventory_result`(`inventory_preparation` Gate 的用户动作)。 -- Produces: 命中有效快照时挂接并加载库存;无快照时返回 `blocked_retryable`,不写 RPA trigger/Attempt。 - -- [ ] **Step 1: 写入失败测试** - -```python -def test_inventory_preparation_allows_reload_without_rpa_trigger(): - assert action_belongs_to_gate( - gate_code='inventory_preparation', action_code='reload_inventory_result', - ) is True - - -def test_reload_inventory_result_reuses_snapshot_without_new_rpa_attempt(app, monkeypatch): - task, execution, snapshot = _seed_timeout_task_with_matching_snapshot() - result = _dispatch_gate_action(execution, 'reload_inventory_result') - assert result['outcome'] == 'passed' - assert task.inventory_snapshot_id == snapshot.id - assert _rpa_attempt_count(task) == 0 -``` - -- [ ] **Step 2: 验证失败原因正确** - -Run: `cd backend; pytest tests/test_shipping_process_gate_contract.py -q` - -Expected: FAIL,因为 `reload_inventory_result` 未注册为 Gate 动作。 - -- [ ] **Step 3: 最小实现** - -```python -def _handle_reload_inventory_result(*, execution, gate, payload): - # 使用 _try_reuse_inventory_snapshot 的查询、身份校验与库存加载行为; - # 不设置 mode='retry_rpa',不调用 ensure_inventory_via_rpa。 - response = ensure_inventory({**_task_payload(execution, payload), 'mode': 'auto'}) - return _tool_outcome(action_code='reload_inventory_result', response=response, ...) -``` - -当 `inventory_preparation` 的原因是 RPA 超时/耗尽时,投影将 `reload_inventory_result` 作为主动作;`retry_inventory_preparation` 作为明确的“重新获取库存(重新运行 RPA)”替代动作。 - -- [ ] **Step 4: 验证通过** - -Run: `cd backend; pytest tests/test_shipping_process_gate_contract.py tests/test_shipping_process_gate_retry_cap.py tests/test_shipping_notice_inventory_rpa_workflow.py -q` - -Expected: PASS。 - -### Task 3: 工作台文案、投影与回归验证 - -**Files:** -- Modify: `frontend/src/locales/zh-CN/workspace.json` -- Modify: `frontend/src/locales/zh-TW/workspace.json` -- Modify: `frontend/src/locales/en/workspace.json` -- Modify: `frontend/src/locales/th/workspace.json` -- Modify: `frontend/src/features/shipping-progress/actionPresentation.ts` -- Modify: `frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts` -- Modify: `docs/features/shipping-notice/technical.md` -- Modify: `docs/funclist.md` - -**Interfaces:** -- Consumes: 后端下发的 `reload_inventory_result` 和 Artifact 成功后才出现的 Notice `business_no`。 -- Produces: 主按钮显示“重新读取库存结果”;备用按钮明确为“重新获取库存(重新运行 RPA)”;Excel 前不展示单号。 - -- [ ] **Step 1: 写入失败测试** - -```ts -it('renders reload result as the timeout primary action', async () => { - const wrapper = mount(ReviewCurrentProcessingCard, { - props: { primaryAction: { code: 'reload_inventory_result' } }, - global: { plugins: [i18n] }, - }); - expect(wrapper.text()).toContain('重新读取库存结果'); -}); -``` - -- [ ] **Step 2: 验证失败原因正确** - -Run: `cd frontend; npm run test -- ReviewCurrentProcessingCard.spec.ts` - -Expected: FAIL,因为该动作尚无前端展示映射或翻译。 - -- [ ] **Step 3: 最小实现** - -新增四语言 label,复用动作展示注册表;仅更改此动作及现有 RPA 重试动作的用户可见标签。更新技术文档与功能清单的单号时机、明细归属和库存重读说明。 - -- [ ] **Step 4: 验证通过** - -Run: `cd frontend; npm run test -- ReviewCurrentProcessingCard.spec.ts; npm run build` - -Expected: PASS。 - -## Plan Self-Review - -- 覆盖规格:Task 1 覆盖延后编号;Task 2 覆盖无 RPA 快照读取与超时主动作;Task 3 覆盖 UI、四语言与文档。 -- 未新增实体、编号表或新的 RPA 流程;复用现有 Notice、Artifact、Reservation、快照和 Gate 机制。 -- 计划未采用未定义的跨域服务;实际代码以现有 `ensure_inventory(mode='auto')` 作为库存快照复用入口。 diff --git a/docs/superpowers/plans/2026-08-25-reservation-vendor-comments-anchor.md b/docs/superpowers/plans/2026-08-25-reservation-vendor-comments-anchor.md deleted file mode 100644 index dbed539b..00000000 --- a/docs/superpowers/plans/2026-08-25-reservation-vendor-comments-anchor.md +++ /dev/null @@ -1,124 +0,0 @@ -# Reservation Vendor Comments Anchor Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** 已标注 Reservation ID 专区的订单模板,跨页在 `Vendor Comments` 与首次 `Terms and Condition(s)` 之间确定性读取 Reservation,而不依赖固定页码或坐标。 - -**Architecture:** `reservation_id_region` 继续作为该能力的显式启用开关,保留原几何数据以兼容历史草稿/画布,但运行时不再消费其 `page_no/region`。运行时为已启用模板补齐全部 PDF 页的坐标证据,以视觉阅读顺序定位起止锚点,截取边界内文本,再复用现有 Reservation 候选解析、行号归属和冲突 Review 契约。 - -**Tech Stack:** Flask、Python、PDF/OCR 坐标证据、pytest。 - -## Global Constraints - -- 只对包含 `definition.reservation_id_region` 的已选中模板启用;未标注模板不得全文扫描或改变结果。 -- 起点为首次 `Vendor Comments`;终点为其后首次 `Terms and Condition` 或 `Terms and Conditions`,匹配忽略大小写、冒号和复数差异。 -- 区块允许跨页;不存在起点、终点或二者顺序异常时不猜值,稳定进入 Review。 -- Reservation 仍仅接受带 `Reservation` 标签的 5 位或 10 位纯数字;行号、冲突和越界处理复用 `reservation_region.py`。 -- 原 PDF 不可变;页坐标只通过 `ensure_on_demand_coordinate_evidence(..., page_nos=None)` 取得;不新增依赖、表结构或 Dify 改动。 - ---- - -### Task 1: Vendor Comments 区块提取契约 - -**Files:** -- Modify: `backend/app/services/shipping_notice/reservation_region.py` -- Test: `backend/tests/test_shipping_notice_reservation_id.py` - -**Interfaces:** -- Produces `extract_reservation_from_vendor_comments_pages(pages: list[tuple[int, list[dict[str, Any]]]]) -> tuple[list[dict[str, object]], str | None]`。 -- `str | None` 是 `None`、`vendor_comments_anchor_missing` 或 `terms_and_conditions_anchor_missing`;调用方据此决定 Review。 - -- [ ] **Step 1: Write failing tests** - -```python -def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading(): - candidates, reason = extract_reservation_from_vendor_comments_pages([ - (1, _glyph_lines('Vendor Comments:', 'Reservation#33008')), - (2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')), - ]) - assert reason is None - assert [item['value'] for item in candidates] == ['33008', '3000098851'] -``` - -- [ ] **Step 2: Verify RED** - -Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py -k vendor_comments` - -Expected: FAIL because the extraction function is not defined. - -- [ ] **Step 3: Implement minimal extractor** - -Implement a pure helper in `reservation_region.py` that renders each page through existing `visual_text_lines`, scans all page lines in page-number order, begins after the first normalized `Vendor Comments` heading, ends before the first later normalized `Terms and Condition(s)` heading, and passes only joined window lines to `extract_reservation_from_region_text`. Do not read coordinates, assets, or database state in this helper. - -- [ ] **Step 4: Verify GREEN** - -Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py` - -Expected: PASS, including existing ID format, line mapping and conflict tests. - -### Task 2: Production routing and fail-closed boundary result - -**Files:** -- Modify: `backend/app/services/shipping_notice/order_extraction_workflow.py` -- Test: `backend/tests/test_order_extraction_pdf_po_split.py` - -**Interfaces:** -- Replaces `_reservation_region_candidates(raw_profile, layout)` fixed-page geometry reading with a result containing `candidates` and optional `reason`. -- Existing `_build_approved_profile_order_result(..., reservation_region_candidates=...)` remains the single application point for values. - -- [ ] **Step 1: Write failing integration tests** - -```python -def test_enabled_reservation_region_reads_vendor_comments_across_pages(): - result = _reservation_region_candidates(raw_profile=_profile_with_region(), layout=_two_page_layout()) - assert result['reason'] is None - assert result['candidates'][0]['value'] == '33008' - -def test_profile_without_reservation_region_does_not_scan_vendor_comments(): - result = _reservation_region_candidates(raw_profile={'definition': {}}, layout=_two_page_layout()) - assert result == {'candidates': [], 'reason': None} -``` - -- [ ] **Step 2: Verify RED** - -Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_order_extraction_pdf_po_split.py -k reservation_region` - -Expected: FAIL because the fixed-page reader returns a list and does not expose dynamic cross-page candidates. - -- [ ] **Step 3: Implement minimal routing change** - -For a Profile with `reservation_id_region`, call `ensure_on_demand_coordinate_evidence(document, layout, page_nos=None)` before matching/reading. In `_reservation_region_candidates`, order available `page_glyphs` numerically, call Task 1 helper, and return `{'candidates': ..., 'reason': ...}`. If a boundary reason exists, preserve it as `reservation_region_status='needs_review'` and `reservation_region_review_reasons=[reason]`; do not write Reservation fields and do not allow STP. No special behavior for profiles without the key. - -- [ ] **Step 4: Verify GREEN** - -Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_order_extraction_pdf_po_split.py tests/test_shipping_notice_reservation_id.py` - -Expected: PASS; dynamic scan works across page breaks, first Terms heading terminates the window, missing boundaries become Review, and unmarked templates do not scan. - -### Task 3: Documentation and final verification - -**Files:** -- Modify: `docs/features/shipping-notice/technical.md` -- Modify: `docs/funclist.md` - -- [ ] **Step 1: Document the enabled-template behavior** - -Add one concise technical section: Reservation ID 专区 is an opt-in semantic parser; it scans from `Vendor Comments` to the first `Terms and Condition(s)` in reading order across pages; geometry remains annotation evidence only; missing/ambiguous boundaries and value conflicts require Review. State that unmarked templates are unchanged. - -- [ ] **Step 2: Update feature list** - -Add the Reservation 专区 dynamic-anchor behavior to the existing shipping order-template entry without creating a parallel feature. - -- [ ] **Step 3: Run verification** - -Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py tests/test_order_extraction_pdf_po_split.py` - -Run: `git diff --check` - -Expected: all targeted tests PASS and no whitespace errors. If frontend files are unchanged, no frontend build is required. - -## Self-Review - -- The plan covers opt-in gating, cross-page reading, first-stop semantics, strict Reservation validation, Review failure paths, unmarked-template isolation, tests and documentation. -- It creates no database migration, dependency, Dify configuration or profile data rewrite. -- Helper and routing interfaces have explicit names and return types; all listed behavior is testable. diff --git a/docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md b/docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md new file mode 100644 index 00000000..59d27db8 --- /dev/null +++ b/docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md @@ -0,0 +1,549 @@ +# 下线旧 CheckPoint 状态机 — 实现计划(A · 批量 batched execution 读取) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 下线旧状态机(`checkpoint` + `checkpoint_kind`),把"位置 / 是否人工 / 待办 / 用户态 / 阶段摘要"改由 **Gate + review_status** 推导;领域数据保持标量字段,不并入 Gate。 + +**Architecture:** **Gate = 唯一事实源**。位置 = `exec.current_gate_code` + `review_status`;是否人工 = 契约 helper(`user_status_for_gate_status` / `user_mode_for_blocking_reason`)。粗分类映射放 `process_gate_contract`(它已管 gate→user 状态)。**批量路径用一次 `executions WHERE task_id IN (...)` 取回 position**,避免 N+1;不引入新模块、不新增列。领域数据(match_status 等)不动。 + +**Tech Stack:** Python 3.12 + Flask + SQLAlchemy 2.0(后端,无前端改动)。 + +## Global Constraints + +- 分支 `hugo-shipping-notice`;**不自动 push**;每任务本地 commit。 +- 后端测试:`PYTHONPATH=D:\Workspace\HxProjects\hxops\backend`,解释器 `backend\.venv\Scripts\python.exe`,`python -m pytest tests/.py -v`。测试慢,只跑受影响 file。 +- **不改** Gate 模型 / 领域数据字段 / 阶段能力集(`STAGE_CAPABILITY_DEFINITIONS` 在别处实现)。 +- 粗分类映射**只加在** `process_gate_contract.py`(与既有 `user_status_for_gate_status`/`user_mode_for_blocking_reason` 同处)。 +- 复用既有投影:`_process_gate_user_summary_for_task(task)`(单任务 gate 摘要)、`execution.current_gate_code`、`user_status`(`shipping_processing_projection` 已暴露)。 + +--- + +### Task 1: 契约层粗分类映射(`process_gate_contract.py`) + +**Files:** +- Modify: `backend/app/services/shipping_notice/process_gate_contract.py` +- Test: `backend/tests/test_gate_derivation.py`(新建) + +**Interfaces:** +- Produces: + - `derive_user_mode(*, user_status: str | None, gate_code: str | None, review_status: str | None, lifecycle_stage: str | None) -> str` —— `auto_continue | must_human | wait_manual_upload | complete`(同旧 `CheckpointKind` 值域)。 + - `derive_position(*, gate_code: str | None, review_status: str | None) -> str | None` —— 位置标签。 + - `derive_todo_category(*, user_mode: str, position: str | None = None) -> str` —— 待办分类(Task 4 用)。 + +- [ ] **Step 1: Write the failing test** + +```python +# backend/tests/test_gate_derivation.py +from app.services.shipping_notice.process_gate_contract import derive_user_mode, derive_position, derive_todo_category + + +def test_user_mode_complete_when_rejected(): + assert derive_user_mode(user_status='completed', gate_code=None, review_status='rejected', lifecycle_stage=None) == 'complete' + + +def test_user_mode_wait_upload_handoff(): + assert derive_user_mode(user_status='waiting_human', gate_code='manual_upload_handoff', review_status=None, lifecycle_stage='freight_upload') == 'wait_manual_upload' + + +def test_user_mode_must_human(): + assert derive_user_mode(user_status='waiting_human', gate_code='inventory_matching', review_status=None, lifecycle_stage='fulfillment_prep') == 'must_human' + + +def test_user_mode_auto(): + assert derive_user_mode(user_status='running', gate_code='inventory_preparation', review_status=None, lifecycle_stage='fulfillment_prep') == 'auto_continue' + + +def test_position_review_dispositions(): + assert derive_position(gate_code=None, review_status='rejected') == 'rejected' + assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue' + assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req' + + +def test_position_fulfillment(): + assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending' + assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready' + + +def test_todo_category(): + assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review' + assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception' + assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload' + assert derive_todo_category(user_mode='complete') == 'done' + assert derive_todo_category(user_mode='auto_continue') == 'in_progress' +``` + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL(函数不存在)。 + +- [ ] **Step 3: Implement** + +`process_gate_contract.py` 末尾追加: +```python +def derive_user_mode(*, user_status, gate_code, review_status, lifecycle_stage): + """粗分类(auto_continue/must_human/wait_manual_upload/complete),替代旧 checkpoint_kind。""" + if str(review_status or '').strip() == 'rejected': + return 'complete' + if str(user_status or '').strip() == 'completed': + return 'complete' + code = str(gate_code or '').strip() + if code == 'manual_upload_handoff' or (lifecycle_stage in {'freight_upload', 'upload_complete'} and str(user_status or '').strip() == 'waiting_human'): + return 'wait_manual_upload' + if str(user_status or '').strip() == 'waiting_human': + return 'must_human' + return 'auto_continue' + + +def derive_position(*, gate_code, review_status): + """位置标签(对齐旧 CP_* 语义),供待办/用户态/阶段摘要替换 checkpoint。""" + rs = str(review_status or '').strip() + if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}: + return rs + mapping = { + 'order_field_extraction': 'parse_review', + 'customer_resolution': 'customer_review', + 'reservation_validation': 'rsv_req', + 'inventory_preparation': 'inventory_pending', + 'inventory_matching': 'ready_to_match', + 'excel_readiness': 'ready_to_export', + 'artifact_generation': 'export_ready', + 'freight_upload_rpa': 'upload_failed', + 'manual_upload_handoff': 'waiting_upload', + } + return mapping.get(str(gate_code or '').strip()) + + +def derive_todo_category(*, user_mode, position=None): + if user_mode == 'wait_manual_upload': + return 'manual_upload' + if user_mode == 'complete': + return 'done' + if user_mode == 'must_human': + return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception' + return 'in_progress' +``` + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/process_gate_contract.py backend/tests/test_gate_derivation.py` +`git commit -m "feat(shipping-notice): gate-based position/user-mode/todo derivation"` + +--- + +### Task 2: 批量便宜读取(batched executions) + +**Files:** +- Modify: `backend/app/services/shipping_notice/query_service.py` +- Test: `backend/tests/test_gate_derivation.py`(追加) + +**Interfaces:** +- Produces: `fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]` —— 一次查询返回 `{task_id: {'current_gate_code', 'status'}}`,供批量待办/列表映射 position。 + +- [ ] **Step 1: Write the failing test** + +```python +# 追加到 test_gate_derivation.py +def test_fetch_gate_positions_batched(monkeypatch): + from app.services.shipping_notice.query_service import fetch_gate_positions + # 用 db facade 桩返回两行 execution + class FakeRow: + task_id = 1 + current_gate_code = 'inventory_preparation' + status = 'active' + monkeypatch.setattr( + 'app.services.shipping_notice.query_service.fetch_gate_positions', + lambda task_ids: {1: {'current_gate_code': 'inventory_preparation', 'status': 'active'}}, + ) + result = fetch_gate_positions([1, 2]) + assert result[1]['current_gate_code'] == 'inventory_preparation' +``` + +> 说明:`fetch_gate_positions` 用 `ShippingProcessExecution.query.filter(task_id.in_(ids)).all()` 一次取回;测试以"存在 + 可调用 + 返回形状"为最小驱动,实际 DB 行为交由 Task 4 单测覆盖。 + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL(`fetch_gate_positions` 不存在)。 + +- [ ] **Step 3: Implement** + +`query_service.py`: +```python +def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]: + """一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。""" + from app.models.shipping_process_gate import ShippingProcessExecution + ids = [int(i) for i in task_ids if i is not None] + if not ids: + return {} + rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all() + return { + int(getattr(r, 'task_id', 0)): { + 'current_gate_code': getattr(r, 'current_gate_code', None), + 'status': getattr(r, 'status', None), + } + for r in rows if getattr(r, 'task_id', None) is not None + } +``` + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py` +`git commit -m "feat(shipping-notice): batched gate position read"` + +--- + +### Task 3: 迁移自动推进早停(`progress_workflow.py:412-431`) + +**Files:** +- Modify: `backend/app/services/shipping_notice/progress_workflow.py:412-431` +- Test: `backend/tests/test_gate_derivation.py`(追加) + +**Interfaces:** +- Consumes: `derive_user_mode`(Task 1)、`_process_gate_user_summary_for_task`。 +- Produces: `_entry_user_mode(task) -> str`(内部小函数)。 + +- [ ] **Step 1: Write the failing test** + +```python +# 追加 +def test_early_stop_uses_derive_user_mode(monkeypatch): + from app.services.shipping_notice import progress_workflow as pw + class FakeTask: + task_no = 'SN-1' + review_status = None + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow._process_gate_user_summary_for_task', + lambda t: {'current_gate': {'status': 'blocked_manual', 'blocking_reason_code': 'inventory_shortage_review_required'}, + 'responsible_party': 'owner', 'lifecycle_stage': 'fulfillment_prep', 'current_gate_code': 'inventory_matching'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_contract.derive_user_mode', + lambda **k: 'must_human', + ) + assert pw._entry_user_mode(FakeTask()) == 'must_human' +``` + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL(`_entry_user_mode` 不存在)。 + +- [ ] **Step 3: Implement** + +`progress_workflow.py`: +```python +def _entry_user_mode(task) -> str: + """自动推进入口早停:从 Gate 推导用户处置模式,替代旧 checkpoint_kind。""" + from app.services.shipping_notice.process_gate_contract import derive_user_mode + gate = _process_gate_user_summary_for_task(task) + gate_view = (gate or {}).get('current_blocking_gate') or (gate or {}).get('current_gate') or {} + status = str(gate_view.get('status') or '').strip().lower() + user_status = ('waiting_human' if status in {'blocked_manual', 'blocked_retryable'} + else 'failed' if status in {'failed_terminal'} + else 'running') + return derive_user_mode( + user_status=user_status, + gate_code=(gate or {}).get('current_gate_code') or gate_view.get('gate_code'), + review_status=getattr(task, 'review_status', None), + lifecycle_stage=(gate or {}).get('lifecycle_stage'), + ) +``` +把 `:415-431` 的 `checkpoint_kind == CheckpointKind.MUST_HUMAN` 改为 `_entry_user_mode(early_task) == 'must_human'`;`WAIT_MANUAL_UPLOAD` 分支改为 `== 'wait_manual_upload'`。 + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py tests/test_shipping_* -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/progress_workflow.py backend/tests/test_gate_derivation.py` +`git commit -m "refactor(shipping-notice): early-stop via gate user mode"` + +--- + +### Task 4: 迁移待办分类(`query_service`) + +**Files:** +- Modify: `backend/app/services/shipping_notice/query_service.py` +- Test: `backend/tests/test_gate_derivation.py`(追加) + +**Interfaces:** +- Consumes: `derive_todo_category`(Task 1)、`fetch_gate_positions`(Task 2)。 +- Produces: 单任务/批量待办改读 gate 位置。 + +- [ ] **Step 1: Write the failing test** + +```python +# 追加 +def test_todo_category_from_gate_positions(monkeypatch): + from app.services.shipping_notice import query_service as qs + # 批量:两任务,一 must_human(review),一 auto(in_progress) + monkeypatch.setattr( + 'app.services.shipping_notice.query_service.fetch_gate_positions', + lambda ids: {1: {'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'}, + 2: {'current_gate_code': 'inventory_preparation', 'status': 'active'}}, + ) + # 单任务用户态映射 + from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position + assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review' + assert derive_todo_category(user_mode='auto_continue', position='inventory_pending') == 'in_progress' +``` + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL。 + +- [ ] **Step 3: Implement** + +`query_service.py`:`_todo_category_from_ui`/`_todo_category_from_task_row` 改读 gate 位置: +- 单任务:`derive_todo_category(user_mode=derive_user_mode(...), position=derive_position(...))`(用 `_process_gate_user_summary_for_task`)。 +- 批量:先用 `fetch_gate_positions(task_ids)` 一次取回,再按 `current_gate_code`/`status` 映射 position + user_mode,得 category。 + +```python +def _todo_category_from_gate(gate_pos: dict, review_status): + from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position + user_mode = derive_user_mode( + user_status=('waiting_human' if gate_pos.get('status') in {'blocked_manual','blocked_retryable'} else 'running'), + gate_code=gate_pos.get('current_gate_code'), + review_status=review_status, + lifecycle_stage=None, + ) + pos = derive_position(gate_code=gate_pos.get('current_gate_code'), review_status=review_status) + return derive_todo_category(user_mode=user_mode, position=pos) +``` + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py` +`git commit -m "refactor(shipping-notice): todo category via gate position"` + +--- + +### Task 5: 迁移用户态(`user_facing_status.user_facing_task_stage:95-98`) + +**Files:** +- Modify: `backend/app/services/shipping_notice/user_facing_status.py:95-98` +- Test: `backend/tests/test_gate_derivation.py`(追加) + +**Interfaces:** +- Consumes: `derive_position`(Task 1)、`_process_gate_user_summary_for_task`。 +- Produces: 无新函数;`_CHECKPOINT_LABELS` 键改为 position。 + +- [ ] **Step 1: Write the failing test** + +```python +# 追加 +def test_user_facing_stage_uses_position(monkeypatch): + from app.services.shipping_notice import user_facing_status as ufs + class FakeTask: + step_payload_json = {} + pending_human_reason = None + lifecycle_status = 'active' + review_status = None + monkeypatch.setattr( + 'app.services.shipping_notice.user_facing_status._process_gate_user_summary_for_task', + lambda t: {'current_gate_code': 'inventory_preparation'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_contract.derive_position', + lambda **k: 'inventory_pending', + ) + assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存' +``` + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL。 + +- [ ] **Step 3: Implement** + +`user_facing_status.py`:把 `_CHECKPOINT_LABELS` 键改为 position(`inventory_pending`/`export_ready`/`waiting_upload`/`upload_failed`/`rejected`/`parse_review`/`rsv_req`/`customer_review`/`quality_issue`),`user_facing_task_stage` 回退: +```python +from app.services.shipping_notice.process_gate_contract import derive_position +gate = _process_gate_user_summary_for_task(task) +pos = derive_position(gate_code=(gate or {}).get('current_gate_code'), review_status=getattr(task, 'review_status', None)) +if pos and pos in _CHECKPOINT_LABELS: + return _CHECKPOINT_LABELS[pos] +``` + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/user_facing_status.py backend/tests/test_gate_derivation.py` +`git commit -m "refactor(shipping-notice): user stage via gate position"` + +--- + +### Task 6: 迁移阶段上下文/摘要(`ui_state`) + +**Files:** +- Modify: `backend/app/services/shipping_notice/ui_state.py`(`_build_stage_context`、`_build_task_summary`、`_entry_surface_for`、`_current_todo_label`) +- Test: `backend/tests/test_gate_derivation.py`(追加) + +**Interfaces:** +- Consumes: `derive_position`/`derive_user_mode`(Task 1)。 +- Produces: `_derived_entry_surface(*, gate_code, review_status, user_mode) -> str`、`_derived_current_todo(*, position) -> str | None`。 + +- [ ] **Step 1: Write the failing test** + +```python +# 追加 +def test_derived_entry_surface_review(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + assert _derived_entry_surface(gate_code='order_field_extraction', review_status='parse_review', user_mode='must_human') == 'review_workbench' + + +def test_derived_entry_surface_task(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + assert _derived_entry_surface(gate_code='artifact_generation', review_status=None, user_mode='wait_manual_upload') == 'task_workbench' +``` + +- [ ] **Step 2: Run to verify it fails** + +`python -m pytest tests/test_gate_derivation.py -v` +Expected: FAIL。 + +- [ ] **Step 3: Implement** + +`ui_state.py`: +```python +def _derived_entry_surface(*, gate_code, review_status, user_mode): + rs = str(review_status or '').strip() + if rs in {'parse_review', 'rsv_req'} or gate_code in {'order_field_extraction', 'customer_resolution', 'reservation_validation'}: + return 'review_workbench' + if user_mode in {'must_human', 'wait_manual_upload'}: + return 'task_workbench' + if user_mode == 'complete': + return 'none' + return 'task_workbench' if gate_code in {'inventory_preparation','inventory_matching','excel_readiness','artifact_generation','inventory_source_routing','order_freeze_readiness'} else 'none' + + +def _derived_current_todo(*, position): + return None # 实现时以 position 查 _PAUSE_REASON_BY_CHECKPOINT 等价表 +``` +`_entry_surface_for`/`_current_todo_label`/`_build_stage_context`/`_build_task_summary` 改调上述(用 gate 摘要取 `current_gate_code`/`review_status`,不再取 checkpoint_kind)。 + +- [ ] **Step 4: Run to verify it passes** + +`python -m pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v`。Expected: PASS。 + +- [ ] **Step 5: Commit** + +`git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_gate_derivation.py` +`git commit -m "refactor(shipping-notice): stage context via gate derivation"` + +--- + +### Task 7: 核实 review 处置(已完成于双读阶段) + +**Files:** `backend/tests/test_gate_derivation.py` + +- [x] `rejected` / `quality_issue` → `derive_position` 单测 +- [x] 聊天侧 Gate-first(`shippingUiPosition` 等) + +> 核实点不得阻塞 Task 8–10;本任务仅作验收锚点。 + +--- + +### Task 8: SQL todo_category 切 Gate(硬删前置) + +**Files:** +- Modify: `backend/app/services/shipping_notice/query_service.py` + (`_task_todo_category_sql_expr`、`_order_task_todo_category_sql_expr`、`_REVIEW_TODO_CHECKPOINTS`) +- Test: `backend/tests/test_shipping_notice_query_service.py`、`backend/tests/test_gate_derivation.py` + +**规则:** +- CASE **优先** `ShippingProcessExecution.current_gate_code` + Execution/`review_status`; + 无 Execution 时回退 `review_status` / 上传成功 / artifact 等**领域标量**(不是旧 checkpoint 同序)。 +- `_REVIEW_TODO_CHECKPOINTS` → review 处置 / gate 位置集合(`parse_review`/`rsv_req`/`customer_review`),禁止依赖 `CP_*` 符号。 +- ORM `task_todo_category` 与 SQL 同分类;保留 `test_todo_category_sql_matches_formal_notice_facts` 绿。 + +- [ ] **Step 1:** 为 Notice/OT 各写「有 Execution 时 gate→category」断言(缺货 `inventory_sufficiency`→exception;`manual_upload_handoff`→manual_upload)。 +- [ ] **Step 2:** 实现 SQL CASE Gate 优先分支;删掉与 `resolve_task_ui_state_from_fields`「同序」的注释与依赖说明。 +- [ ] **Step 3:** `pytest tests/test_gate_derivation.py tests/test_shipping_notice_query_service.py -k todo_category -v` +- [ ] **Step 4:** 不自动 commit(仓库约定:仅用户明确要求时提交)。 + +--- + +### Task 9: 下线 state_machine CP 裁决 + 切断剩余调用 + +**Files:** +- Modify: `backend/app/services/shipping_notice/state_machine.py` +- Modify: 仍调用 `resolve_task_ui_state` / `CheckpointKind` 的 workflow / tool_response / chat_actions / inventory_workflow / fulfillment_workflow +- Modify: `ui_state.py` / `progress_workflow.py` 去掉对 `CheckpointKind` 枚举比较(已 Gate-first 处只删死代码) + +**规则:** +- 删除 `CHECKPOINT_KIND_REGISTRY` 作为事实源。 +- `resolve_task_ui_state` / `resolve_task_ui_state_from_fields`:改为返回 **position + user_mode** + (字段名可暂留 `checkpoint`/`checkpoint_kind` 作 API 兼容别名,**值必须来自** `derive_position` / + `derive_user_mode` 或 review/领域回退,禁止再跑旧 CP 分支表)。 +- 或:直接删除两函数,调用方改 `derive_*` + `_process_gate_user_summary_for_task`(优先,若回归面可控)。 + +- [ ] **Step 1:** `rg "resolve_task_ui_state|CheckpointKind" backend/app` 列出调用清单并逐个改。 +- [ ] **Step 2:** 重写或删除 `state_machine` CP 映射;文件头注释改为「已退役 / 仅兼容别名」。 +- [ ] **Step 3:** `pytest tests/test_shipping_notice_state_machine.py tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v` +- [ ] **Step 4:** 不自动 commit。 + +--- + +### Task 10: `CP_*` → 位置标签 / 删除闲置符号 + +**Files:** +- Modify: `backend/app/services/shipping_notice/constants.py` +- Modify: 所有 `from ...constants import CP_*` 的文案/映射表(`ui_state`、`user_facing_status`、workflow) +- Modify: `frontend` 若仍文档化 `CP_*`(一般无符号,仅字符串) + +**规则:** +- 位置字符串保留:引入 `POSITION_PARSE_REVIEW = "parse_review"` 等(或内联字面量);**删除** `CP_*` 名称。 +- 删除闲置:`CP_PARSE_OK`、`CP_TASK_EXISTS`(设计 §3.4)。 +- `RS_*` / `PH_*` 保留;`PH_*` 若曾 `= CP_*` 改为字面量或 `POSITION_*`。 +- `grep -rn "\\bCP_" backend/app frontend/src` → 零命中(测试里描述性字符串除外)。 + +- [ ] **Step 1:** 在 `constants.py` 增加 `POSITION_*`(或决定全内联),迁移引用,删 `CP_*`。 +- [ ] **Step 2:** 文案表键改位置字符串;更新文件头注释。 +- [ ] **Step 3:** 回归 + `pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py tests/test_shipping_notice_query_service.py tests/test_shipping_notice_state_machine.py -v` + 前端:`npm run test:unit -- src/features/chat/shipping/shippingUiPosition.spec.ts src/features/chat/shipping/useChatShippingRefresh.spec.ts` +- [ ] **Step 4:** 更新 `.engramory-memory/shipping-retire-checkpoint-progress.md`;不自动 commit。 + +--- + +### Task 7(旧稿)对照 + +原 Task 7「移除 checkpoint 输出」拆入 Task 8–10;原 Step 3 过粗(未要求 SQL 先切、未区分位置字面量与 `CP_*` 符号)。以 Task 8–10 为准。 + +--- + +## Self-Review + +- **Spec 覆盖**:§8 四阶段 → Task1–6(双读/切消费)/ Task7 核实 / Task8 SQL / Task9 下线裁决 / Task10 清 `CP_*`。§6 廉价读取用 **batched executions(A)**;SQL CASE 为列表廉价路径,必须 Gate 优先。 +- **无新模块**:粗分类映射落 `process_gate_contract`;不创建 `checkpoint_derivation`。 +- **Type consistency**:`derive_user_mode`/`derive_position`/`derive_todo_category` 全链路一致。 +- **字面量 vs 符号**:位置字符串可留;`CP_*` / `CheckpointKind` / 旧 `resolve` 裁决必须删。 +- **提交纪律**:本仓库反馈「禁止自动 commit」优先于计划内每任务 commit 句;仅用户明确要求时提交。 + +--- + +## Execution Handoff + +计划已保存到 `docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md`。 + +**执行方式:1. Subagent-Driven(推荐)** 每任务派全新 subagent,任务间 review;**2. Inline Execution** 本会话 executing-plans。你选哪种?(按约定不自动 push / 不自动 commit。) diff --git a/docs/superpowers/plans/2026-09-01-shipping-wave-write-path-task-source-draft.md b/docs/superpowers/plans/2026-09-01-shipping-wave-write-path-task-source-draft.md new file mode 100644 index 00000000..2a4b5f31 --- /dev/null +++ b/docs/superpowers/plans/2026-09-01-shipping-wave-write-path-task-source-draft.md @@ -0,0 +1,72 @@ +# 波次出单写路径改源到任务级(计划 E 草案) + +> **状态:DRAFT — 供用户审阅,未经 writing-plans 完整流程与用户确认前不得执行。** +> 起源于 2026-09-01 SDD 执行「下游工作面单源投影收敛」的裁决 C 暂留债务与终审建议(详见 +> `.superpowers/sdd/2026-09-01-shipping-downstream-single-projection/progress.md` 终审段)。 + +## Goal + +把「通知准备」波次出单/缺口放行的**写路径**从 Case(`activeCase`/`displayCase`)改源到任务级 +(`ui_state.stage_context.preparation` + task_no 寻址 API),使 `fulfillment_prep` 可从 +`REVIEW_EDITOR_NEEDED_STAGES` 移出,下游工作面(货代上传/通知完成/通知准备)**零** `getReviewCase`/ +`getReviewEvidence` 请求,Prep 面(渲染+写)完整单源。 + +## 债务清单(本计划要还的) + +1. `fulfillment_prep` 暂留 `REVIEW_EDITOR_NEEDED_STAGES`(裁决 C):冷进入需 watch 补拉 Case。 +2. 波次写路径 Case 依赖:`confirmPreparationWave` 需 `activeCase.case_no`+`draft_version`; + `preparationWaveSelectableLines`→`lineFulfillmentFor`→`displayCase.line_fulfillment.lines`; + `formalPreparationLineAllows` 读 Case 的 `line_allowed_actions`/`inventory_allowed_actions`。 +3. `processDetailPoNumber` PO 腿:Case 头优先、投影兜底(摘要 JSDoc 已如实标注)。 +4. 右卡 `:loading` 覆盖全部 12 处 detail re-fetch 窗口(动作按钮短暂隐藏)。 +5. pre-formal 窗口右卡阶段显示中性「—」(原「创建正式订单」推断丢失,产品确认后可恢复)。 +6. spec 断言 `getWorkspaceShippingOrderReviewCase).not.toHaveBeenCalled()` 恒真且与裁决 C 字面冲突 + (vitest 恢复后需改写为真实断言)。 + +## 方案骨架(待 writing-plans 细化) + +### Task 1(后端):`stage_context.preparation` 补齐写路径字段 + +- `draft_version`(或等价任务级并发控制 token,与 Case 的 expected_draft_version 语义对齐)。 +- 行级:`fulfillable`(映射 line_fulfillment 可出库判定)、`allowed_actions`(行级动作门, + 映射 `line_allowed_actions`/`inventory_allowed_actions`)。 +- pytest:字段存在性与语义等价(与 Case 数据源对照);`include_stage_context` 门不受影响。 + +### Task 2(后端):wave/放行 API 支持 task_no 寻址 + +- 新增或扩展端点:按 `task_no` 提交波次/缺口放行,服务端由任务解析归属 Case(或直操作 fulfillment 域), + 并发控制用 Task 1 的任务级版本字段。 +- 兼容:旧 case_no 寻址保留(复核编辑器仍用);pytest 覆盖成功/版本冲突/任务不存在。 + +### Task 3(前端):写路径改读 ui_state + 集合收窄 + +- `preparationWaveSelectableLines`/`confirmPreparationWave`/`confirmReleaseInventoryShortage`/ + `formalPreparationLineAllows` 改读 `stage_context.preparation`(删 displayCase/activeCase 依赖)。 +- `REVIEW_EDITOR_NEEDED_STAGES` 移出 `fulfillment_prep`(收窄到 `['intake_parse','order_review']`), + 更新 watch 注释(裁决 C 债务清偿)。 +- `processDetailPoNumber` 改源为投影优先(PO 腿单源化,摘要 JSDoc 同步更新)。 + +### Task 4(前端):右卡与占位收尾 + +- 右卡 `:loading` 收窄到「detail 尚未在手」(消除动作后 re-fetch 期间按钮闪烁)。 +- pre-formal 阶段信号:投影增加 pre-formal 阶段或标记(产品确认后实施,消除「—」信息损失)。 +- spec:改写 `getReviewCase` 断言为真实语义(下游零 Case 拉取);failed 臂补 `mockRejectedValue` 用例; + 占位补 testid(货代上传/通知完成两段同步)。 + +### Task 5:回归 + 手动核验 + +- 后端 pytest 全量相关文件;前端任务级 build gate(vitest 恢复后跑全部新增 spec)。 +- 手动:冷进入通知准备 → 勾选列即时可用(无 Case 网络请求)→ 波次出单成功/版本冲突路径; + Network 面板下游零 `getReviewCase`/`getReviewEvidence`。 + +## 效能红线 + +- `build_task_ui_state`/`_build_stage_context` 不增加触发频率(新增字段为既有调用内追加)。 +- 下游进入请求计数 ≈3-4 且**零** `getReviewCase`/`getReviewEvidence`(本计划的验收断言)。 +- wave API 新寻址不新增 N+1(服务端单任务解析)。 + +## 前置条件 + +- 用户确认本草案并走 writing-plans 完整流程。 +- 并行会话的 STP/会话处理 WIP 落地后再启动(避免同文件竞争:本计划与并行工作共同触及 + `ShippingOrderReviewView.vue`、`useShippingOrderReview.ts`、`ui_state.py`)。 diff --git a/docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md b/docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md new file mode 100644 index 00000000..df97e38b --- /dev/null +++ b/docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md @@ -0,0 +1,192 @@ +# 货代 Gate 编排对齐 — 匹配后独立 Excel Attempt 实现计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 把履约段(Gate 13–20)统一成「当前 Gate Attempt 只做本门禁职责 → `complete` → 入队下一 Gate Attempt」;拆除匹配 Attempt 内嵌的 `try_auto_chain` Excel/上传副作用,使 `artifact_generation` 成为可观测的独立 Attempt。 + +**Architecture:** 保留既有 P0-3 脊柱:`submit_auto_progress` / `_enqueue_auto_progress_after_gate_pass` → `queue_gate_attempt` → Job Worker → `execute_queued_attempt` → `complete_gate_attempt`。匹配 Handler 只写匹配事实并 `sync`;Excel 仅由 `_handle_regenerate_excel` 在 `artifact_generation` Attempt 内、经 `_task_payload`(`_orchestrator_internal_dispatch=True`)调用 `generate_excel`。事实门禁(sufficiency / excel_readiness / mapping)允许 sync 投影,但 **不得**在 sync 里把「尚未执行的 worker 门禁」标成已完成产物工作。 + +**Tech Stack:** Python 3.12 + Flask + SQLAlchemy 2.0;测试 `backend\.venv\Scripts\python.exe -m pytest`;文档 `docs/features/shipping-notice/process-gate-recovery-contract.md` / `technical.md`。 + +## Global Constraints + +- 分支现状:在现有 shipping 开发分支上改;**不自动 push**;用户未明确要求时不 commit。 +- 后端解释器:`backend\.venv\Scripts\python.exe`;只跑受影响测试文件。 +- **禁止**再引入新的跨 Gate 内嵌工作流;`_orchestrator_internal_dispatch` 仅表示「已在本 Attempt 内直跑本 Gate 的 workflow」,不得用来在匹配 Attempt 里生成 Excel。 +- 配置语义:`SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED` 控制「是否自动入队 artifact Attempt」,**不再**表示「在 match 里直跑 generate」。 +- `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 同理:只控制是否自动入队 freight Attempt,不在 match 内嵌 upload。 +- 同步更新契约/技术文档中与自动串联相关的段落,避免文档继续描述嵌套链。 + +--- + +## 现状审计结论(实施前共识) + +### 正式脊柱(应对齐的好模式) + +```text +submit_auto_progress / complete(passed) + → _enqueue_auto_progress_after_gate_pass + → queue_gate_attempt + enqueue_gate_attempt_job + → Worker claim_and_run_gate_attempt + → execute_queued_attempt → handler(_task_payload + internal) + → complete_gate_attempt → 再入队下一 Gate +``` + +关键落点: + +| 角色 | 文件 | 函数 | +| --- | --- | --- | +| 任务级提交 | `auto_progress_controller.py` | `submit_auto_progress` | +| Attempt 收口续跑 | `process_gate_service.py` | `complete_gate_attempt` → `_enqueue_auto_progress_after_gate_pass` | +| Worker | `process_gate_job_service.py` / `jobs/handlers/shipping_process_gate.py` | `claim_and_run_gate_attempt` | +| 分发 | `process_gate_executor.py` | `execute_queued_attempt` / `_task_payload` | +| 事实投影 | `process_gate_bridge.py` | `sync_fulfillment_gates_from_task` | + +### Gate 13–20 分类(今天) + +| Gate | 好模式? | 今天主路径 | +| ---: | --- | --- | +| 13 preparation | ✅ | **新 Attempt** 跑 `ensure_inventory`;不内嵌 match/excel | +| 14 field_mapping | ⚪ 事实门禁 | 多为 **sync 投影**;恢复路径 `from_field_mapping` **同 Attempt 嵌套 match**(次要债务) | +| 15 matching | ❌ | **新 Attempt** 跑 match,但成功后 **`try_auto_chain` 同 Attempt 内嵌 generate±upload** | +| 16 sufficiency | ⚪ 事实/人工 | sync / recheck;短缺则 **人工** | +| 17 excel_readiness | ✅ 事实门禁 | sync / recheck **不生成** Excel | +| 18 artifact | ❌ 契约有、开心路径绕过 | 自动成功靠 match 内嵌;手动「重新生成」才走 `_handle_regenerate_excel` **新 Attempt** | +| 19 freight RPA | 部分 | 有独立 Handler;`AUTO_UPLOAD` 时可被 chain 嵌套 | +| 20 manual handoff | ✅ | **owner 人工**;auto enqueue 跳过 | + +### 目标开心路径 + +```text +Attempt(prep) → pass → enqueue +Attempt(match) → 仅匹配 + sync 事实 → pass → enqueue +[可选 Attempt/sync excel_readiness] +Attempt(artifact) → generate_excel(_task_payload) → pass → enqueue +Attempt(freight) 或 停在 manual_upload(人工) +``` + +--- + +## File map + +| 文件 | 职责 | +| --- | --- | +| `fulfillment_workflow.py` | 收缩/拆分 `try_auto_chain_after_match`;match 成功不再 generate/upload | +| `process_gate_executor.py` | 确认 match handler 只 sync+return;artifact handler 保持原子 | +| `process_gate_bridge.py` | sync:无 Artifact 时 **不得**把 artifact 标 passed;可保留 readiness 资格投影 | +| `process_gate_service.py` | 确认 match pass 后续跑能落到 `regenerate_excel_artifact` | +| `auto_progress_controller.py` | 确认 technical next_action 覆盖 artifact | +| `process_gate_contract.py` | 如需:明确 artifact 自动 next_action / 配置开关语义 | +| `docs/features/shipping-notice/process-gate-recovery-contract.md` | 记录「禁止跨 Gate 内嵌产物」 | +| `docs/features/shipping-notice/technical.md` | 删改 `try_auto_chain` 开心路径描述 | +| 测试 | STP acceptance、auto_progress、process recovery、line rematch、excel regenerate | + +--- + +### Task 1: 红灯 — 匹配 Attempt 不得生成 Excel;artifact 须有独立 Attempt + +**Files:** +- Create/Modify: `backend/tests/test_shipping_gate_orchestration_separation.py`(新建聚焦文件) +- 可参考:`test_shipping_notice_stp_acceptance.py`、`test_shipping_auto_progress_p0_3.py`、`test_shipping_process_recovery_plan.py` + +- [x] **Step 1–3: 红灯测试已写入并随实现转绿**(见 `test_shipping_gate_orchestration_separation.py`) +- [ ] **Step 4: 本地 commit(仅当用户要求)** + +--- + +### Task 2: 拆除 match 内嵌 `try_auto_chain` 产物副作用 + +**Files:** +- Modify: `backend/app/services/shipping_notice/fulfillment_workflow.py` +- Modify: `backend/tests/test_shipping_notice_stp_acceptance.py`(改写旧「chain 必调 generate」断言) + +- [x] **Step 1: 收缩 `try_auto_chain_after_match`** +- [x] **Step 2: 更新 STP acceptance 测试**(Gate 路径不调 generate;遗留路径只 submit auto_progress) +- [x] **Step 3: 跑聚焦测试**(orchestration separation 全绿;STP chain 相关用例绿) + +--- + +### Task 3: 保证 match pass 后续跑落到独立 `artifact_generation` Attempt + +**Files:** +- Modify: `backend/app/services/shipping_notice/process_gate_bridge.py`(必要时) +- Modify: `backend/app/services/shipping_notice/process_gate_service.py` / `process_gate_contract.py`(若 next_action 未自动露出) +- Modify: `backend/app/services/shipping_notice/process_gate_executor.py`(仅确认 `_handle_regenerate_excel` 不变) + +- [x] **Step 1: sync 规则收紧**(STEP 6A 无 export 不得 passed;保留 regenerate next_action) +- [x] **Step 2: 确认 enqueue 不跳过 artifact**(`_auto_generate_excel_enabled` 门控入队) +- [x] **Step 3: 绿灯 Task1 入队断言** +- [x] **Step 4: recovery / auto_progress_p0_3 聚焦回归通过** + +--- + +### Task 4: 端到端编排回归(prep → match → artifact → handoff) + +**Files:** +- Modify/Create: `backend/tests/test_shipping_gate_orchestration_separation.py` 增加集成用例 +- 可选:轻量 spy Job enqueue,避免真实 RPA + +- [x] **Step 1: 集成断言**(`test_happy_path_generate_excel_only_in_artifact_attempt`) +- [x] **Step 2: 跑测试至全绿** + +--- + +### Task 5: 次要债务(可同 PR 或 follow-up)— 恢复路径嵌套 + +**Files:** +- Modify: `process_gate_executor.py` → `_handle_retry_inventory_from_field_mapping` + +- [x] **Step 1: 评估范围** — **Follow-up P1**(本迭代不拆):映射恢复 Attempt 仍嵌套 `_handle_retry_inventory_matching`;函数注释已标注目标形态。 + +- [ ] **Step 2: 若本迭代纳入** — 延期。 + +--- + +### Task 6: 文档与死代码标注 + +**Files:** +- Modify: `docs/features/shipping-notice/process-gate-recovery-contract.md` +- Modify: `docs/features/shipping-notice/technical.md`(`try_auto_chain` / auto excel 相关) +- Modify: `progress_workflow.py` 文件头注释(标明 P0-3 后旧跨 Gate 体为 dead) + +- [x] **Step 1: 契约增补一条硬规则** +- [x] **Step 2: technical.md 开心路径改为「match pass → enqueue artifact Attempt」** +- [x] **Step 3: 可选清理** — `_dispatch_legacy_orchestration` / STEP 3 注释标 DEPRECATED。 + +--- + +### Task 7: 验收清单(人工) + +- [ ] 重匹配成功后:诊断/Attempt 列表出现 **独立的** `artifact_generation` Attempt(不仅是 matching)。 +- [ ] 右卡在生成中短暂停留「Excel 生成」而非匹配完成后瞬间跳过。 +- [ ] 生成失败:仅 artifact Attempt `blocked_retryable` +「重新生成 Excel」;matching 保持 passed。 +- [ ] `AUTO_GENERATE_EXCEL=false`:匹配通过后停在可点「重新生成」,不静默 noop。 +- [ ] `AUTO_UPLOAD=true`:artifact pass 后再出现 freight Attempt(不在 match 内嵌 upload)。 +- [ ] i18n / `can_fulfill_complete_line` 等已合入改动回归仍正常。 + +--- + +## 风险与回滚 + +| 风险 | 缓解 | +| --- | --- | +| 匹配通过后若 enqueue 失败会停在无 Excel | 测试锁 enqueue;失败时 UI 仍有 regenerate | +| 延迟增加(多一个 Job) | 可接受;观测性优先 | +| 旧 chat tool 仍调 `try_auto_chain` | Gate 路径切断;遗留路径改为只 submit auto_progress | +| sync 与 enqueue 竞态 | 沿用现有 Job 去重 / idempotency_key;禁止 sync 提前 passed artifact | + +回滚:恢复 `try_auto_chain` 内 generate(仅应急);正式修复应保留独立 Attempt。 + +--- + +## 建议实施顺序 + +1. Task 1 红灯 +2. Task 2 拆 chain +3. Task 3 sync + enqueue +4. Task 4 集成 +5. Task 6 文档 +6. Task 5 视排期 +7. Task 7 人工验收 + +**非目标(本计划不做):** 重写 20 Gate 模型、改前端按钮契约、合并 excel_readiness 与 artifact、删除全部 legacy auto_progress 函数体。 diff --git a/docs/superpowers/plans/2026-09-06-shipping-status-contract-unification.md b/docs/superpowers/plans/2026-09-06-shipping-status-contract-unification.md new file mode 100644 index 00000000..000c89d5 --- /dev/null +++ b/docs/superpowers/plans/2026-09-06-shipping-status-contract-unification.md @@ -0,0 +1,181 @@ +# 货代域状态契约统一(Phase A–E) + +> **日期**:2026-09-06 +> **范围**:shipping-notice 对外状态词 / 投影边界 +> **权威手册**:落地后同步 [`docs/features/shipping-notice/technical.md`](../../features/shipping-notice/technical.md)「状态契约统一」节 +> **Phase A 状态**:已完成(`project_notice_upload_status` / `project_facts_upload_state`) +> **Phase B/D/E 状态**:已完成(2026-09-06;C 仍待做) +> **本轮未做**:Phase C match 拆名;D1c 全局停发 `pending_human_reason` + +--- + +## 1. 方法论(以 Phase A 为模板,B–E 强制同款) + +Phase A 已验证的最佳实践,**后续 Phase 一律照此执行**,不再用「过渡期同义词 / 双读 / LEGACY 兜底」: + +| 原则 | 含义 | 反例(禁止) | +|---|---|---| +| **单一判词** | 每个对外字段、每个语义位只有一个规范词;调用方只写 `== 'canonical'` | `{'uploaded','succeeded','success'}`、`includes([...])` | +| **单点投影** | 跨层翻译只发生在**一个** projector/mapper;业务/FE 禁止再造轮子 | 各文件自写 frozenset、入口散落 OR | +| **层内一词 ≠ 层间一词** | Attempt / Artifact / Job / Gate / Tool 可保留各自库内词;**同名对外字段**必须经投影后只暴露本层契约词 | 把 Attempt.`succeeded` 直接塞进名为 `upload_status` 的 API | +| **硬切、无历史兼容** | 不读旧别名、不双字段镜像、不 LEGACY-UNIFY;测试与 FE 同步删兜底 | 「先发双认、下个版本再删」 | +| **故意双层保留** | Gate→`user_status`、五段 `lifecycle_stage` vs 15 段 stage、`lifecycle_status` vs runtime 是**分层设计**,不是同义词债 | 为了「统一」把 F2 与 stage 压成一词 | + +成功判据(每个 Phase 自检): + +1. 存在唯一投影/映射函数(或已有契约 helper,禁止新建平行集合)。 +2. 调用点全部改为单一等值判断或既有域谓词(如 `has_verified_upload_success`)。 +3. 前后端测试不再断言或接受别名。 +4. `technical.md` 写明该字段的规范词与禁止项。 + +--- + +## 2. Review 结论(仍成立) + +同类债不止 `upload_status`:内部枚举泄到对外字段、或同字段混多域词,迫使 frozenset / `includes` 兜底。 + +```mermaid +flowchart TB + subgraph keep [故意双层_保留] + Gate["Gate/Execution"] --> UserStatus["user_status F2六值"] + Machine15["15段 processing stage"] --> Lifecycle5["lifecycle_stage 五段"] + end + subgraph done [Phase A_已收口] + Attempt["Attempt.succeeded"] --> UploadProj["project_notice_upload_status → uploaded"] + Attempt2["Attempt/Artifact"] --> FactsProj["project_facts_upload_state → succeeded"] + end + subgraph todo [B-E_待硬切] + HumanMix["跨层: waiting_human / waiting_review / needs_human / idle"] + MatchMix["同名多域: match_status"] + JobMix["Job→automation 散落 synonym"] + Hygiene["canceled/done/error 入口与读侧"] + end +``` + +--- + +## 3. Phase A — 上传边界(已完成 · 模板) + +| 层 | 字段 | 规范成功词 | +|---|---|---| +| Attempt(库内) | `ShippingUploadAttempt.status` | `succeeded` | +| Artifact(库内) | `ShippingExportArtifact.status` | `uploaded` | +| Notice 面 API | `upload_status` | **`uploaded`**(经 `project_notice_upload_status`) | +| facts | `facts.upload_state` | **`succeeded`**(经 `project_facts_upload_state` ∈ `PROJECTION_UPLOAD_STATES`) | +| 业务完成谓词 | — | `has_verified_upload_success`(三层验证,非同义词 OR) | + +调用方只允许 `projected == 'uploaded'` 或 `has_verified_upload_success`;禁止再读 Attempt 原词做成败。 + +--- + +## 4. Phase B — human-wait:跨层硬切(重评) + +### 问题本质(与 A 不同) + +**不是**同一语义的多别名,而是 **把不同层的词当成同义词**: + +| 层 | 规范词 | 用途 | +|---|---|---| +| Wire `user_status`(F2) | **`waiting_human`** 等六值 | 唯一用户主态;已有 `user_status_for_gate_status` | +| Processing / lifecycle **stage** | 可含 `waiting_review`、`order_review` 等 | 阶段位置,**不是** user_status | +| Tool 响应 `status` | `needs_human` | Agent/Tool 契约,**不得**泄入 `user_status` | +| 废弃/脏词 | `idle`、`pending_review` 作 user_status | **停发**;读侧不认 | + +当前债:FE [`normalizeLifecycleStatus`](../../../frontend/src/features/chat/shipping/conversationProcessingProjection.ts) 的 `[LEGACY-UNIFY]` 把 `waiting_human` 压成 `waiting_review`;卡片仍 `waiting_human \|\| idle`。 + +### 落地做法(同款原则) + +1. **不新造** synonym projector;复用 `process_gate_contract.USER_FACING_TASK_STATUSES` + 既有 Gate→user mapper。 +2. 后端保证 wire `user_status` ∈ F2 六值;**禁止**把 stage 词或 Tool `needs_human` 写入 `user_status`。 +3. FE:**删除** LEGACY-UNIFY;`userStatus === 'waiting_human'` 单判;文案/stage 走独立 stage 字段。 +4. **无兼容期**:停发即删读侧别名;测试锁定混层必失败。 + +### 不做 + +- 不把 `waiting_review` 并进 `waiting_human`(那是 stage)。 +- 不把 Tool `needs_human` 改成 `waiting_human`(换一层契约,属于另案)。 + +--- + +## 5. Phase C — match_status:同名多域拆字段(重评) + +### 问题本质 + +**同音异义(homonym)**,不是同义词:`match_status` 被 inventory / profile / STP / ledger 共用不同枚举。 + +### 落地做法 + +1. **拆名硬切**(无双读旧字段): + - 任务履约:`inventory_match_status` ∈ {`fulfillable`,`partial`,`unfulfillable`,…}(以 `match.py` / 行聚合为准) + - 模板路由:`profile_match_status` ∈ profile 路由枚举 +2. STP / ledger / audit **改写**到对应域词;禁止再用 `matched`/`shortage` 冒充 fulfillable 语义。 +3. 行级对外只发 `inventory_matched`;FE 删 `matched` 双认。 +4. 单点:聚合只走既有 `aggregate_match_status_for_task`(或改名后的唯一出口),调用方 `==` 域内一词。 + +### 不做 + +- 不写「旧 match_status OR 新字段」过渡读。 +- 不把三域枚举塞进一个 frozenset「统一成功」。 + +--- + +## 6. Phase D — blocking_reason / Job→automation(重评) + +### D1 `blocking_reason` + +- Wire **只暴露** Gate 形 `blocking_reason` / `blocking_reason_code`。 +- `pending_human_reason`:可留作写库镜像,**读 API 停发、FE 停读**(硬切,不做双字段兼容窗口)。 +- 判定复用既有 Gate 投影,不新造 reason synonym 表。 + +### D2 Job → Case `automation.status` + +- 抽取**唯一** `project_job_to_automation_status(job, …)`(落点靠近现有 [`order_review_workbench_projection`](../../../backend/app/services/shipping_notice/order_review_workbench_projection.py) 内联逻辑)。 +- Job 库内可保留 `succeeded`/`dead` 等;**mapper 内**翻译一次;调用方只见 Case automation 枚举,禁止 `{succeeded,success,completed}` / `{failed,dead}` 散落。 +- FE 只消费投影后的 automation 枚举。 + +--- + +## 7. Phase E — 入口卫生 + 不变量门禁(重评) + +与「兼容入口归一」旧表述不同:**读侧零别名,写侧单点规范化**。 + +1. 每个子系统一个 write-path normalizer(取消态只认 `cancelled`;禁止读侧再认 `canceled`/`done` 作同义)。 +2. `failed`/`error`/`fatal`:对外失败词按该层契约定一词;其余只在 mapper 入口吸收并**立刻写成规范词**,库外不泄漏。 +3. 不变量测试:关键 API 字段 ∈ 契约集合;**禁止**在 projector 模块外新增 synonym frozenset(CI/单测扫描或显式白名单)。 +4. Phase A 已示范:成功路径不留 `success` 对外出口。 + +--- + +## 8. 执行顺序与切片 + +| Phase | 状态 | 建议触发 | 依赖 | +|---|---|---|---| +| **A** 上传投影 | **完成** | — | — | +| **B** human-wait 跨层硬切 | **完成** | — | 不动 Gate→user 设计 | +| **C** match 拆名 | 待做 | STP/ledger 再踩坑或 API 演进窗口 | 独立变更,忌与 B 绑死 | +| **D** reason / automation | **完成(D1b+D2)** | D1c 全局 PH 停发可另开 | 写路径 PH 列保留 | +| **E** 卫生门禁 | **完成(最小门禁)** | 全量入口归一可跟 C | `test_shipping_status_contract_hygiene` | + +**禁止**:发现债就一次清完;每个 Phase 单独可验证、单独可回滚。 + +--- + +## 9. 明确保留(不要合并) + +- Gate/Execution → `user_status`(F2) +- `lifecycle_stage`(五段)vs 15 段 processing stage(`freight_upload` vs `freight_uploading` 属分层) +- `lifecycle_status`(active/voided/…)vs runtime status +- STP `progress_nodes` 诊断 ≠ UI 真源 +- FileAsset.`upload_status`(另一产品面) + +--- + +## 10. 与旧计划差异(本次重评) + +| 旧表述 | 新表述 | +|---|---| +| B:冻结 wire,LEGACY 后端停发后再删 FE | B:**立即硬切**;删 LEGACY-UNIFY;跨层分词而非 synonym 合并 | +| C:拆分/冻结,可过渡 | C:**拆名硬切、无双读** | +| D:双字段可共存一段时间 | D:**读侧只留 blocking_reason**;PH 停发 | +| E:入口归一 + 兼容拼写 | E:**写侧单点规范化 + 读侧零别名**;不变量禁 frozenset 扩散 | +| 「过渡期同义词兜底」 | **全面取消**;与 Phase A 一致 | diff --git a/docs/superpowers/specs/2026-08-25-shipping-artifact-notice-and-inventory-reload-design.md b/docs/superpowers/specs/2026-08-25-shipping-artifact-notice-and-inventory-reload-design.md deleted file mode 100644 index 0dcab416..00000000 --- a/docs/superpowers/specs/2026-08-25-shipping-artifact-notice-and-inventory-reload-design.md +++ /dev/null @@ -1,80 +0,0 @@ -# 发货 Excel 单据编号与库存结果重读设计 - -## 背景与目标 - -当前 `ShippingNotice.business_no` 在客户确认/正式建单时分配,并被工作台展示为“发货通知单号”。这与实际业务不一致:现有的 `ShippingNotice` 就是发货通知单实体,但应延后到其 Excel 首次成功生成的同一业务事务中创建;一个发货通知单可覆盖多条订单明细,而每条订单明细只能归属一个有效发货通知单。Excel 是发货通知单的外在文件表示,不是业务主实体。 - -同时,库存 RPA 超时后,业务人员需要先重新读取已经产生但未被系统消费的库存结果;该操作不得再次触发 RPA。 - -本设计的目标是: - -1. 复用现有 `ShippingNotice` 承载单号和订单明细归属,而非以 Excel Artifact 承载业务身份。 -2. 保证发货通知单与首次生成的 Excel 在同一事务中产生;一个通知单覆盖一个固定的订单明细集合。 -3. 在库存 RPA 超时后,提供只读取并挂接有效库存快照的恢复动作。 - -## 数据模型与编号边界 - -复用现有 `ShippingNotice` 作为发货通知单实体,使用其 `business_no`、业务日期、日内流水、规则版本、所属正式订单及状态字段;其现有 Reservation/Artifact 明细关联以订单明细为外键,并对有效归属建立唯一约束。`ShippingExportArtifact` 只保存该通知单的 Excel 文件版本和生成输入快照。 - -首次生成 Excel 时,在同一数据库事务内完成以下操作: - -1. 根据经库存匹配确认的订单明细/Reservation 创建现有 `ShippingNotice`,并冻结其归属集合。 -2. 按客户、上海业务日期为该发货通知单分配业务编号。 -3. 创建并校验该通知单的首个 Excel Artifact,并将 Artifact 关联到通知单。 -4. 提交事务后才将发货通知单、Excel 文件及单号作为正式结果对外展示。 - -编号写入失败、明细绑定失败或 Artifact 校验失败时,整个生成事务失败,不得暴露发货通知单、无编号 Excel 或订单明细占用。 - -新流程不再在客户确认/正式订单创建阶段分配 `ShippingNotice.business_no`,而是在创建该 Notice 与首个 Excel 的同一事务分配。历史记录仍可查询、下载和审计;新投影和新货代操作使用该 Notice 的 `business_no`。 - -一个 `ShippingNotice` 恒等于一张发货通知单、一个业务编号和一个 Excel。分批发货时,每个 Excel 都必须创建独立 `ShippingNotice` 并分配独立单号;不得在同一 Notice 下创建第二个 Excel Artifact。模板修订或技术故障需要重出文件时,沿用既有文件修复/替代机制,不得将第二个有效 Excel 挂到同一 Notice,也不得改变已冻结订单明细集合。 - -## API、投影与 UI - -处理工作台的“发货通知单号”仅在发货通知单及其首个 Excel 均已在同一事务中成功生成后展示。生成 Excel 前不显示该字段。 - -下载 Excel、RPA 上传、人工确认上传、批量上传投影与审计查询均按发货通知单号精确定位通知单,再读取其当前有效 Excel 和已冻结明细集合。不得再把整单 `task_no` 或新流程中的 `ShippingNotice.business_no` 当作外部发货通知单号。 - -既有按 Notice 级 `business_no` 的路由和审计语义保持不变。过渡期须兼容历史“先建 Notice 后生成 Excel”的数据;新数据仅在首个 Excel 成功生成时创建 Notice 并分配其 `business_no`。 - -## 库存结果重读动作 - -新增正式 Gate action:`reload_inventory_result`,仅归属 `inventory_preparation`。 - -该动作执行步骤: - -1. 根据当前任务已冻结的库存源和仓库身份查找最新、未过期、状态为 ready 的库存快照。 -2. 复用现有身份校验和 `link_snapshot_to_task` / `link_snapshot_to_task_for_preparation` 逻辑挂接快照。 -3. 从快照 JSON 或存储文件读取库存行,并调用既有库存加载/门禁同步流程。 -4. 写入独立审计事件,记录命中的快照、来源、仓库及读取结果。 - -该动作严禁调用 trigger 写入、`retry_rpa` 模式或创建新的 RPA Attempt。未找到有效快照、快照过期或身份不匹配时,以可恢复阻断返回,并下发“重新获取库存”(现有 `retry_inventory_preparation`,明确为重新运行 RPA)和上传库存文件的替代路径。 - -RPA 超时对应的 `inventory_preparation` Gate 应将 `reload_inventory_result` 作为首选主动作;用户主动选择“重新获取库存”时才重新创建 RPA 导出。 - -## 错误处理与审计 - -所有新增 API/服务错误保持 `{ success, data | error, request_id }` 契约,业务失败使用既有 `AppError` 子类。新增错误码必须同步四语言 `errors.json`。 - -审计必须能回答:哪个发货通知单在何时因首次 Excel 生成而创建、覆盖哪些 Reservation/订单明细、其当前及历史 Excel Artifact 分别是什么;以及库存重读是否命中快照、为何未命中、是否发生任何 RPA trigger(该操作必须为否)。 - -## 测试与验收 - -后端测试至少覆盖: - -1. 客户确认和正式建单后不再分配新 Notice 级编号。 -2. 发货通知单与其首个 Excel Artifact 在同一事务中创建并分配通知单号。 -3. 同一发货通知单可绑定多个明细;同一明细不能归属两个有效发货通知单;分批导出必须创建不同 Notice、不同单号和不同 Excel。 -4. 通知单创建、编号、明细绑定或首个 Artifact 校验失败时不留下可用通知单、Excel、单号或 Reservation 占用。 -5. 同一 Notice 不能生成第二个有效 Excel;分批导出创建新 Notice,并保留 Reservation/明细不可重复归属约束。 -6. `reload_inventory_result` 命中有效快照时完成挂接和库存加载,且不写 RPA trigger、不创建 RPA Attempt。 -7. `reload_inventory_result` 无可用快照时返回可恢复阻断,允许用户明确选择重新运行 RPA。 -8. RPA 超时投影首选“重新读取库存结果”。 - -前端测试至少覆盖:Artifact 单号未生成时不显示、生成后显示;RPA 超时时主按钮为“重新读取库存结果”,并保留“重新获取库存(重新运行 RPA)”作为替代动作。四种语言(zh-CN、zh-TW、en、th)均提供新增文案。 - -## 非目标 - -- 不为每条订单明细生成单独单号;订单明细只能通过通知单明细关联归属一个有效发货通知单。 -- 不改变库存 RPA Worker、trigger 文件格式、callback 协议或已存在的重新 RPA 行为。 -- 不修改历史数据的已有 Notice 单号;仅提供兼容读取。 diff --git a/docs/superpowers/specs/2026-09-01-shipping-prep-single-projection-design.md b/docs/superpowers/specs/2026-09-01-shipping-prep-single-projection-design.md new file mode 100644 index 00000000..977d4cd5 --- /dev/null +++ b/docs/superpowers/specs/2026-09-01-shipping-prep-single-projection-design.md @@ -0,0 +1,198 @@ +# 设计:订单生命周期工作台「下游工作面」单源投影收敛(彻底单源化) + +日期:2026-09-01 +状态:已确认(方案 2 彻底版:不做历史兼容 / 旧行为保留) +关键词:shipping-workbench / fulfillment-prep / freight-upload / upload-complete / single-source-projection / FOIU / skeleton-loading + +> 本文档承接 `2026-08-31-shipping-workbench-stage-lazy-load-design.md`(阶段懒加载)与 +> `2026-09-01-shipping-stage-capability-window-design.md`(阶段能力集),聚焦订单生命周期工作台 +> **下游工作面**(通知准备 / 货代上传 / 通知完成)与右卡「当前任务/场景」的**两次投影 / +> 先只读后可编**闪烁,并以**彻底单源化**根治。 + +## 背景与问题 + +进入「通知准备」(`fulfillment_prep`)时,页面先后进入两个状态(用户观察): + +1. **图1(首投影)**:库存匹配表仅有列头、无行数据(或行退化)、右侧「当前任务」显示 + 「步骤未指定」、**不可编辑**(无勾选列、无「选择出库单明细 / 生成发货通知单」工具条)。 +2. **图2(次投影)**:行矩阵完整、顶部出现 `PJO | ZN…` 订单摘要、右卡显示「场景: 库存匹配」、 + **可编辑**(工具条 + 勾选列 + 生成按钮出现)。 + +用户在 1→2 之间看到「先不可编辑、再变可编辑」的闪烁 —— 即「两次投影 / 不可编辑→可编辑」。 + +## 根因(why) + +下游工作面是一个**由多个相互独立、异步到达、且到达时刻不一致的投影拼装**的复合 UI: + +| 表面要素 | 当前来源投影 | 到达通道 | +|---|---|---| +| 行矩阵内容 / `capabilities` / `source_options` | `formalTaskDetail.ui_state.stage_context.preparation` | `loadFormalTaskDetail()`(挂载预取 + `hasFormalOt` watcher + `progressVersion` watcher) | +| **可编辑**(勾选列 / 波次出单工具条) | `activeCase.available_actions` 含 `edit_formal_task` | `loadReviewCase()`(进入下游阶段才懒加载) | +| 顶部订单摘要 | `activeCase.draft.header_values.po_number` + `documentNavItems` | `loadReviewCase()` | +| 客户 PO 行号列 | `displayCase.schema.fields` + `displayDraftLines` | `loadReviewCase()` | +| 右卡「场景/下一步」 | `shippingProcessingProjection`(主)+ `activeCase.current_stage`(兜底) | `useShippingProcessingWorkItem`(轮询) | + +下游各段的渲染门仅为 `hasCreatedShippingTask && formalTaskDetail && `;而 +「可编辑性 + 摘要 + 客户 PO 列 + 右卡阶段兜底」都依赖 **`activeCase`(review Case)**。下游阶段 +`activeCase` 默认**不加载**、要等 `loadReviewCase` 二次触发 → 与 `formalTaskDetail` 错峰 → 先只读残缺 +(图1),后可编辑完整(图2)。 + +> 行业定性:这是 **Flash of Incomplete UI(FOIU)/ loading 状态泄漏**。React Query / SWR / Relay +> 的核心约定是一个资源只有 `isLoading → data`(或 `isLoading → error`),**禁止把"已渲染但语义上是 +> 半成品"的中间态当作真实状态**。当前实现恰好把"内容已到、可编辑性未到"当作"就绪",于是泄漏了 +> 半成品只读态。 + +## 五阶段双投影审计(2026-09-01 全量核查) + +对五个阶段逐面核查「是否由多个独立、异步、错峰到达的投影拼装」。结论如下: + +| 阶段 / 面 | 主来源投影 | 是否双投影 | 说明 | 处置 | +|---|---|---|---|---| +| 接收解析 `intake_parse` | `activeCase` + `intakeParseContext` | 否(低风险) | 编辑器单源;context 有授权门 + `caseContentSkeleton` 骨架 | 边界外(编辑器单源) | +| 订单复核 `order_review` | `activeCase` | 否 | 复核编辑器单源;`caseContentSkeleton` 骨架 | 边界外(编辑器单源) | +| **通知准备 `fulfillment_prep`** | `formalTaskDetail.ui_state` + **`activeCase`(`formalEditable`)`** | **是(核心)** | 可编辑性/摘要/客户 PO 列依赖懒加载 `activeCase` → 先只读后可编 | **彻底单源化** | +| 货代上传 `freight_upload` | `formalTaskDetail`(门)+ `freightNoticeGroups` | 否 | 内容/动作来自任务级 `group.available_actions`(非 `activeCase`);有 `freightNoticeGroupsLoading` 占位 + stale-while-revalidate | 一并单源化(门/内容仍任务级) | +| 通知完成 `upload_complete` | `formalTaskDetail`(门)+ `freightNoticeGroups` | **是(轻)** | 段内**缺加载占位**:直接渲染 `uploadedFreightNoticeGroups.length`,直入时闪「0 已上传/空」再填充 | **补加载占位** | +| **右卡「当前任务/场景」(跨全部阶段)** | `shippingProcessingProjection`(主)+ **`activeCase.current_stage`(兜底)** | **是(跨阶段)** | 下游阶段 `activeCase` 不加载 → 阶段兜底缺失 → 先「步骤未指定」占位后真值(`currentProcessingStageDisplay`,`ShippingOrderReviewView.vue:223`) | **彻底单源化** | + +**结论**:根治对象为**全部下游工作面(通知准备 / 货代上传 / 通知完成)+ 右卡当前任务/场景**。 +两个编辑器阶段(接收解析 / 订单复核)本就是单源(`activeCase` 为其权威),保持不动。 + +## 方案(彻底单源化:后端驱动 + 前端原子渲染) + +### §1 目标与边界 + +**目标**:让**所有下游工作面**(通知准备 / 货代上传 / 通知完成)与**右卡当前任务/场景**完全脱离 +`activeCase` / `displayCase` / `formalEditable`,只由**一个权威投影** `formalTaskDetail.ui_state` +(+ 既有的 `shippingProcessingProjection` 承担实时自动化/进度)驱动,一次原子渲染,消除一切 +「先只读后可编 / 空→有 / 步骤未指定→场景」的两跳。 + +**边界(不做)**: +- 不改顶部五阶段导航结构。 +- 不重构「订单复核 / 接收解析」编辑器(`activeCase` 是它们的权威单源;见审计表)。 +- 不引入 GraphQL / BFF / 新框架 / 新状态库。 + +### §2 后端:`ui_state` 作为下游工作面唯一权威(单源 DTO) + +`build_task_ui_state`(经 `/shipping-tasks/?view=workbench`,恒 `include_stage_context=True`, +见 `api/workspace/shipping_notice.py:557`)是下游工作面的**唯一权威**。在其已有基础上补齐 +下游面当前被迫从 review Case 取的字段: + +```jsonc +// stage_context.preparation(在现有 status/lines/source_options/source_locked/capabilities 基础上) +{ + "editable": true, // 【新增】任务级:本正式 OT 已确认且非仅查看 → 工作面可操作 + // preparation_lines[] 新增原生 customer_po_line_no(业务核对主键;区别于已下发的 line_no/line_no_source, + // 后者可能退化为内部行序 sequence)。列头用标准字段名「客户 PO 行号」(standard_field_registry.py:134)i18n; + // 列是否展示由前端按 prep 行是否含 customer_po_line_no 简单判定,无需单独后端标志。 +} +// 【不在后端改】顶部「PJO | ZN…」摘要由前端用既有投影拼装: +// file_name ← Run/Queue item;po_number ← shippingProcessingProjection.sourceSummary.poNumber; +// version ← reviewProgressContext(reviewProgressVersionLabel);caseNo ← route 参数。 +// 不读 activeCase,也不新增后端 summary 字段。 +``` + +**关键决策**: +- **`editable`(任务级)**:取值 == 现有 `edit_formal_task` 判据(`case.status=='confirmed'` 且存在 + `confirmed_task_no`,见 `order_review_projection.py:603-608`),即「live 已确认正式 OT,非历史/作废查看」。 + **后端判据(明确化)**:存在正式任务号(`task.order_task_no` / 关联 `confirmed_task_no`)**且** + `task.lifecycle_status` 不属于 `{closed, cancelled}` 时置 `true`;被替换/历史/作废视图置 `false`。 +- **`edit_window` 不替代 `editable`**:`edit_window`(`editable_scope`,`order_edit_window_service.py:123`) + 是 D10 **字段级**`{header, lines}` 编辑窗,判据「无 Export Artifact 且无活动 Attempt」,Excel 生成后 + 会变 `false`;而「波次出单」需要任务级「已确认 OT」。二者语义不同,不可互换。`edit_window` 仅用于 + 正式任务编辑器字段级读写锁定。 +- **下游面零 `activeCase` 依赖**:`hasCreatedShippingTask` / `hasFormalOt` / `confirmedNoticeTaskNo` + 全部由 Run/Queue 摘要项(后端已带 `has_formal_ot`/`confirmed_task_no`,见 + `order_review_projection.py:1173-1174`)与 `ui_state` 供给,不再读 `activeCase`/`displayCase`。 + +### §3 前端:下游工作面只渲染该单源 + 原子门 + 骨架/占位 + +**通知准备**: +- 新增 `preparationSurfaceReady`:`formalTaskDetail && ui_state.stage_context.preparation` 完整; + 未就绪渲染骨架(复用现有 `formalTaskDetailPending` 分支),就绪后**一次渲染完整可编辑面**。 +- 新增 `preparationEditable`:`computed(() => ui_state.stage_context.preparation?.editable ?? false)`; + 替换模板三处 `formalEditable`(勾选列 / 「选择出库单明细 + 生成发货通知单」工具条 / 行级选源)。 +- **删除 `formalPreparationContext` 的 `[B1]` 兜底**(回退 `displayCase.line_fulfillment` 正是"只读半成品" + 来源);Prep 面只认 `ui_state.stage_context.preparation`。 +- 顶部订单摘要改由**既有投影拼装**(Run/Queue item + `sourceSummary.poNumber` + `reviewProgressContext`), + 不再读 `activeCase`;客户 PO 行号列改由 §2 DTO(`lines[].customer_po_line_no`)供给,不再依赖 + `displayCase`/`displayDraftLines`/`lineSchemaFields`。 + +**货代上传 / 通知完成**: +- 内容与动作继续由任务级 `freightNoticeGroups` + `group.available_actions` + `formalTaskDetail.ui_state` + 供给(本就是任务级,无 `activeCase`);**通知完成段补 `freightNoticeGroupsLoading` 加载占位**, + 消除直入时「0 已上传/空」先行。 + +**右卡当前任务/场景(真单源)**: +- `currentProcessingStageDisplay` 的「当前阶段/场景」**只读 `shippingProcessingProjection`**(实时、轻量、已轮询), + 不读 `ui_state` / `activeCase.current_stage` —— 避免「同一语义多源先 A 后 B」的闪烁。 +- **投影未就绪** → 返回空阶段,由右卡在 `loading` 时渲染骨架占位(`stageLoading`);**不是**「步骤未指定」 + 之类的误导值。`isLoading → data`,无两跳。 +- `ui_state` 不参与右卡阶段(它只用于下游工作面内容);终态「通知完成」由投影 + (`uiState.lifecycleStage==='upload_complete'` / `userStatus==='completed'`)判定。 +- 保留 `loading` fail-closed(投影读取中抑制可执行动作)语义。 + +**统一**:下游路径与 `activeCase` / `displayCase` / `formalEditable` 解除所有读关系; +`loadReviewCase()` 只在进入「订单复核 / 接收解析」编辑器时触发(`REVIEW_EDITOR_NEEDED_STAGES` +仅保留这两阶段)。 + +### §4 数据流(下游工作面原子首屏) + +``` +Run + Queue(导航/阶段入口 + has_formal_ot/confirmed_task_no)──┐ +任务详情 view=workbench(ui_state 单源:行矩阵+capabilities+editable+摘要+客户PO列)──┼─ 并行 +work-item 投影(OT;右卡阶段/实时自动化/进度) ────────────────┘ +复核 Case + Evidence ── 默认不拉;进入「订单复核 / 接收解析」才拉 +``` + +各下游面模板门均为「该面单源就绪」原子门;loading→骨架/占位;ready→完整面;无中间只读/空态。 + +### §5 加载 / 错误 / 回归 + +**加载态**:骨架 / 加载占位;**错误态**:沿用 `formalTaskDetailLoadFailed` + 「重新加载」按钮; +全程不出现「半成品只读 / 空→有」中间态。 + +**回归测试**(`frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts`): +- 进入 Prep:`formalTaskDetail.ui_state` 单源就绪即渲染**完整可编辑矩阵**(勾选列 + 工具条 + + 「生成发货通知单」);无需二次 `activeCase`;无「只读→可编辑」翻转。 +- `activeCase` 缺省(下游懒加载)**不影响** Prep 可编辑性与行矩阵(顺序断言:`getReviewCase` 在 + 下游阶段**不被调用**)。 +- 删除 `[B1]` 兜底后,`displayCase.line_fulfillment` 为空不降级为「只读半成品」。 +- 右卡:阶段**只由 `shippingProcessingProjection`** 供给;投影未到 → 空阶段 + 骨架占位, + 不出现「步骤未指定→场景」两跳,也不读 `ui_state`/`activeCase`。 +- 通知完成:直入(`freightNoticeGroups` 未就绪)时段内显示加载占位,不闪「0 已上传/空」。 +- 货代上传:保持既有加载占位。 + +**后端测试**(`backend/tests/test_shipping_*`): +- `stage_context.preparation.editable` 在下发(`include_stage_context=True`)时存在且取值符合 + 「已确认 OT」判据;历史/作废任务为 `false`。 +- `preparation_lines[].customer_po_line_no` 存在(原始客户 PO 行号,非 `line_no`)。 +- Run/Queue 摘要项 `has_formal_ot` / `confirmed_task_no` 在下游阶段稳定下发。 + +### §6 分阶段落地(小而可验证) + +1. 后端:`ui_state.stage_context.preparation` 增 `editable`;`preparation_lines[]` 增 + `customer_po_line_no`(原生值,非 `line_no`)。跑 `test_shipping_*` 回归。 + (摘要不改后端:前端用既有投影拼装。) +2. 前端:新增 `preparationSurfaceReady` + `preparationEditable`;替换三处门控;删除 `[B1]` 兜底与 + 下游路径对 `activeCase`/`displayCase`/`formalEditable` 的全部读取; + `currentProcessingStageDisplay` 改为**只读 `shippingProcessingProjection`**(投影未到 → 空阶段 + + 骨架占位,不读 `ui_state`/`activeCase`);摘要去 `activeCase`(既有投影拼装);客户 PO 列读 + `lines[].customer_po_line_no` + 标准 i18n 列头;`REVIEW_EDITOR_NEEDED_STAGES` 收窄到 + 仅编辑器两阶段;通知完成段补 `freightNoticeGroupsLoading` 占位。`npm run build` 通过。 +3. 全量回归 + 手动核对(深链带 `task_no` / 批次中心跳转 / 通知准备直接进入),确认无任何 + 「只读→可编辑 / 空→有 / 步骤未指定→场景」两跳;且下游阶段 Network 无 `getReviewCase`/`getReviewEvidence`。 + +**效能约束(实现时必须守住)**: +1. 右卡阶段只由 `shippingProcessingProjection`(实时轻量轮询)驱动,不耦合 `formalTaskDetail` 重刷新节奏; +2. `build_task_ui_state` 不增加触发频率(沿用 `deepLinkTaskPrefetch` + `formalTaskDetailGeneration` + 代际守卫 + `progressVersion` 变化检测);`view=workbench` 继续裁剪重字段,`ui_state` 只追加小字段; +3. `loadFreightNoticeGroups` 保持 `freightGroupsInFlight` 去重 + stale-while-revalidate; +4. 下游阶段请求计数 ≈3-4(Run+Queue+taskDetail+work-item),无 `getReviewCase`/`getReviewEvidence`。 + +## 自测入口 + +- 后端:`PYTHONPATH=D:\Workspace\HxProjects\hxops\backend`, + `backend\.venv\Scripts\python.exe -m pytest tests/test_shipping_* -v`(测试环境慢,逐文件跑)。 +- 前端:`cd frontend && npm run build`(内含 `vue-tsc -b` 类型拦截)。vitest 因 `node:crypto`/vite8 + 暂不可用,以前端 build + 手动核对为主。 diff --git a/docs/superpowers/specs/2026-09-01-shipping-retire-checkpoint-state-machine-design.md b/docs/superpowers/specs/2026-09-01-shipping-retire-checkpoint-state-machine-design.md new file mode 100644 index 00000000..ecc5d9f1 --- /dev/null +++ b/docs/superpowers/specs/2026-09-01-shipping-retire-checkpoint-state-machine-design.md @@ -0,0 +1,233 @@ +# 2026-09-01 货代发货通知 — 下线旧 CheckPoint 状态机(收敛到 Gate + 领域数据分离)设计 + +> 目标:下线旧粗粒度状态机(`checkpoint` + `checkpoint_kind`),把"进程位置 / 是否人工 / 待办 / 按钮"改由**单一事实来源(SSOT)**推导:**履约+复核位置 = Gate(Process Gate)**,**review case 处置(非订单 / 文件质量异常)= 接收解析节点**,**文档 intake 文本抽取失败 = 文件质量异常处置**。业务领域数据保持独立标量字段,不塞进 Gate。 +> 前提:模块未正式上线(无历史兼容负担);不影响现有功能需求。这是**减法**。 + +--- + +## 1. 背景与问题 + +### 1.1 现状:两套状态机表达同一个履约进程 + +确认后 OT 的"进程位置 + 是否需要人工"存在**两套**表达: + +| 层 | 表达 | 来源 | 现状 | +|---|---|---|---| +| CheckPoint(旧,粗) | 一个 `checkpoint` id + `checkpoint_kind`(AUTO_CONTINUE / MUST_HUMAN / WAIT_MANUAL_UPLOAD / COMPLETE) | `resolve_task_ui_state`(`state_machine.py:246`)从任务标量字段投影 | 与 Gate 概念重复 | +| Process Gate(新,细) | 20 门禁 + Execution/Gate/Attempt + 恢复动作 + 幂等 | `process_gate_contract.py` / `process_gate_service.py` | 真正的工作流状态机 | + +`checkpoint_kind` 那 4 分类**恰好是** `gate_status + responsible_party + blocking_reason → user_mode` 的一张粗查表。**CheckPoint 是 Gate 的粗投影,概念重复 → 违反单一事实来源(SSOT)。** + +### 1.2 关键区分:状态机 ≠ 领域数据 ≠ 派生视图 + +这里要分清**三层不同的东西**: + +| 层 | 是什么 | 来源 | +|---|---|---| +| **Gate** | 工作流/检查状态机(20 gate 各自的 status + attempt + 恢复动作 + 责任方 + 作废链) | Execution/Gate/Attempt 表 | +| **领域数据** | `inventory_lines_json`(库存数据)、`export_file_path`(Excel 产物指针)、`match_status`(匹配结果值)、`upload_status`(上传结果) | **领域服务产出**(inventory/fulfillment/upload),Gate 只**校验**其是否就绪 | +| **派生视图** | "进程位置 / 是否人工 / 待办 / 用户态 / 阶段摘要" | 旧机由领域数据投影;新设计**由 Gate 推导** | + +**三个约束**: + +1. **Gate ≠ 领域数据**:`inventory_lines_json` 装库存数据、`export_file_path` 是产物指针,Gate 表里没有这些。把领域数据塞进 Gate 会让状态机"爆炸",是过度设计。 +2. **不能把 Gate 压回领域数据列**:Gate 是**更富**的状态机(每个 gate 的 status/attempt/恢复/作废/责任方),几列标量表达不了;CheckPoint 当初正是因为"标量列太粗"才被 Gate 取代。压回去是倒退。 +3. **领域数据 ≠ Gate 的缓存**:领域数据是真实数据、由领域服务产出,不是对 Gate 状态的缓存;它只是被 Gate 校验。 + +行业最佳实践 = **状态机(Gate)+ 领域数据(标量字段)正确分离**;派生视图(位置/待办/状态)从 Gate 推导。 + +--- + +## 2. 设计原则 + +- **撤**:旧粗状态机(`checkpoint` + `checkpoint_kind`,即 `state_machine.TaskUiState` 的状态机投影)。 +- **留**:Gate(状态机)+ 标量字段(领域数据/结果)。不把数据塞回 Gate。 +- **不新增**:不新造第三套状态;只把"位置/是否人工/待办/按钮"从旧机迁到正确轴。 +- **SSOT**:履约+复核位置 = Gate;review case 处置 = 接收解析节点;领域数据 = 标量字段。 + +--- + +## 3. 最终 CP 去处(全部 20 个) + +### 3.1 复核 gate(seq1-9,在执行链内)→ 从 Gate 读 + +| CP | 位置 | Gate | +|---|---|---| +| `CP_PARSE_REVIEW` | 解析需人审 | `order_field_extraction` / `document_profile_routing`(needs_human) | +| `CP_CUSTOMER_REVIEW` | 客户身份确认 | `customer_resolution`(blocked_manual) | +| `CP_RSV_REQ` | Reservation 需人审 | `reservation_validation`(blocked_manual) | + +> 复核 gate 确实在 OT 执行链里(如 exec 51 的 seq5-9 均为 passed),故复核 CP 读 Gate 即可。 + +### 3.2 履约/上传/完成 gate(seq10-20)→ 从 Gate 读 + +| CP | Gate | +|---|---| +| `CP_INVENTORY_PENDING` | `inventory_preparation`(pending/queued/running) | +| `CP_UPLOAD_REQ` | `inventory_preparation`(RPA 耗尽→补传库存文件) | +| `CP_READY_MATCH` | `inventory_matching`(pending,字段映射 passed 后) | +| `CP_READY_EXPORT` | `excel_readiness`(pending,满足性 passed 后) | +| `CP_EXPORT_READY` / `CP_EXPORT_GENERATED` | `artifact_generation`(passed)→ 货代上传 | +| `CP_UPLOAD_FAILED` | `freight_upload_rpa`(failed_terminal / blocked_retryable) | +| `CP_UPLOAD_RESULT_UNKNOWN` | `freight_upload_rpa`(waiting_external) | +| `CP_WAITING_UPLOAD` | `manual_upload_handoff`(blocked_manual) | +| `CP_UPLOADED` | `manual_upload_handoff`(passed)/ `upload_complete` | +| `CP_COMPLETED` | `upload_complete` | +| `CP_INVENTORY_SOURCE_REVIEW` | `inventory_source_routing`(规则自动) | +| `CP_ORDER_FREEZE` | `order_freeze_readiness` | + +### 3.3 review case 处置(接收解析节点)→ 从 review case / disposition 读 + +| CP | 处置 | review case | +|---|---|---| +| `CP_REJECTED` | **标记为非订单**(`mark_non_order`) | `status='non_order'` | +| `CP_NOTICE_TEXT_EXTRACTION_FAILED` | **文件质量异常**(`mark_quality_issue`) | `status='quality_issue'` | + +> 这两者本就是"接收解析"节点的处置结果,不是独立状态机节点。`mark_non_order` / `mark_quality_issue` 是建单前人工 gate 的既有动作,`order_review_projection._allowed_actions` 已覆盖(non_order → view;quality_issue → view/mark_quality_issue/reparse)。 + +### 3.4 转瞬/信息态 → 省略 + +| CP | 处理 | +|---|---| +| `CP_PARSE_OK` | 省略("解析通过"仅转瞬态,被 gate passed / 推进中吸收) | +| `CP_TASK_EXISTS` | 省略("任务已存在"信息态,被 task_creation passed 吸收) | + +## 4. 结论:旧 CheckPoint 状态机可整体下线 + +**所有 20 个 CP 节点去处已定**: + +- **16 个 → Gate**(复核 seq1-9 + 履约/上传/完成 seq10-20)。 +- **2 个 → review case 处置**(非订单 / 文件质量异常)。 +- **2 个 → 省略**(转瞬/信息态)。 + +撤掉 `checkpoint` + `checkpoint_kind` 后:履约+复核位置读 Gate;拒绝/文件质量读 review case;领域数据读标量字段。**无需为任何 CP 硬造 Gate 等价。** + +--- + +## 5. 为什么符合行业最佳实践(SSOT) + +- **单一事实来源**:一个状态概念只有一个权威表达(履约+复核 = Gate;处置 = review case)。消除并存的旧粗状态机,即消除反模式的"双写状态"。 +- **移除被取代的旧代码层**:CheckPoint 是初版粗机,Gate 是为更细控制/恢复/幂等后加。冗余源于"新层到位旧层未撤"。正确修法是在新层验证后删旧层。 +- **增量迁移**(见 §6):先并行验证、再切换、最后清理,是"状态机替换"的标准流程。 +- **不过度设计**:下线是往"更少、更单一"走;Gate 复杂由职责需要,不构成保留旧粗层的理由。 + +## 6. 一个需要处理的问题:廉价读取(不是保留状态机的理由) + +**先分辨"便宜"的对象**:旧机便宜,是因为它算的**派生视图**(位置/是否人工/待办/状态)由**单行标量列**直接投影(0 join)。而查 Gate 要跨 `executions + gates + attempts` 多表 join。**单任务详情**查 Gate 完全没问题;**批量/列表/待办索引**一次算 N 个任务的待办/状态时,逐任务 join 就是 N+1/重 join,明显变慢。 + +**但这不构成保留旧状态机的理由——正确做法是**: + +- **派生视图从 Gate 推导**(进程位置/是否人工/待办/状态 = Gate 的 `user_status`/`user_mode`/`entry_surface`),保持 SSOT。 +- **为满足廉价读**,把**这个派生视图**做成**缓存**(写到 task 行/派生列),列表/索引读缓存,不 join Gate 表。 +- **领域数据字段(`inventory_lines_json`、`export_file_path`、`match_status`、`upload_status`)保持原样**——它们是**真实数据,不是缓存**,由领域服务产出、被 Gate 校验。**不要**把领域数据当缓存写回、也**不要**把 Gate 压回这几列。 + +> 一句话:**不是"把 Gate 改成读标量列"(倒退),而是"把旧机算的那个派生视图改成读 Gate,并缓存它以满足廉价读";领域数据照旧单独存放。**(此点属后续实现范畴,本期设计仅指出方向。) + +### 6.1 与阶段能力集(`STAGE_CAPABILITY_DEFINITIONS`)的关系 + +`STAGE_CAPABILITY_DEFINITIONS`(阶段能力集,定义在别处实现)与**本下线方案正交、不冲突、且方向互相印证**: + +| | 阶段能力集 | 本下线方案 | +|---|---|---| +| 概念轴 | **动作/权限**(该阶段能点哪些按钮) | **状态/进程**(走到哪、是否人工) | +| 字段依赖 | `stage` / `scope` / `action_code` / `invalidate` / `reset_to`(全部 gate/阶段码) | `checkpoint` / `checkpoint_kind` → 改读 Gate + review case | +| 是否引用 `checkpoint_kind` | **没有** | — | + +要点: + +1. `STAGE_CAPABILITY_DEFINITIONS` 只写 gate 码/阶段码,**不引用** `checkpoint`/`checkpoint_kind`,故不依赖旧状态机。 +2. 阶段能力集的核心(触发上游能力 → **作废下游 gate → 重置回 inventory_preparation → 重跑**)正是**把 Gate 当唯一事实源**(通过作废/重置 Gate 表达回退与推进)——**与本下线方案想让"位置从 Gate 推导"方向一致**,甚至是"Gate = 事实源"的先行实践。 +3. 阶段能力集作废下游时会经 `recovery_invalidation_service` 清 `match_status`/`export_file_path` 等标量:旧机(从标量投影)会自然跟随;下线后从 Gate 读位置,Gate 被重置位置也自然对。**两种口径自洽,不打架**。 +4. 能力渲染 `ui_state.stage_context.preparation.capabilities`(`_stage_capabilities_for_task`)只读 `lifecycle_stage`/`source_locked`/预条件,**不看 `checkpoint_kind`**。 + +**结论**:两者不同轴、可并行、无需因一方改动而改另一方。 + +--- + +## 7. 消费点迁移 + +| 消费点 | 现读 | 改读 | +|---|---|---| +| 自动推进早停 `progress_workflow.py:415-431` | `checkpoint_kind == MUST_HUMAN / WAIT_MANUAL_UPLOAD` | Gate 推导 `user_mode`(`blocking_reason → BLOCKING_REASON_TO_USER_MODE`)+ `responsible_party` | +| 待办分类 `query_service._todo_category_from_ui:722` | `checkpoint + checkpoint_kind` | 履约:Gate `user_status`/`user_mode`;复核:review case 处置 | +| 用户态 `user_facing_status.py` | `checkpoint → 用户态` | Gate `user_status_for_gate_status` + review case 处置 | +| 阶段上下文/摘要 `ui_state._build_stage_context/_build_task_summary` | `checkpoint_kind` 驱动 `current_todo`/`entry_surface`/阻断文案 | 同轴推导 | + +--- + +## 8. 迁移计划(分阶段,低风险) + +### 阶段 1:加轴推导 + 双读(行为不变) +- 新增"轴推导"纯函数(履约=Gate、复核=review case 处置)。 +- 4 个消费点**先读新轴推导**,并**对照旧 checkpoint_kind** 断言一致(双读,不改行为)。 +- 目的:验证新推导与旧机一致,暴露分歧。 + +### 阶段 2:消费点切到新轴 +- 4 个消费点正式改读新轴推导,移除对 `resolve_task_ui_state` 的 `checkpoint`/`checkpoint_kind` 依赖。 +- 每切一个,跑该消费点回归。 + +### 阶段 3:下线旧机(硬删顺序,禁止跳步) + +> **保留字面量 ≠ 保留状态机**:`parse_review` / `inventory_pending` / `export_ready` 等字符串是 +> **位置标签**(与 `derive_position` 对齐),可继续作文案/映射表的 key。删的是 **CheckPoint 状态机**: +> `CheckpointKind`、`resolve_task_ui_state` 的 CP 裁决、`CP_*` 常量命名,以及 SQL/API 对它们的依赖。 + +**强制顺序(后步依赖前步):** + +1. **SQL `todo_category` CASE 切 Gate / `review_status`** + `_task_todo_category_sql_expr` / `_order_task_todo_category_sql_expr` 优先读 + `ShippingProcessExecution.current_gate_code` + `review_status`;与 ORM `task_todo_category` + 口径对齐后再删旧 checkpoint 分支。列表过滤不得在删旧机后仍依赖 `resolve_task_ui_state` 同序 CASE。 + +2. **切断消费点对 `resolve_task_ui_state` 的依赖** + 确认 progress / query / ui_state / user_facing / chat 均 Gate-first;仅允许迁移期 API + 别名 `checkpoint_*`(值 = `derive_position` / `derive_user_mode`)。 + +3. **下线 `state_machine` CP 裁决** + 移除 `CHECKPOINT_KIND_REGISTRY` / `CheckpointKind` 作为事实源;`resolve_task_ui_state*` + 删除或改为薄委托(仅回退无 Execution 的 review_status / 领域标量),**禁止**再输出独立 CP 状态机结果。 + +4. **`CP_*` 常量清理 / 改名** + `constants.py` 中仅服务旧机的 `CP_*`:能映射为位置标签的改为 `POSITION_*`(或内联字面量); + 转瞬态 `CP_PARSE_OK` / `CP_TASK_EXISTS` 直接删除。`RS_*` / `PH_*` **保留**。 + 文案表(`_PAUSE_REASON_*`、`_CHECKPOINT_LABELS`)改键为位置字符串,禁止再 import `CP_*`。 + +5. **聊天 / Tool 别名收口(可选同 PR 或紧随)** + 前端已 Gate-first(`shippingUiPosition`);后端 Tool/confirm 响应优先 `position`/`user_mode`, + `checkpoint` 字段可暂留别名,硬删 API 字段另开任务。 + +6. **回归 + grep 门禁** + `grep CP_|CheckpointKind|resolve_task_ui_state` 仅允许测试过渡与明确 deprecated 包装; + 跑 `test_gate_derivation` + `test_shipping_notice_ui_state` + `test_shipping_notice_query_service` 待办分类。 + +### 阶段 4:回归 +- 全量受影响 `test_shipping_*`;重点:自动推进、待办 SQL/ORM 一致、用户态、五阶段/摘要、F5CDD796 类死局。 +- 前端:`shippingUiPosition` / `useChatShippingRefresh` / `parseOrderReviewConfirmResponse`。 + +--- + +## 9. 风险与注意 + +| 风险 | 对策 | +|---|---| +| 复核阶段 CP 停点归属(gate vs review case) | 已核对:复核 gate(seq1-9)在执行链内,CP_RSV_REQ 等读 Gate;非订单/文件质量走 review case 处置 | +| 廉价读取(列表/索引)性能 | 用 Gate 派生缓存/字段,不并存状态机(§6) | +| 4 消费点漂移 | 阶段 1 双读断言兜住 | +| 全量回归耗时(~1-2 min/file) | 只跑受影响 file;分阶段回归 | + +--- + +## 10. 验收标准 + +- [x] `checkpoint` + `checkpoint_kind` 不再被消费点直接依赖(4 消费点改读 Gate / review case 处置);API 字段已硬删为 `position` / `user_mode`。 +- [x] "位置 / 是否人工 / 待办分类 / 用户态 / 阶段摘要" 由 Gate + review 推导;领域标量 CP 裁决已删除。 +- [ ] 履约死局(F5CDD796 类)与正常流不回归(待人工冒烟)。 +- [x] Gate 与领域数据字段不互相塞入对方(数据仍在标量字段,状态机仍只是状态机)。 + +--- + +## 11. 不属于本设计的范围 + +- **不**把领域数据(库存/Excel/匹配结果)并入 Gate(过度设计)。 +- **不**重写 Gate 模型本身(保留状态机主轴)。 +- **不**触及阶段能力集(已在别处实现)。 diff --git a/docs/tec.md b/docs/tec.md index 57987002..6b0f0a71 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -27,9 +27,9 @@ ### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏) - 标准字段目录锁定 **58** 项;`reservation_id` 可同时存在于 Header 与 Line,资产唯一键为 `(field_code, scope)`。 -- 运行时投影:`line_key`(草稿稳定标识)、`effective_reservation_id = validated(line) ?? validated(header)`;`line_no` 为可识别内部项次,不再由 `position+1` 系统覆盖。 -- Schema `definition_json.derivation_rules`:同行明细派生契约(首期仅 `copy_if_empty`,目标仅 `line_no`);新草稿预置关闭的 `customer_po_line_no → line_no`。 -- `customer_po_line_no` / `line_no` 均进入确定性表格可解析字段集;Excel 导出行号为 `system_fact:export_sequence`。 +- 草稿行使用 `draft_line_id`;冻结档与库存准备使用 `snapshot_line_id` 和系统生成的 `line_no`;正式通知使用 `ShippingNoticeLine.line_no`。 +- Schema 不提供派生规则;`line_no` 不进入确定性表格解析字段集,由各单据写路径按顺序生成。 +- Excel 导出行序号使用已持久化的 `ShippingNoticeLine.line_no`。 - 进度事实源仍以后端状态机为准;阶段 0 冻结字段与投影语义。 ### STP 阶段 1:模板起行锚点(2026-07-30) @@ -54,7 +54,7 @@ - `stp_line_inventory_match`:准备冻结候选快照行;按 `effective_reservation_id + part_number` 跨文件匹配。 - 裁决:`ok` / `shortage` / `not_found` / `multi_file_conflict`;结果写入 `step_payload.line_inventory_resolutions`。 -- 唯一 ok 源 → `inventory_source_status=resolved` 并 `try_auto_chain_after_match` 生成 Excel(`export_sequence`);多源行级成功命中以主绑定源制单(`stp_line_match_multi`),同键多文件冲突仍停人工。 +- 库存门禁通过后才创建 `ShippingNotice`/`ShippingNoticeLine` 并生成 Excel;库存准备失败停留在通知准备阶段,多候选源只写一个批量 RPA trigger。 - `match_completed` 仅 `fulfillable` 且全部明细 `ok` 时允许 Excel;partial 禁止制单。 - OT 后短缺放行复用 `SHIPPING_LINE_AUTO_FULFILL` Job:已审计放行的短缺行可作为 wave 候选;仅唯一开放候选自动创建独立 `ShippingNotice` 并调度 Excel,多候选返回人工勾选,不自动合并或批次放行。 - `ensure_inventory` 多候选路径不隐式 RPA;自动链硬停 `wait_manual_upload`。 @@ -215,10 +215,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 ### 2.x 立账凭证检核(accounting-voucher-check) - 前端路由 `/workspace/accounting-voucher-check` 标记 `requiresAdmin`,工作台侧栏按当前用户角色隐藏入口;全局路由守卫负责阻止非管理员直接访问。 -- 任务引擎从 Oracle `apa_file` 按 `apa09` 查询当前自然月 `apa08`,一期仅处理 HXJM 套账。 -- 共享盘默认路径为 `vouche/{YYYY}/{MM}/{invoice_no}/`,通过目录模板配置支持调整;必检文件名通过配置维护。 -- 扫描器只读取目录和文件元数据判断文件是否存在,不读取内容、不调用 LLM;齐全票可基于元数据指纹增量跳过。 -- 共享盘不可用时批次失败并告警,不生成缺资料结论;单票缺目录或缺必检文件才记缺资料。 +- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `apa_file`(`apa08`/`apa09`);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 +- **销售一期来源**:ERP 打印 PO(查询与打印方式待确认)、OA 销货放行单一期模拟页面(后期换新接口)、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 +- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。归档复制策略为同名跳过。 +- **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。 +- **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。 +- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 - 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。 ### 2.x 货代发货通知批次库存能力 @@ -242,7 +244,7 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - Excel 命名规则由已发布模板的 `filename_pattern` 定义;未定义时读取环境变量 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两者均由后端编译、校验并在 Artifact 保存规则来源、版本、最终文件名和独立流水。客户端请求不得携带命名模式或文件名;流水即使 Artifact 作废亦不得复用。 - LLM Observation 必须有真实 `evidence_ref`,并以 `evidence_verified=false` 落库;任意关键字段存在该类 Observation 时,冻结门禁返回 `SHIPPING.ORDER_LLM_REVIEW_REQUIRED`。Dify 故障只能转人工复核,不能使确定性模板路径降级为猜测。 - JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.INVENTORY_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。 -- **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期优先按快照 ID 取值;普通 Schema 升级仅在 `field_code`、Header 作用域、值类型和身份授权均未变化时映射新 ID,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。 +- **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期**以 `field_code`(语义键)优先绑定**当前 Schema 字段,快照 `context_field_id`(UUID) 仅作同字段快速命中兜底;Schema 升级造成字段 UUID 漂移时仍能按稳定 `field_code` 承接旧快照,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。 - **裁决边界**:客户主体和送货站点独立候选;编码确定性匹配优先;多命中、冲突、未命中均进入人工复核。业务弱证据(地址、联系人、名称)默认不得单独自动确认;公共邮箱域名永久禁止。 - **Dify**:不新增 Tool 或修改画布。Dify 继续按已发布动态 Schema 契约提交 Header Observation;HXOPS 完成证据校验、字段裁决、规则匹配、质量门禁和最终确认。 - **技术编号与业务编号分离**:`ShippingNotice.task_no` 是内部不可变锚点;`ShippingNotice` 自持 `business_no`、标准客户和编号快照。一个 PO 可对应多个 Notice;每个 Notice 只有一个 `business_no` 和一个 Excel。货代下载、人工确认、RPA 上传和批量 API 只接受 `business_no`,内部 `task_no` 不得作为货代操作维度。 @@ -322,8 +324,9 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - 裁决结果写入 `ShippingOrderFieldDecision/ShippingOrderFieldValue`,流程摘要写入 `ShippingTask.step_payload_json.parse_validation`;字段模型调整必须配套 Alembic 迁移。 - 不保留旧字段 alias、双版本读取、固定订单行投影或历史值猜测回填;任务的 `current_order_extraction_id` 是履约读取入口。 - 订单抽取提交、人工确认和 `match_inventory` 三层重复执行关键门禁,防止脏值通过任一旁路进入后续履约。 -- 客户角色采用“解析原文”和“主数据解析”分层:动态 Schema 保存 Bill-to/Ship-to 名称、外部编码、来源系统及地址证据;`ShippingOrderCustomerMatch` 保存角色候选和确认快照;`ShippingCustomerExternalRef`、`ShippingCustomerSite`、`ShippingCustomerSiteIdentifier` 提供外部客户编码与送货站点匹配。LLM 不生成主数据 ID 或客户简称。 -- 客户匹配遵循外部编码优先、标准名称/已审核别名回退;Ship-to 必须落到启用站点并校验所属客户。Candidate 只展示候选,正式客户绑定和业务编号仍通过既有质量门禁。 +- 客户识别采用“解析原文”和“规则证据”分层:动态 Schema 保存 Bill-to/Ship-to 名称、外部编码、来源系统及地址证据;已发布 Identity Rule Set 以全部适用证据生成 `ShippingCustomerShadowResolution`,其中 `confirmed_customer_id` 是唯一客户确认事实。`ShippingCustomerExternalRef`、`ShippingCustomerSite`、`ShippingCustomerSiteIdentifier` 只提供可被规则使用的主数据证据。LLM 不生成主数据 ID 或客户简称。 +- 客户识别可采用外部编码、标准名称、已审核别名或其他已发布证据;Bill-to/Ship-to 不是客户业务角色。Candidate 只展示 Resolution 候选,正式客户绑定和业务编号仍通过既有质量门禁。 + - 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。 - 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 @@ -1456,8 +1459,7 @@ Dify - **受控坐标预览**:页面授权写入 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。 - **模板版本中心数据边界**:版本列表接口只返回族摘要和版本摘要,不返回 PDF、正文、大体积 Layout payload 或盲测真值。版本详情接口返回 Profile 元数据、Schema 摘要、定义摘要、配置规模、冻结证据摘要、样本摘要、测试摘要、自动冻结资格摘要、来源版本和 checksum;样本画布预览接口必须以冻结样本绑定身份鉴权,短时、单用途、管理员绑定且 `no-store`,不得接受任意 `document_id` 直接取页。 - **模板版本中心审计与使用数据边界**:`audit-events` 只返回事件类型、操作者摘要、`request_id`、过滤条件命中的安全 `detail_json` 和 ISO 8601 时间,不返回 PDF、正文、对象存储地址、盲测真值或可复原答案的坐标。`usages` 只返回脱敏文档名、Run 编号、匹配/执行状态、原因码、模板身份命中方式和只读诊断入口;不得回传文档正文、文件地址或运行时原始模型输出。 -- **订单客户指纹与冻结门禁**:`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、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。 - +- **订单客户识别与冻结门禁**:`ShippingCustomerShadowResolution` 保存已发布 Rule Set 的证据、候选快照和确认审计。只有 Resolution 为 `confirmed`、存在 `confirmed_customer_id`、证据和 Rule Set checksum 时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存 Resolution ID、Rule Set checksum/version、确认方法和人员时间,避免主数据变化改写历史履约事实。 ### XFA 拆分规则作用域与源路径(2026-08-05) @@ -1514,3 +1516,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t `freight-receipt-rpa` 写入 `shipping_receipt_rpa.v1` trigger,仅由 `freight_receipt_rpa_worker.py` 消费。它使用专属 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 和 `...RECEIPT_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 receipt drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_inventory_files` 无关联。 下载接口为 `GET /api/workspace/receipt-report-files/{file_id}/download`(管理员或排程接收人);`GET /api/workspace/receipt-report-files` 仅列出当前用户有权读取的脱敏归档元数据,并在授权过滤后施加 limit。管理员可通过 `GET /api/admin/receipt-rpa-units?status=failed` 定位失败单元,并以 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`(必填原因)或 `POST /api/admin/receipt-report-files/{file_id}/resend` 补偿。运行等待 callback 超时会被 Worker 启动和周期扫描收口为失败,绝不自动重试;管理员补偿创建新单元,保留旧单元。管理员在既有库存站点抽屉通过独立 `GET/PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` 维护收料配置,不能改写库存 Source 字段:DBS 维护路径/条件/Warehouse,Crane 固定 `Inbound Details`,拒绝 Warehouse 和查询条件;Worker 无论 Profile 登录 URL 的原 hash 均强制进入 `#/inbound-details-query` 并直接使用页面默认条件。所有入口写含前后状态快照的 `ShippingAuditEvent`;三年期满仅删除对象、保留文件事实与审计。 + +# 在途仓自动调拨独立架构(2026-08) + +调拨业务域独立于 shipping_notice 订单解析:ackend/app/services/in_transit_transfer/ 承载状态机/DTO/审计/文件准备/预检/执行/恢复/通知/归档/指标,erp_adapter.py 为 ERP 唯一访问出口(SOAP 在 WSDL 冻结前 fail-closed,凭据仅来自环境/Secret)。数据落 ransfer_* 七表(迁移 it1a2b3c4d5e);异步走 ransfer 队列(workers/worker_in_transit_transfer.py);08:00/09:00 platform job 注册于 schedule。前端卡片在 rontend/src/features/chat/(TransferMessageView 自驱动),四语言文案齐备。运维手册见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md)。 diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index d799eb41..622102dc 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -85,6 +85,8 @@ const ProcurementContractPage = () => import("@/features/admin/modules/procurement-contract/ProcurementContractPage.vue"); const TrainingConfigPage = () => import("@/features/admin/modules/training-config/TrainingConfigPage.vue"); +const IntegrationConnectorPage = () => + import("@/features/admin/modules/integration-connector/IntegrationConnectorPage.vue"); export const adminRoutes: RouteRecordRaw[] = [ { @@ -355,6 +357,16 @@ export const adminRoutes: RouteRecordRaw[] = [ title: "admin.nav.trainingConfig", }, }, + { + path: "integration-connector", + name: "AdminIntegrationConnector", + component: IntegrationConnectorPage, + meta: { + requiresAdmin: true, + adminModule: "integration_connector", + title: "admin.nav.integrationConnector", + }, + }, { path: "reports/:table?", name: "AdminReports", diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index c16134d0..153bc89b 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -2,7 +2,7 @@ * app/router/routes/workspace.routes.ts * 工作台路由表:/workspace 布局壳 + 各业务子页面懒加载。 * 依赖:vue-router、contract-payment 权限常量;meta.title 存 i18n key(workspace.*),由 guards 解析为 document.title。 - * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款子路由用 requiresFeaturePermission 而非 requiresAdmin。 + * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款子路由用 requiresFeaturePermission 而非 requiresAdmin;立账凭证明细为 accounting-voucher-check/runs/:runId。 */ import type { RouteRecordRaw } from 'vue-router'; import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants'; @@ -84,6 +84,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: () => import('@/features/workspace/pages/AccountingVoucherCheckPage.vue'), meta: { title: 'workspace.nav.accountingVoucherCheck', requiresAdmin: true }, }, + { + path: 'accounting-voucher-check/runs/:runId', + name: 'workspace-accounting-voucher-check-detail', + component: () => import('@/features/workspace/pages/AccountingVoucherCheckDetailPage.vue'), + meta: { title: 'workspace.voucherCheck.detailTitle', requiresAdmin: true }, + }, { path: 'contract-payment', name: 'workspace-contract-payment', diff --git a/frontend/src/config.ts b/frontend/src/config.ts index ac6546ae..d3988a52 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -74,6 +74,7 @@ export const config = { shipping_inventory: true, // 货代配置 procurement_contract: true, // 采购合同审查(模板库 + 历史) training_config: true, + integration_connector: true, // 集成连接器配置 } } }; diff --git a/frontend/src/constants/shippingNoticeActions.ts b/frontend/src/constants/shippingNoticeActions.ts index 115507fb..eb0f5fcb 100644 --- a/frontend/src/constants/shippingNoticeActions.ts +++ b/frontend/src/constants/shippingNoticeActions.ts @@ -24,8 +24,6 @@ export type ShippingActionId = (typeof SHIPPING_ACTION_IDS)[number]; export const SHIPPING_KNOWN_ACTION_ID_SET = new Set(SHIPPING_ACTION_IDS); /** Backend state-machine codes — must never appear in user-visible chat text. */ -export const SHIPPING_TERMINAL_CHECKPOINTS = new Set(['uploaded', 'completed', 'rejected']); - export const SHIPPING_INTERNAL_STATUS_TOKENS = [ 'rpa_pending', 'upload_rpa_pending', diff --git a/frontend/src/features/admin/api/shipping-order-schema.api.ts b/frontend/src/features/admin/api/shipping-order-schema.api.ts index 1264aa85..710289a5 100644 --- a/frontend/src/features/admin/api/shipping-order-schema.api.ts +++ b/frontend/src/features/admin/api/shipping-order-schema.api.ts @@ -8,10 +8,6 @@ import { requestJson } from '@/shared/api/client'; import { getAuthHeaders } from '@/shared/utils/auth'; import type { - ShippingOrderDerivationRule, - ShippingOrderDerivationSimulateRequest, - ShippingOrderDerivationSimulateResult, - ShippingOrderDerivationSimulateSampleItem, ShippingOrderField, ShippingOrderFieldConfig, ShippingOrderSchemaAuditEventPage, @@ -158,13 +154,12 @@ export const getShippingOrderExtractionAudit = (extractionId: number) => auth(), ); -/** 整体保存草稿字段配置、自动建单策略、派生规则及每个字段的版本纳入状态。 */ +/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */ export const saveShippingOrderSchemaDraft = ( versionId: number, payload: { fields: ShippingOrderFieldConfig[]; auto_creation_policy?: { enabled: boolean }; - derivation_rules?: ShippingOrderDerivationRule[]; change_note?: string; expected_lock_version: number; }, @@ -177,34 +172,6 @@ export const saveShippingOrderSchemaDraft = ( }, ); -/** - * 对 Schema 版本派生规则做样本模拟(不改订单)。 - * @param versionId - Schema 版本 ID - * @param payload - 样本行与可选规则覆盖 / sample_ref - */ -export const simulateShippingOrderSchemaDerivation = ( - versionId: number, - payload: ShippingOrderDerivationSimulateRequest, -) => - requestJson( - `/api/admin/shipping-order-schema/versions/${versionId}/simulate-derivation`, - { - method: 'POST', - body: JSON.stringify(payload), - ...jsonAuth(), - }, - ); - -/** - * 列出可供派生规则模拟的历史 Extraction 样本。 - * @param limit - 返回条数上限 - */ -export const listShippingOrderSchemaDerivationSimulateSamples = (limit = 20) => - requestJson<{ items: ShippingOrderDerivationSimulateSampleItem[] }>( - `/api/admin/shipping-order-schema/derivation-simulate-samples?limit=${limit}`, - auth(), - ); - /** 删除错误草稿;发布版本由服务端拒绝删除。 */ export const deleteShippingOrderSchemaDraft = (versionId: number) => requestJson(`/api/admin/shipping-order-schema/versions/${versionId}`, { diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index cea62eda..de6789f3 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router'; import { LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText, Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow, - ScrollText, ExternalLink, PackageSearch, GraduationCap, + ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable, } from 'lucide-vue-next'; import type { Component } from 'vue'; import { config } from '@/config'; @@ -44,6 +44,7 @@ const iconMap: Record = { platform_apps: AppWindow, procurement_contract: ScrollText, training_config: GraduationCap, + integration_connector: Cable, requests: ShieldCheck, reports: BarChart2, shipping_inventory: PackageSearch, @@ -129,6 +130,8 @@ watch( isShippingActive, (active) => { if (!active) return; + // 进入任一货代子路由时自动展开父菜单,保证当前子页可见。 + navStore.shippingMenuExpanded = true; let matched = false; for (const groupKey of shippingGroups.value) { const groupHasActiveSub = SHIPPING_CONFIG_SUB_MODULE_METAS.some( @@ -210,14 +213,14 @@ watch( type="button" class="admin-nav-btn group justify-between" :class="{ 'admin-nav-btn--active': isShippingActive }" - @click="navigateModule('AdminShippingInventory')" + @click="navStore.shippingMenuExpanded = !navStore.shippingMenuExpanded" >
{{ t('admin.nav.shippingConfig') }}
-
+