diff --git a/backend/app/api/contract_payment.py b/backend/app/api/contract_payment.py index 0a7f41a9..728fe927 100644 --- a/backend/app/api/contract_payment.py +++ b/backend/app/api/contract_payment.py @@ -1,11 +1,12 @@ """ backend/app/api/contract_payment.py -用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要和同步 API。 +用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。 依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。 -逻辑:页面查询合同、节点与本周待发送摘要;同步和预警操作入队,避免请求线程执行外部系统和企微调用。 +逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。 合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。 -鉴权:所有接口要求已登录且具备 `contract_payment.access`(admin 默认开,可显式授予普通用户)。 +鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户); + 同步/扫描/周汇总发送仅 `role=admin`。 """ from __future__ import annotations @@ -28,6 +29,11 @@ from app.models import ( FileAsset, ) from app.services.contract_payment.alert_service import build_weekly_alert_summary +from app.services.contract_payment.ledger_focus import ( + LEDGER_FOCUS_VALUES, + apply_ledger_focus, + ledger_focus_counts, +) from app.services.contract_payment.parse_service import unique_parse_issues from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes from app.services.file_assets.service import read_asset_bytes @@ -92,6 +98,30 @@ def _require_contract_payment_access(): return user +def _require_contract_payment_admin(): + """ + 确保当前用户既有合同付款预警访问权,又是平台管理员。 + + 核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总 + 会改写外部系统或触发企微,因此仅 `role=admin` 可调用。 + + Args: + 无。当前请求身份由 JWT 上下文提供。 + Returns: + 已认证的管理员用户。 + Raises: + UnauthorizedError: 请求没有有效登录身份。 + ForbiddenError: 无合同付款访问权,或已授权但不是管理员。 + """ + user = _require_contract_payment_access() + if getattr(user, "role", None) != "admin": + raise ForbiddenError( + 'Admin privilege required for contract payment jobs', + code='CONTRACT_PAYMENT.ADMIN_REQUIRED', + ) + return user + + def _serialize_contract(row: ContractPaymentContract) -> dict: """ 序列化合同台账、付款节点及预警记录,供列表和详情共用。 @@ -170,7 +200,7 @@ def list_contracts(): """ 查询合同台账。 - 核心逻辑:支持合同编号、流程编号、采购单号和解析状态筛选,并按 offset 分页返回台账,避免工作台一次加载全部合同。 + 核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。 Args: 无。筛选条件从 query string 读取。 Returns: @@ -185,6 +215,7 @@ def list_contracts(): ContractPaymentContract.contract_no.ilike(like) | ContractPaymentContract.workflow_no.ilike(like) | ContractPaymentContract.purchase_order_no.ilike(like) + | ContractPaymentContract.supplier_name.ilike(like) ) parse_status = str(request.args.get("parse_status") or "").strip() review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"} @@ -195,6 +226,13 @@ def list_contracts(): else: # 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。 query = query.filter_by(parse_status="parsed") + focus = str(request.args.get("focus") or "").strip() + if focus: + if review_only: + raise ValidationError("待确认列表不支持汇总卡筛选", details={"focus": focus}) + if focus not in LEDGER_FOCUS_VALUES: + raise ValidationError("不支持的汇总卡筛选", details={"focus": focus}) + query = apply_ledger_focus(query, focus, session=db.session) page = max(_query_int("page", default=1), 1) page_size = min(max(_query_int("page_size", default=20), 1), 100) total = query.count() @@ -215,6 +253,21 @@ def list_contracts(): }, request_id=getattr(g, "request_id", None)) +@contract_payment_bp.route("/contracts/summary", methods=["GET"]) +def get_ledger_summary(): + """ + 查询合同台账四张汇总卡的合同份数。 + + 核心逻辑:始终统计全部已解析台账,不跟页面 keyword;口径与点卡片过滤列表共用 ledger_focus。 + Args: + 无。 + Returns: + 标准成功 envelope,含 due、overdue、needs_completion、due_this_month。 + """ + _require_contract_payment_access() + return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None)) + + def _query_int(key: str, *, default: int) -> int: """读取正整数查询参数;非法值回退默认值,防止分页接口返回 500。""" try: @@ -279,12 +332,15 @@ def enqueue_sync(): """ 将 OA 合同、验收和厂商预付款请款同步任务入队。 + 核心逻辑:仅管理员可入队;force / reparse_existing 仍走同一 Job,避免普通授权用户改写 OA 字段。 Args: 无。操作用户由 JWT 上下文读取。 Returns: HTTP 202 与后台 Job ID。 + Raises: + ForbiddenError: 非管理员或无合同付款访问权。 """ - user = _require_contract_payment_access() + user = _require_contract_payment_admin() data = request.get_json(silent=True) or {} force_value = data.get("force", False) if not isinstance(force_value, bool): @@ -303,12 +359,15 @@ def enqueue_alert_scan(): """ 将四阶段三轮合同付款预警扫描任务入队。 + 核心逻辑:仅管理员可手动补扫;日常扫描仍由排程触发。 Args: 无。操作用户由 JWT 上下文读取。 Returns: HTTP 202 与后台 Job ID。 + Raises: + ForbiddenError: 非管理员或无合同付款访问权。 """ - user = _require_contract_payment_access() + user = _require_contract_payment_admin() job_id = enqueue(JobType.CONTRACT_PAYMENT_ALERT, {}, domain="procurement_contract", business_ref="daily-alert", created_by_id=user.id, message="等待计算合同付款预警") return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202) @@ -331,12 +390,15 @@ def get_alert_summary(): def enqueue_weekly_alert_send(): """将合同付款预警周汇总发送任务入队。 + 核心逻辑:仅管理员可手动补发;周五 18:00 排程不受此限制。 Args: 无。操作用户由 JWT 上下文读取。 Returns: HTTP 202 与后台 Job ID。 + Raises: + ForbiddenError: 非管理员或无合同付款访问权。 """ - user = _require_contract_payment_access() + user = _require_contract_payment_admin() job_id = enqueue( JobType.CONTRACT_PAYMENT_ALERT_WEEKLY, {}, diff --git a/backend/app/api/kb/common.py b/backend/app/api/kb/common.py index 329439ef..e7b1f0fa 100644 --- a/backend/app/api/kb/common.py +++ b/backend/app/api/kb/common.py @@ -1,10 +1,13 @@ """ backend/app/api/kb/common.py -用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。 +用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览、下载头)。 依赖:app.core.*、models、services/kb/storage、edkb_system。 逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。 """ +from pathlib import Path +from urllib.parse import quote + from flask import current_app from sqlalchemy.exc import DatabaseError, OperationalError @@ -31,6 +34,31 @@ def require_user(): raise UnauthorizedError() return user + +def build_content_disposition(filename: str, *, as_attachment: bool = True) -> str: + """ + 构造 RFC 5987 Content-Disposition,保证中文源文件名不被浏览器拼成怪名。 + + 核心逻辑:quoted ASCII 回退名(保留扩展名)+ filename*=UTF-8''百分号编码原名。 + 浏览器优先 filename*;旧客户端才用 ASCII 回退。ASCII 段必须加引号且不含分号。 + + Args: + filename: 用户可见的原始文件名。禁止路径分隔与换行。 + as_attachment: True 为下载(attachment),False 为预览(inline)。 + + Returns: + 可直接写入响应头的 Content-Disposition 字符串。 + """ + safe_name = Path(str(filename or '').replace('\\', '/')).name + safe_name = safe_name.replace('\r', '').replace('\n', '').replace('"', '').strip() or 'download' + suffix = Path(safe_name).suffix + stem_ascii = Path(safe_name).stem.encode('ascii', 'ignore').decode('ascii').strip() or 'download' + ascii_name = f'{stem_ascii}{suffix}' if suffix else stem_ascii + encoded = quote(safe_name, safe='') + disposition = 'attachment' if as_attachment else 'inline' + return f'{disposition}; filename="{ascii_name}"; filename*=UTF-8\'\'{encoded}' + + def run_db_read(label: str, loader): try: return loader() diff --git a/backend/app/api/kb/documents.py b/backend/app/api/kb/documents.py index 17ed7dbd..4d213c03 100644 --- a/backend/app/api/kb/documents.py +++ b/backend/app/api/kb/documents.py @@ -3,13 +3,19 @@ backend/app/api/kb/documents.py 用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。 依赖:kb.blueprint、kb.common、services/kb/document_service。 -逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。 +逻辑:/documents* 与 /document-versions* 路由;业务见 document_service;源文件下载覆盖 RFC 5987 Content-Disposition。 """ from flask import jsonify, request, send_file from app import db from app.api.kb.blueprint import knowledge_base_bp -from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version +from app.api.kb.common import ( + build_content_disposition, + require_user, + serialize_document, + serialize_sync_record, + serialize_version, +) from app.core.auth.jwt import get_current_user from app.core.decorators import require_admin from app.services.kb import document_service @@ -24,10 +30,18 @@ def list_document_versions(document_id: int): @knowledge_base_bp.route('/document-versions//source-file', methods=['GET']) def get_document_version_source_file(version_id: int): + """ + 返回知识库版本原始文件。 + + 用途:工作台源文件信息弹窗下载原件;?download=1 时按附件下发,保存名与上传时一致。 + 核心逻辑:send_file 后再覆盖 Content-Disposition 为 RFC 5987,避免 Werkzeug ASCII 回退名无引号导致浏览器拼名。 + """ require_user() source_path, filename = document_service.resolve_source_file_path(version_id) as_attachment = str(request.args.get('download') or '').strip() == '1' - return send_file(source_path, as_attachment=as_attachment, download_name=filename) + response = send_file(source_path, as_attachment=as_attachment, download_name=filename) + response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment) + return response @knowledge_base_bp.route('/document-versions//training-preview-file', methods=['GET']) @@ -41,7 +55,9 @@ def get_training_preview_file(version_id: int): require_user() preview_path, filename = document_service.resolve_training_preview_file_path(version_id) as_attachment = str(request.args.get('download') or '').strip() == '1' - return send_file(preview_path, as_attachment=as_attachment, download_name=filename) + response = send_file(preview_path, as_attachment=as_attachment, download_name=filename) + response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment) + return response @knowledge_base_bp.route('/documents//sync-records', methods=['GET']) diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index bf1f4cd2..171d0de0 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -4,10 +4,11 @@ backend/app/jobs/handlers/shipping_order_extraction.py 用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。 依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、 ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、 - order_supplement_merge(仅 eml)。 -逻辑:物化附件与排版面 Job 均在主 try 内执行;每个 Unit 按 STP route_decision - 直通或落 provisional;needs_review 剥离验收标记;不调用 Dify 主链。 - 阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*; + order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。 +逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进, + 兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout; + 每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记; + 不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*; 合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。 """ @@ -44,6 +45,8 @@ from app.services.shipping_notice.order_extraction_run_service import ( complete_input_freeze, mark_order_extraction_persistence_started, order_extraction_layout_prerequisite_issues, + order_extraction_layouts_pending, + order_extraction_ready_document_ids, materialize_order_extraction_run_inputs, ensure_workflow_items_for_run, progress_ready_extraction_unit, @@ -661,7 +664,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: """ 执行一次纯确定性订单抽取 Job。 - 核心逻辑:物化附件与排版面 Job 纳入主 try;排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。 + 核心逻辑:物化附件与排版面 Job 纳入主 try;有 ready PDF 时按 Unit 抽取并立刻下游推进; + 仍有 layout pending 时 Job 成功收口并回到 waiting_layout,不终态 Run。 + 排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。 Args: ctx: Worker 上下文,仅用于安全日志。 @@ -703,47 +708,72 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: ensure_workflow_items_for_run(run, stage_when_ready='extracting') schedule_order_extraction_layouts(run, created_by_id=run.user_id) - # [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。 + # [STEP 2] 按 Unit 放行:仅当零 ready PDF 时整 Job defer;有 ready 则抽 ready Unit。 layout_issues = order_extraction_layout_prerequisite_issues(run) - if 'layout_pending' in layout_issues.values(): - # 布局等待期已进入 freezing;仍禁止追加,待布局就绪后完成冻结。 - run.phase = 'waiting_layout' - record_run_progress(run=run, event_code='layout_parsing_started', commit=False) - db.session.commit() - finish_job( - job.id, - result={ - 'run_no': run.run_no, - 'waiting_layout': True, - 'handoff_status': 'deferred_to_layout', - }, - message='已转交附件版面解析,完成后自动创建后继订单识别任务', - owned_attempt=owned_attempt, - ) - return - if layout_issues: - complete_input_freeze(run) - transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed') - transition_order_extraction_run( - run, target_status='failed', phase='layout_prerequisite_failed', - error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', - error_message='Order PDF layout prerequisites are incomplete', - ) - record_run_progress( - run=run, event_code='technical_failed', - reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', - summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False, - ) - db.session.commit() - finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt) - return + pending_layout_ids = { + document_id + for document_id, code in layout_issues.items() + if code == 'layout_pending' + } + hard_layout_issues = { + document_id: code + for document_id, code in layout_issues.items() + if code != 'layout_pending' + } + ready_document_ids = order_extraction_ready_document_ids(run) + if not ready_document_ids: + if pending_layout_ids: + # 布局等待期已进入 freezing;仍禁止追加,待任一布局就绪后再抽。 + run.phase = 'waiting_layout' + record_run_progress(run=run, event_code='layout_parsing_started', commit=False) + db.session.commit() + finish_job( + job.id, + result={ + 'run_no': run.run_no, + 'waiting_layout': True, + 'handoff_status': 'deferred_to_layout', + }, + message='已转交附件版面解析,完成后自动创建后继订单识别任务', + owned_attempt=owned_attempt, + ) + return + if hard_layout_issues: + complete_input_freeze(run) + transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed') + transition_order_extraction_run( + run, target_status='failed', phase='layout_prerequisite_failed', + error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', + error_message='Order PDF layout prerequisites are incomplete', + ) + record_run_progress( + run=run, event_code='technical_failed', + reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', + summary={'document_count': len(hard_layout_issues)}, job_id=job.id, commit=False, + ) + db.session.commit() + finish_job( + job.id, + result={'run_no': run.run_no, 'layout_issues': hard_layout_issues}, + message='订单附件解析条件不完整', + owned_attempt=owned_attempt, + ) + return - # [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。 + # [STEP 3] 至少一个 PDF 版式就绪即可建 Plan 并冻结输入;未 ready 的 Unit 留 pending。 plan = materialize_order_extraction_run_inputs(run) if plan is None: raise RuntimeError('order extraction plan was not finalized') # [BE-F03] 物化完成 → frozen,再进入 processing。 complete_input_freeze(run) + # 物化可能回填刚就绪的坐标证据;按最新前置条件决定本轮抽哪些 Unit。 + layout_issues = order_extraction_layout_prerequisite_issues(run) + pending_layout_ids = { + document_id + for document_id, code in layout_issues.items() + if code == 'layout_pending' + } + ready_document_ids = order_extraction_ready_document_ids(run) if run.status == 'queued': transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit @@ -751,6 +781,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: selection = (run.input_snapshot_json or {}).get('attachment_selection') or {} max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0)) runtime_budget_stopped = False + layout_blocked_in_wave = False run.current_job_id = job.id run.attempt_count = owned_attempt record_run_progress( @@ -759,6 +790,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: summary={ **_selection_progress_summary(run), 'unit_count': int(getattr(plan, 'unit_count', 0) or 0), + 'ready_document_count': len(ready_document_ids), + 'pending_layout_count': len(pending_layout_ids), 'job_attempt': owned_attempt, }, job_id=job.id, @@ -829,6 +862,29 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: continue if unit.status == 'review_required': continue + unit_layout_issue = layout_issues.get(int(unit.document_id or 0)) + if unit_layout_issue == 'layout_pending': + layout_blocked_in_wave = True + continue + if unit_layout_issue: + # 硬前置失败:pending→routing→failed,避免 Unit 永久挂起阻塞收口。 + if str(unit.status or '') == 'pending': + transition_order_extraction_unit(unit, target_status='routing') + transition_order_extraction_unit( + unit, + target_status='failed', + error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', + error_message=f'layout prerequisite: {unit_layout_issue}', + ) + record_unit_progress( + run=run, + unit=unit, + event_code='technical_failed', + reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED', + summary={'layout_issue': unit_layout_issue}, + job_id=job.id, + ) + continue unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt) db.session.expire_all() unit = db.session.get(ShippingOrderProcessingUnit, int(unit.id)) @@ -839,6 +895,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: wave_orders.extend(unit_orders) if runtime_budget_stopped: break + # 同批仍有 layout pending 的 Unit:禁止扩附,交 partial defer。 + if layout_blocked_in_wave: + break wave_orders = _wave_orders_for_expansion(run, orders=wave_orders) expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders) @@ -1094,6 +1153,23 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: job_id=job.id, ) raise + # [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。 + if layout_blocked_in_wave or order_extraction_layouts_pending(run): + run.phase = 'waiting_layout' + db.session.commit() + finish_job( + job.id, + result={ + 'run_no': run.run_no, + 'waiting_layout': True, + 'handoff_status': 'partial_units_done', + 'merged_unit_count': len(pending_merge_unit_ids), + 'ready_document_ids': sorted(ready_document_ids), + }, + message='已完成就绪附件的订单识别,其余附件版面解析完成后继续', + owned_attempt=owned_attempt, + ) + return orders = persisted_orders + merged_orders execution = { 'mode': 'deterministic', diff --git a/backend/app/services/contract_payment/alert_service.py b/backend/app/services/contract_payment/alert_service.py index 2875d5b6..d4869980 100644 --- a/backend/app/services/contract_payment/alert_service.py +++ b/backend/app/services/contract_payment/alert_service.py @@ -280,22 +280,24 @@ def _node_paid_date(node: ContractPaymentNode) -> str | None: def _build_excel(items) -> tuple[bytes, dict[str, object]]: - """生成收件人专属逐笔付款预警明细 Excel。""" + """生成收件人专属逐笔付款预警明细 Excel。 + + 核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。 + """ wb = Workbook() ws = wb.active ws.title = "付款预警明细" - headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件岗位", "状态"] + headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"] ws.append(headers) for cell in ws[1]: cell.font = Font(bold=True) counts = Counter() - for alert, contract, node, _user in items: - role = _ALERT_RULES[node.node_type][alert.alert_round - 1][1] + for alert, contract, node, user in items: ws.append([ contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—", str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""), str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—", - f"第{alert.alert_round}次", _role_label(role), alert.status, + f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status), ]) counts[node.node_type] += 1 ws.freeze_panes = "A2" @@ -305,6 +307,25 @@ def _build_excel(items) -> tuple[bytes, dict[str, object]]: return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}} +def _recipient_display_name(user: User | None) -> str: + """ + 返回 Excel「收件人」列展示的人名。 + + 核心逻辑:优先真实姓名;姓名为空时回退用户名,避免再写出岗位名称。 + Args: + user: 本行预警对应的系统用户;缺失时写「—」。 + Returns: + 去空白后的姓名或用户名;都没有时为「—」。 + """ + if user is None: + return "—" + name = str(getattr(user, "real_name", None) or "").strip() + if name: + return name + username = str(getattr(user, "username", None) or "").strip() + return username or "—" + + def _build_summary_message(summary: dict[str, object]) -> str: stages = summary.get("stages") or {} detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无" @@ -464,6 +485,22 @@ def _node_label(node_type: str) -> str: return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type) -def _role_label(role: str) -> str: - """返回提醒岗位中文名称。""" - return {"owner": "采购负责人", "department_head": "采购部负责人", "procurement_leader": "采购分管领导"}.get(role, role) +def _alert_status_label(status: str | None) -> str: + """返回预警状态的中文名称,供企微 Excel「状态」列使用。 + + 核心逻辑:与工作台 alertStatus 口径一致;未知编码原样回写,避免掩盖新增状态。 + Args: + status: 预警记录内部状态码。 + Returns: + 中文状态;空值写「—」。 + """ + code = str(status or "").strip().lower() + if not code: + return "—" + return { + "pending": "待发送", + "sent": "已发送", + "failed": "发送失败", + "resolved": "已关闭", + "sending": "发送中", + }.get(code, str(status).strip()) diff --git a/backend/app/services/contract_payment/ledger_focus.py b/backend/app/services/contract_payment/ledger_focus.py new file mode 100644 index 00000000..4565bf3c --- /dev/null +++ b/backend/app/services/contract_payment/ledger_focus.py @@ -0,0 +1,220 @@ +""" +backend/app/services/contract_payment/ledger_focus.py + +用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。 +依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。 +逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。 +""" + +from __future__ import annotations + +from collections import defaultdict +from datetime import date, datetime +from typing import Any, Iterable +from zoneinfo import ZoneInfo + +from sqlalchemy.orm import Query, Session +from sqlalchemy.sql.expression import false + +from app.models import ContractPaymentContract, ContractPaymentNode + +LEDGER_FOCUS_DUE = "due" +LEDGER_FOCUS_OVERDUE = "overdue" +LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion" +LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month" +LEDGER_FOCUS_VALUES = { + LEDGER_FOCUS_DUE, + LEDGER_FOCUS_OVERDUE, + LEDGER_FOCUS_NEEDS_COMPLETION, + LEDGER_FOCUS_DUE_THIS_MONTH, +} +_NEAR_DUE_DAYS = 7 +_SHANGHAI = ZoneInfo("Asia/Shanghai") + + +def business_today(*, today: date | None = None) -> date: + """ + 返回汇总卡使用的业务日(上海日历)。 + + Args: + today: 测试注入的业务日;缺省为 Asia/Shanghai 当天。 + Returns: + 用于 7 日内到期、逾期和本月判断的日期。 + """ + return today or datetime.now(_SHANGHAI).date() + + +def node_due_reference(due_date: date | None, anchor_date: date | None) -> date | None: + """ + 付款节点到期判断基准日。 + + 核心逻辑:与前台 paymentStatus.nodeDueReference 一致,优先 due_date,否则回退 anchor_date。 + Args: + due_date: 节点到期日。 + anchor_date: 节点锚点日。 + Returns: + 可用于比较的日期;两者皆空时为 None。 + """ + return due_date or anchor_date + + +def classify_ledger_status( + *, + contract_status: str | None, + parse_status: str | None, + nodes: Iterable[dict[str, Any]], + today: date, +) -> str: + """ + 按合同聚合出台账状态,与列表「状态」列一致。 + + 核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充; + 进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。 + Args: + contract_status: 合同主状态。 + parse_status: 解析状态。 + nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。 + today: 业务日。 + Returns: + overdue / due / active / completed / needs_completion。 + """ + node_list = list(nodes) + if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review": + return LEDGER_FOCUS_NEEDS_COMPLETION + if not node_list: + return LEDGER_FOCUS_NEEDS_COMPLETION + active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"] + if not active: + has_paid = any( + str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at")) + for node in node_list + ) + return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION + refs = [ + ref + for node in active + if (ref := node_due_reference(node.get("due_date"), node.get("anchor_date"))) + ] + if any((ref - today).days < 0 for ref in refs): + return LEDGER_FOCUS_OVERDUE + if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs): + return LEDGER_FOCUS_DUE + return "active" + + +def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool: + """ + 合同是否有未付节点的到期日落在本自然月。 + + 核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。 + Args: + nodes: 轻量节点 dict。 + today: 业务日,用于确定自然月。 + Returns: + 存在本月未付到期节点时为 True。 + """ + month_start = today.replace(day=1) + month_end = date(today.year + 1, 1, 1) if today.month == 12 else date(today.year, today.month + 1, 1) + for node in nodes: + if str(node.get("status") or "").strip().lower() != "active": + continue + ref = node_due_reference(node.get("due_date"), node.get("anchor_date")) + if ref and month_start <= ref < month_end: + return True + return False + + +def _node_payload(node: ContractPaymentNode) -> dict[str, Any]: + """把 ORM 节点收成分类所需的轻量字段。""" + return { + "status": node.status, + "due_date": node.due_date, + "anchor_date": node.anchor_date, + "paid_at": (node.evidence_json or {}).get("paid_at"), + } + + +def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict[str, set[int]]: + """ + 扫描全部已解析台账合同,按汇总卡口径收集合同 ID。 + + 核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。 + Args: + session: 当前请求的 SQLAlchemy 会话。 + today: 可选业务日。 + Returns: + 四个 focus 键到合同 ID 集合的映射。 + """ + as_of = business_today(today=today) + contracts = ( + session.query(ContractPaymentContract.id, ContractPaymentContract.status, ContractPaymentContract.parse_status) + .filter(ContractPaymentContract.parse_status == "parsed") + .all() + ) + buckets: dict[str, set[int]] = { + LEDGER_FOCUS_DUE: set(), + LEDGER_FOCUS_OVERDUE: set(), + LEDGER_FOCUS_NEEDS_COMPLETION: set(), + LEDGER_FOCUS_DUE_THIS_MONTH: set(), + } + if not contracts: + return buckets + contract_ids = [row.id for row in contracts] + nodes_by_contract: dict[int, list[dict[str, Any]]] = defaultdict(list) + node_rows = ( + session.query(ContractPaymentNode) + .filter(ContractPaymentNode.contract_id.in_(contract_ids)) + .all() + ) + for node in node_rows: + nodes_by_contract[node.contract_id].append(_node_payload(node)) + for row in contracts: + nodes = nodes_by_contract.get(row.id, []) + status = classify_ledger_status( + contract_status=row.status, + parse_status=row.parse_status, + nodes=nodes, + today=as_of, + ) + if status == LEDGER_FOCUS_DUE: + buckets[LEDGER_FOCUS_DUE].add(row.id) + elif status == LEDGER_FOCUS_OVERDUE: + buckets[LEDGER_FOCUS_OVERDUE].add(row.id) + elif status == LEDGER_FOCUS_NEEDS_COMPLETION: + buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id) + if has_unpaid_due_this_month(nodes, as_of): + buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id) + return buckets + + +def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[str, int]: + """ + 返回四张汇总卡的合同份数。 + + Args: + session: 当前请求的 SQLAlchemy 会话。 + today: 可选业务日。 + Returns: + due / overdue / needs_completion / due_this_month 的计数。 + """ + buckets = collect_ledger_focus(session=session, today=today) + return {key: len(ids) for key, ids in buckets.items()} + + +def apply_ledger_focus(query: Query, focus: str, *, session: Session, today: date | None = None) -> Query: + """ + 按汇总卡口径把台账查询限制到对应合同 ID。 + + 核心逻辑:空集合时强制无结果,避免 SQL IN () 退化成不过滤。 + Args: + query: 已按解析状态/关键词过滤的合同查询。 + focus: 四个合法口径之一。 + session: 当前请求的 SQLAlchemy 会话。 + today: 可选业务日。 + Returns: + 叠加 ID 过滤后的查询。 + """ + ids = collect_ledger_focus(session=session, today=today).get(focus) or set() + if not ids: + return query.filter(false()) + return query.filter(ContractPaymentContract.id.in_(ids)) diff --git a/backend/app/services/schedule/shipping_inventory_rpa_archive.py b/backend/app/services/schedule/shipping_inventory_rpa_archive.py index 17f56eb1..bfe3acf8 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_archive.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_archive.py @@ -1,10 +1,11 @@ """ backend/app/services/schedule/shipping_inventory_rpa_archive.py -用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。 +用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。 逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary; - query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。 + 企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」; + 完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。 """ from __future__ import annotations @@ -12,6 +13,7 @@ from __future__ import annotations import json import re import zipfile +from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -21,6 +23,7 @@ from app import db from app.core.errors import NotFoundError from app.models import ScheduleRun, ShippingInventoryFile from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task +from app.services.schedule.timezone_util import resolve_schedule_tzinfo _RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员" @@ -48,9 +51,63 @@ def get_inventory_archive_dir() -> str: return str(archive_dir) -def inventory_raw_zip_download_name(run_no: str) -> str: - """浏览器下载时使用的 ZIP 文件名。""" - return f"inventory-rpa-raw-{run_no}.zip" +def _attachment_when_from_run(run: ScheduleRun) -> datetime: + """ + 推导企微/下载展示名中的当地时刻。 + + 核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow; + 上述时刻在库内均为 UTC naive(含 run_no 时间戳),格式化前转到任务 + schedule_timezone(缺省 Asia/Shanghai)。完整 run_no 仍留在卡片与磁盘归档键。 + """ + when_utc: datetime | None = None + for value in (run.started_at, run.created_at, run.finished_at): + if isinstance(value, datetime): + when_utc = value + break + if when_utc is None: + match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip()) + if match: + try: + when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S") + except ValueError: + when_utc = None + if when_utc is None: + when_utc = datetime.now(timezone.utc).replace(tzinfo=None) + + task = getattr(run, "task", None) + tz_name = getattr(task, "schedule_timezone", None) if task is not None else None + tz = resolve_schedule_tzinfo(tz_name) + if when_utc.tzinfo is None: + when_utc = when_utc.replace(tzinfo=timezone.utc) + return when_utc.astimezone(tz) + + +def inventory_rpa_attachment_stem(run: ScheduleRun) -> str: + """ + 库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 + + Args: + run: 排程执行记录。 + + Returns: + 不含角色后缀与扩展名的展示名前缀。 + """ + when = _attachment_when_from_run(run) + return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" + + +def inventory_rpa_result_excel_name(run: ScheduleRun) -> str: + """库存 RPA 结果 Excel 的企微/下载展示名。""" + return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx" + + +def inventory_raw_zip_download_name(run: ScheduleRun) -> str: + """ + 库存 ZIP 的企微/浏览器下载展示名。 + + 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 + """ + return f"{inventory_rpa_attachment_stem(run)}-库存.zip" def _inventory_raw_zip_archive_path(run_no: str) -> Path: @@ -157,7 +214,6 @@ def persist_inventory_rpa_raw_zip_archive( index=zip_index, source_code=source_code, warehouse_id=warehouse_id, - inventory_file_no=inventory_file_no, original_suffix=storage_path.suffix or ".xlsx", ) archive.write(storage_path, arcname=entry_name) @@ -236,7 +292,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: if not _is_allowed_inventory_archive_path(zip_path): raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) - return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no) + return zip_path.resolve(), inventory_raw_zip_download_name(run) def _sanitize_zip_segment(value: str) -> str: @@ -245,25 +301,33 @@ def _sanitize_zip_segment(value: str) -> str: return cleaned or "unknown" +def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str: + """ + 包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。 + + warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。 + """ + source = str(source_code or "").strip() + if source: + return source + warehouse = str(warehouse_id or "").strip() + if warehouse and warehouse.lower() != "unknown": + return warehouse + return "inventory" + + def _build_zip_entry_name( *, index: int, source_code: str, warehouse_id: str, - inventory_file_no: str, original_suffix: str, ) -> str: - """生成 ZIP 内单文件条目名(不含目录)。""" - base = "_".join( - filter( - None, - [ - f"{index:03d}", - _sanitize_zip_segment(source_code), - _sanitize_zip_segment(warehouse_id), - _sanitize_zip_segment(inventory_file_no), - ], - ) - ) + """ + 生成 ZIP 内单文件条目名(不含目录)。 + + 核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。 + """ + label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id)) suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}" - return f"{base}{suffix}" + return f"{index:03d}_{label}{suffix}" diff --git a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py index 899a6768..077a42c9 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py @@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl( errors.append(f"Excel导出失败: {excel_exc}") if status == "success": status = "partial_failed" + else: + # 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 + from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name + + file_name = inventory_rpa_result_excel_name(run) step_logs = list(run.step_logs or []) step_logs.append({ diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_region_text.py b/backend/app/services/shipping_notice/document_layout/coordinate_region_text.py index d4c53743..cd35c320 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_region_text.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_region_text.py @@ -3,13 +3,61 @@ services/shipping_notice/document_layout/coordinate_region_text.py 用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。 依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。 -逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。 +逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则; + 另提供单逻辑表头折行合并(x 回退副标签并入最近列,不拆成新身份列)。 """ from __future__ import annotations from typing import Any, Literal +# 单逻辑表头:列中心相对页宽回退超过该阈值,视为同列折行副标签。 +_HEADER_CENTER_X_REGRESSION_TOLERANCE = 0.02 + + +def merge_header_identity_wrap_tokens( + tokens: list[str], + centers: list[float] | None, + widths: list[float] | None = None, +) -> tuple[list[str], list[float] | None, list[float] | None]: + """ + 将单逻辑表头中的折行副标签并入所属列,保留文案、不新增身份列。 + + 核心逻辑:主行列中心近似单调递增;若下一 token 的中心明显回退,则并入与其 + x 最近的已有列(如 Part Number 下 Vendor Item#、Requested Arrival 下 Date)。 + 多行正式表头不要调用本函数。 + + Args: + tokens: 按阅读序的 header_tokens(可含第二视觉行)。 + centers: 与 tokens 对齐的列中心(0..1);缺失或长度不一致时原样返回。 + widths: 可选列宽比;对齐时随列保留(被并入列沿用主行宽度)。 + + Returns: + 合并后的 (tokens, centers, widths)。 + """ + if not tokens or not centers or len(centers) != len(tokens): + return tokens, centers, widths + has_widths = isinstance(widths, list) and len(widths) == len(tokens) + merged_tokens: list[str] = [] + merged_centers: list[float] = [] + merged_widths: list[float] | None = [] if has_widths else None + max_center = float('-inf') + for index, token in enumerate(tokens): + center = float(centers[index]) + if merged_centers and center < max_center - _HEADER_CENTER_X_REGRESSION_TOLERANCE: + parent = min( + range(len(merged_centers)), + key=lambda item: abs(merged_centers[item] - center), + ) + merged_tokens[parent] = f'{merged_tokens[parent]} {token}'.strip() + continue + merged_tokens.append(str(token)) + merged_centers.append(center) + if merged_widths is not None: + merged_widths.append(float(widths[index])) + max_center = max(max_center, center) + return merged_tokens, merged_centers, merged_widths + def render_positioned_row( glyphs: list[Any], *, geometry_gap_limit: float | None = None, 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 271e6ba1..306a362a 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 @@ -153,10 +153,13 @@ def reconstruct_coordinate_profile_rows_with_strategy( coordinate_transform: dict[str, Any] | None = None, page_no: int = 1, ) -> tuple[list['CoordinateProfileLogicalRow'], Any]: - """统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。""" - from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( - resolve_runtime_parse_strategy, - ) + """统一评估 fixed/adaptive/dynamic,并返回坐标明细与策略结果。 + + 核心逻辑:三种重建模式都跑一遍再交给策略裁决;``selected`` 时只返回被选中模式。 + 策略为 ``needs_review`` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/ + 验证人工核对;正式自动建单路径必须自行检查 ``strategy.status == 'selected'``。 + """ + from app.services.shipping_notice.document_layout import runtime_parse_strategy as parse_strategy fixed_rows = reconstruct_coordinate_profile_rows( characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, @@ -197,20 +200,23 @@ def reconstruct_coordinate_profile_rows_with_strategy( for row in rows ] - strategy = resolve_runtime_parse_strategy( + strategy = parse_strategy.resolve_runtime_parse_strategy( page_glyphs={str(page_no): characters}, fixed_rows=strategy_rows(fixed_rows), adaptive_rows=strategy_rows(adaptive_rows), dynamic_rows=strategy_rows(dynamic_rows), ) - if strategy.status != 'selected' or strategy.row_mode is None: - return [], strategy - return ( - fixed_rows if strategy.row_mode == 'fixed_subrows' - else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' - else dynamic_rows, - strategy, - ) + if strategy.status == 'selected' and strategy.row_mode is not None: + return ( + fixed_rows if strategy.row_mode == 'fixed_subrows' + else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' + else dynamic_rows, + strategy, + ) + # 策略需复核时仍返回最佳努力明细,供盲测/验证人工核对;正式自动建单仍以 + # strategy.status == 'selected' 为准,不得把 fallback 当成可自动建单结果。 + fallback = fixed_rows or adaptive_rows or dynamic_rows + return fallback, strategy def resolve_line_start_field_code(value: Any = None) -> 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 683492c5..bddf94b0 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -6,6 +6,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py 逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费 DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成 matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。 + 表区 region_role 区分主明细与同文档 LN 补料号补充表(line_field_supplement)。 """ from __future__ import annotations @@ -259,6 +260,8 @@ class TableRegionProfile(OrderProfileModel): page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages' page_no: int | None = Field(default=None, ge=1) region: RelativeRegion + # business_lines=主明细命中源;line_field_supplement=同文档按 LN 补料号(如 COO),不进业务表匹配。 + region_role: Literal['business_lines', 'line_field_supplement'] = 'business_lines' # 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。 line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') # 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。 @@ -304,6 +307,22 @@ class TableRegionProfile(OrderProfileModel): field.field_code for field in self.line_layouts[0].field_regions }: raise ValueError('main line layout must bind the configured line-start field') + if self.region_role == 'line_field_supplement': + # 补充表只允许起行 + 客户料号/Vendor,禁止绑数量金额等以免误当业务明细。 + bound = { + field.field_code + for item in self.line_layouts + for field in item.field_regions + } + if not self.line_start_field_code or self.line_start_field_code not in bound: + raise ValueError('line_field_supplement requires the configured line-start field') + allowed = {self.line_start_field_code, 'customer_part_number', 'part_number'} + extra = sorted(bound - allowed) + if extra: + raise ValueError( + 'line_field_supplement may only bind line-start and part number fields; ' + f'unexpected: {", ".join(extra)}' + ) # A physical text band must have exactly one layout interpretation. Allowing # overlapping header/line regions would reintroduce the cross-row ambiguity # that v2 coordinate profiles are intended to eliminate. @@ -505,6 +524,11 @@ class OrderCoordinateProfile(OrderProfileModel): ids = [item.region_id for item in self.table_regions] if len(ids) != len(set(ids)): raise ValueError('table region ids must be unique') + if not any( + str(getattr(item, 'region_role', None) or 'business_lines') == 'business_lines' + for item in self.table_regions + ): + raise ValueError('at least one business_lines table region is required') for index, left in enumerate(self.table_regions): for right in self.table_regions[index + 1:]: # Different exact pages may use identical coordinates without competing at runtime. 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 c00706d5..457eee5e 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 @@ -5,8 +5,12 @@ services/shipping_notice/document_layout/order_profile_matcher.py 依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。 逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜; table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column; + 主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠; + 无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient; + 身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底; 主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表; - 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。 + 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁; + 单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。 """ from __future__ import annotations @@ -19,6 +23,7 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field from app.services.shipping_notice.document_layout.coordinate_region_text import ( + merge_header_identity_wrap_tokens, positioned_token_spans, read_coordinate_region_text, visual_glyph_rows, @@ -44,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import # 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义, # 避免无意义的版本兼容分支。 LAYOUT_MATCHING_FEATURES_VERSION = 'v1' +# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。 +_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5 def _anchor_comparable_text(value: Any) -> str: @@ -284,7 +291,12 @@ def match_frozen_coordinate_profiles( candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6) if not hard_valid: - if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered): + # [STEP] 仅当全部候选都缺关键坐标结构时才抬升 evidence_insufficient; + # 禁止无关远亲候选的坐标码掩盖近亲模板的真实 header/topology 冲突。 + if rendered and all( + 'profile_coordinate_evidence_unavailable' in item.reason_codes + for item in rendered + ): return ProfileMatchResult( status='evidence_insufficient', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin, @@ -960,13 +972,11 @@ def _score_header_semantic_position( """比对真实表头 token、横向顺序和位置。 核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。 + 期望侧先截断单逻辑表头的折行副标签污染。 """ if signature is None: return MatchDimensionResult(state='unavailable', score=0.0) - expected_tokens: list[str] = [] - for table in signature.get('table_patterns') or []: - if isinstance(table, dict): - expected_tokens.extend(str(item).casefold() for item in table.get('header_tokens') or []) + expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)] observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []] required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0 if not expected_tokens: @@ -986,7 +996,7 @@ def _score_header_semantic_position( 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 []] + expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)] observed_order = observed.get('header_tokens') or [] shared = [item for item in expected_order if item in observed_order] order_ratio = 1.0 @@ -1006,20 +1016,80 @@ def _score_header_semantic_position( _HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'}) _HEADER_ATOM_MIN_LEN = 3 +_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]') + + +def _sanitize_signature_table_identity( + pattern: dict[str, Any], +) -> tuple[list[str], list[float] | None, list[float] | None]: + """ + 按需合并单逻辑表头签名中的折行副标签。 + + 核心逻辑:header_row_count==1 时按 column_centers 回退把副标签并入最近列; + 多行正式表头原样返回。兼容尚未重冻、仍把 Vendor Item#/Date 列为独立 token 的旧签名。 + """ + raw_tokens = [str(item) for item in pattern.get('header_tokens') or []] + centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else None + widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else None + try: + center_values = [float(item) for item in centers] if centers is not None else None + except (TypeError, ValueError): + center_values = None + try: + width_values = [float(item) for item in widths] if widths is not None else None + except (TypeError, ValueError): + width_values = None + if int(pattern.get('header_row_count') or 1) > 1: + return raw_tokens, center_values, width_values + return merge_header_identity_wrap_tokens(raw_tokens, center_values, width_values) + + +def _signature_identity_header_tokens(signature: dict[str, Any] | None) -> list[str]: + """读取截断折行副标签后的签名表头身份 token。""" + tokens: list[str] = [] + for pattern in (signature or {}).get('table_patterns') or []: + if isinstance(pattern, dict): + trimmed, _, _ = _sanitize_signature_table_identity(pattern) + tokens.extend(trimmed) + return tokens + + +def _signature_identity_header_order(signature: dict[str, Any] | None) -> list[str]: + """读取合并折行后的 header_order;与身份 token 对齐。""" + ordered: list[str] = [] + for pattern in (signature or {}).get('table_patterns') or []: + if not isinstance(pattern, dict): + continue + tokens, _, _ = _sanitize_signature_table_identity(pattern) + ordered.extend(tokens) + return ordered + + +def _signature_single_logical_header(signature: dict[str, Any] | None) -> bool: + """签名是否全部为逻辑一行表头(可含格内折行)。""" + patterns = [ + item for item in (signature or {}).get('table_patterns') or [] + if isinstance(item, dict) + ] + if not patterns: + return True + return all(int(item.get('header_row_count') or 1) <= 1 for item in patterns) def _header_token_atoms(tokens: list[str]) -> frozenset[str]: """ 将表头 token 拆成稳定原子,供无锚点近亲模板互斥。 - 核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。 + 核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时 + 仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。 """ + joined = ' '.join(str(token) for token in tokens) + normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold()) + normalized = re.sub(r"['’]", '', normalized) 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) + 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) @@ -1031,10 +1101,7 @@ def _header_discriminator_atoms_conflict( """签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。""" 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 []) + expected_tokens = _signature_identity_header_tokens(signature) observed_tokens = [str(item) for item in observed.get('header_tokens') or []] if not expected_tokens or not observed_tokens: return False @@ -1075,9 +1142,15 @@ def _score_column_topology( for pattern, expected in zip(patterns, expected_counts): if expected <= 0: continue - count_score = min(observed_count, expected) / max(observed_count, expected) - expected_centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else [] - expected_widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else [] + tokens, expected_centers_raw, expected_widths_raw = _sanitize_signature_table_identity(pattern) + expected_identity_count = len(tokens) or expected + count_score = min(observed_count, expected_identity_count) / max(observed_count, expected_identity_count) + expected_centers = expected_centers_raw if isinstance(expected_centers_raw, list) else [] + expected_widths = expected_widths_raw if isinstance(expected_widths_raw, list) else [] + if not expected_centers and isinstance(pattern.get('column_centers'), list): + expected_centers = pattern.get('column_centers') or [] + if not expected_widths and isinstance(pattern.get('column_width_ratios'), list): + expected_widths = pattern.get('column_width_ratios') or [] if expected_centers and observed_centers: center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08) width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0 @@ -1261,10 +1334,11 @@ def _observe_layout_features( if width > 0 and height > 0: aspect_ratio = width / height - # [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0] - # 可能是抬头/元数据表,不能作为运行时默认主表。 + # [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的 + # tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。 primary_bbox = _select_signature_primary_table_bbox( tables=tables, pages=pages, signature=signature, + page_glyphs=page_glyphs, glyph_tables=glyph_tables, ) # [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。 primary_bbox = _clip_observed_primary_table_bbox( @@ -1373,18 +1447,8 @@ def _select_persisted_header_candidate( *, candidates: list[dict[str, Any]], signature: dict[str, Any] | None, ) -> tuple[dict[str, Any], list[float]] | None: """按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。""" - expected_tokens = [ - str(token).casefold() - for pattern in (signature or {}).get('table_patterns') or [] - if isinstance(pattern, dict) - for token in pattern.get('header_tokens') or [] - ] - expected_order = [ - str(token).casefold() - for pattern in (signature or {}).get('table_patterns') or [] - if isinstance(pattern, dict) - for token in pattern.get('header_order') or [] - ] + expected_tokens = [str(token).casefold() for token in _signature_identity_header_tokens(signature)] + expected_order = [str(token).casefold() for token in _signature_identity_header_order(signature)] expected_centers = _signature_column_values(signature or {}, 'column_centers') expected_widths = _signature_column_values(signature or {}, 'column_width_ratios') if not expected_tokens or not expected_centers: @@ -1420,9 +1484,21 @@ def _select_persisted_header_candidate( def _select_signature_primary_table_bbox( - *, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None, + *, + tables: list[dict[str, Any]], + pages: dict[str, Any], + signature: dict[str, Any] | None, + page_glyphs: dict[str, Any] | None = None, + glyph_tables: dict[str, Any] | None = None, ) -> list[float] | None: - """按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。""" + """ + 选取运行时主表框:签名表头亲和度优先,其次表区重叠;无签名时首表兼容。 + + 核心逻辑:MinerU 常把右上角 ORDER DATE/NO 等 KV 块拆成独立表且排在 tables[0]; + 仅靠 bbox 重叠在全页 glyphs 场景下仍可能读错表头。对每个候选表顶部观测 header + atoms,与签名 identity header 算交集占比;占比 ≥ 阈值时优先该表,并列再比 + table_patterns.bbox.median 重叠。 + """ normalized_tables: list[list[float]] = [] for table in tables: page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1) @@ -1448,22 +1524,99 @@ def _select_signature_primary_table_bbox( and isinstance(item['bbox'].get('median'), list) and len(item['bbox']['median']) == 4 ] - if not patterns: - return normalized_tables[0] - best_bbox = normalized_tables[0] - best_overlap = -1.0 - for candidate in normalized_tables: + expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature)) + glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {} + table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {} + + def _best_pattern_overlap(candidate: list[float]) -> float: + best = -1.0 for pattern in patterns: try: expected = [float(value) for value in pattern['bbox']['median']] except (TypeError, ValueError): continue - overlap = _bbox_overlap(expected, candidate) - if overlap > best_overlap: - best_overlap, best_bbox = overlap, candidate + best = max(best, _bbox_overlap(expected, candidate)) + return best + + if expected_atoms and (glyph_pages or table_glyph_map): + affinity_scored: list[tuple[float, float, list[float]]] = [] + for candidate in normalized_tables: + tokens = _header_tokens_for_table_bbox( + bbox=candidate, + tables=tables, + pages=pages, + page_glyphs=glyph_pages, + glyph_tables=table_glyph_map, + ) + observed_atoms = _header_token_atoms(tokens) + affinity = ( + len(observed_atoms & expected_atoms) / len(expected_atoms) + if expected_atoms else 0.0 + ) + affinity_scored.append((affinity, _best_pattern_overlap(candidate), candidate)) + affinity_scored.sort(key=lambda item: (item[0], item[1])) + best_affinity, best_overlap, best_bbox = affinity_scored[-1] + if best_affinity >= _PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM: + return best_bbox + if not patterns: + return best_bbox if best_affinity > 0 else normalized_tables[0] + + if not patterns: + return normalized_tables[0] + best_bbox = normalized_tables[0] + best_overlap = -1.0 + for candidate in normalized_tables: + overlap = _best_pattern_overlap(candidate) + if overlap > best_overlap: + best_overlap, best_bbox = overlap, candidate return best_bbox +def _header_tokens_for_table_bbox( + *, + bbox: list[float], + tables: list[dict[str, Any]], + pages: dict[str, Any], + page_glyphs: dict[str, Any], + glyph_tables: dict[str, Any], +) -> list[str]: + """ + 在候选表顶部条带观测表头 token,供主表亲和度打分。 + + 核心逻辑:取相对坐标表框顶边向下 max(6%, 18% 表高) 的条带,用页级 glyphs + (不足时回退 table glyphs)拼 token;不做折行合并,仅服务选表。 + """ + if not isinstance(bbox, list) or len(bbox) != 4: + return [] + page_no, page = _page_for_primary_table_bbox(bbox, tables=tables, pages=pages) + if not isinstance(page, dict): + return [] + glyphs = None + if page_no is not None: + glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) + if not isinstance(glyphs, list) or not glyphs: + glyphs = page_glyphs.get('1') or page_glyphs.get(1) or [] + if not isinstance(glyphs, list) or not glyphs: + glyphs = [] + for table_glyphs in glyph_tables.values(): + if isinstance(table_glyphs, list): + glyphs.extend(table_glyphs) + if not glyphs: + return [] + region = { + 'x0': float(bbox[0]), + 'y0': float(bbox[1]), + 'x1': float(bbox[2]), + 'y1': float(bbox[1]) + max(0.06, (float(bbox[3]) - float(bbox[1])) * 0.18), + } + header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region) + spans = [ + item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False) + if _usable_observed_header_token(str(item.get('text') or '')) + ][:32] + return [' '.join(str(item['text']).split())[:80].casefold() for item in spans] + + def _clip_observed_primary_table_bbox( primary_bbox: list[float] | None, *, @@ -1566,26 +1719,62 @@ 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 是否足以代表签名表头。 +def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None: + """读取签名首个可用 table_patterns.bbox.median(归一化四点)。""" + for pattern in (signature or {}).get('table_patterns') or []: + if not isinstance(pattern, dict): + continue + bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None + if not isinstance(bbox, dict): + continue + median = bbox.get('median') + if isinstance(median, list) and len(median) == 4: + try: + return [float(item) for item in median] + except (TypeError, ValueError): + continue + return None - 只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”, - 直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行) - 需要回退到表体顶部的结构搜索。 + +def _align_signature_header_bbox_to_primary( + *, + signature: dict[str, Any] | None, + primary_bbox: list[float], +) -> list[float] | None: """ - 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 + 将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。 + + 核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0 + 平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。 + """ + if not isinstance(primary_bbox, list) or len(primary_bbox) != 4: + return None + header_bbox = _signature_header_bbox(signature) + if header_bbox is None: + return None + table_median = _signature_table_bbox_median(signature) + try: + hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4)) + py0, py1 = float(primary_bbox[1]), float(primary_bbox[3]) + except (TypeError, ValueError, IndexError): + return None + if hy1 <= hy0 or py1 <= py0: + return None + delta_y = 0.0 + if table_median is not None: + try: + delta_y = py0 - float(table_median[1]) + except (TypeError, ValueError, IndexError): + delta_y = 0.0 + aligned_y0 = hy0 + delta_y + aligned_y1 = hy1 + delta_y + # [STEP] 夹在主表内;保持最小可读高度。 + height = max(0.02, aligned_y1 - aligned_y0) + clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height)) + clipped_y1 = min(clipped_y0 + height, py1) + if clipped_y1 <= clipped_y0: + return None + return [hx0, clipped_y0, hx1, clipped_y1] def _observe_primary_table_header( @@ -1596,12 +1785,12 @@ def _observe_primary_table_header( primary_bbox: list[float] | None, signature: dict[str, Any] | None, ) -> tuple[list[str], list[float], list[float]]: - """从实际主表顶部观测表头,与签名生成保持同一证据口径。 + """ + 从对齐身份窗口观测表头,与签名生成保持同一证据口径。 - 先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为, - 不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到 - 错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑), - 从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。 + 核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框 + 时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行 + 宽带搜索,避免印刷括号注记污染身份原子。 """ if not primary_bbox or len(primary_bbox) != 4: return [], [], [] @@ -1614,14 +1803,23 @@ def _observe_primary_table_header( page = pages.get('1') or pages.get(1) if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict): return [], [], [] - header_bbox = _signature_header_bbox(signature) - region = ( - {'x0': header_bbox[0], 'y0': header_bbox[1], 'x1': header_bbox[2], 'y1': header_bbox[3]} - if header_bbox is not None else { - 'x0': primary_bbox[0], 'y0': primary_bbox[1], 'x1': primary_bbox[2], - 'y1': primary_bbox[1] + max(0.06, (primary_bbox[3] - primary_bbox[1]) * 0.18), - } + aligned = _align_signature_header_bbox_to_primary( + signature=signature, primary_bbox=primary_bbox, ) + if aligned is not None: + region = { + 'x0': float(aligned[0]), 'y0': float(aligned[1]), + 'x1': float(aligned[2]), 'y1': float(aligned[3]), + } + else: + region = { + 'x0': float(primary_bbox[0]), + 'y0': float(primary_bbox[1]), + 'x1': float(primary_bbox[2]), + 'y1': float(primary_bbox[1]) + max( + 0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18, + ), + } width = float(page.get('width') or 0) if width <= 0: return [], [], [] @@ -1632,28 +1830,68 @@ def _observe_primary_table_header( ][:32] 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) - 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 + table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001) + band_widths = [ + round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans + ] + if _signature_single_logical_header(signature): + merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens( + band_tokens, band_centers, band_widths, + ) return ( - [str(token).casefold() for token in header['header_tokens']], - header['column_centers'], header['column_width_ratios'], + [str(item).casefold() for item in merged_tokens], + list(merged_centers or []), + list(merged_widths or []), ) return band_tokens, band_centers, band_widths +def _merge_following_wrap_candidate( + *, + header: dict[str, Any], + header_candidates: list[dict[str, Any]], +) -> tuple[list[str], list[float], list[float]]: + """ + 将选中主表头行与紧邻下一视觉行合并(折行副标签)。 + + 核心逻辑:下一行 token 的列中心若相对主行回退,merge_header_identity_wrap_tokens + 会把它们并入所属列;若不构成回退则合并结果与主行等价或略增列,仍可安全返回。 + """ + tokens = [str(token).casefold() for token in header.get('header_tokens') or []] + centers = [float(item) for item in header.get('column_centers') or []] + widths = [float(item) for item in header.get('column_width_ratios') or []] + header_y1 = float((header.get('bbox') or [0, 0, 0, 0])[3]) + following = None + for candidate in header_candidates: + if candidate is header: + continue + bbox = candidate.get('bbox') if isinstance(candidate.get('bbox'), list) else None + if not bbox or len(bbox) != 4: + continue + y0 = float(bbox[1]) + if y0 + 1e-6 < header_y1: + continue + if following is None or y0 < float(following['bbox'][1]): + following = candidate + if following is None: + return tokens, centers, widths + wrap_tokens = [str(token).casefold() for token in following.get('header_tokens') or []] + wrap_centers = [float(item) for item in following.get('column_centers') or []] + wrap_widths = [float(item) for item in following.get('column_width_ratios') or []] + if not wrap_tokens or len(wrap_tokens) != len(wrap_centers): + return tokens, centers, widths + merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens( + tokens + wrap_tokens, + centers + wrap_centers, + widths + wrap_widths if len(widths) == len(tokens) else None, + ) + return ( + [str(item).casefold() for item in merged_tokens], + list(merged_centers or []), + list(merged_widths or []), + ) + + def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None: """读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。""" for pattern in (signature or {}).get('table_patterns') or []: @@ -1690,9 +1928,15 @@ def _usable_observed_header_token(token: str) -> bool: def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]: - """读取签名中首个可用表格的列结构向量。""" + """读取签名中首个可用表格的列结构向量,单逻辑表头时合并折行副标签后再取。""" for pattern in signature.get('table_patterns') or []: - if isinstance(pattern, dict) and isinstance(pattern.get(key), list): + if not isinstance(pattern, dict): + continue + _, centers, widths = _sanitize_signature_table_identity(pattern) + selected = centers if key == 'column_centers' else widths if key == 'column_width_ratios' else None + if isinstance(selected, list) and selected: + return list(selected) + if isinstance(pattern.get(key), list): try: return [float(item) for item in pattern[key]] except (TypeError, ValueError): 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 26a26c88..681e5ff0 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 @@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_parse_validation.py 依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。 逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent; 返回 passed/reason_codes/metrics 供 unique_match 二次裁决。 + 类型 sanity 接受 MM/DD/YY;字段覆盖仅统计 business_lines。 """ from __future__ import annotations @@ -26,8 +27,9 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio _NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$') +# Hyve 等 PO 常见 MM/DD/YY;亦接受 YYYY-MM-DD / MM/DD/YYYY。 _DATE_PATTERN = re.compile( - r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$', + r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})$', ) @@ -94,8 +96,13 @@ def validate_profile_parse_candidate( ) # [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报) + # 补充表不参与发布解析门禁的字段覆盖/类型检查(正式路径另行按 LN 合并)。 + business_tables = [ + table for table in profile.table_regions + if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines' + ] line_fields = [ - field for table in profile.table_regions for layout in table.line_layouts + field for table in business_tables for layout in table.line_layouts for field in layout.field_regions if field.scope == 'line' ] line_coverage = _line_region_coverage_shift_tolerant( @@ -130,7 +137,7 @@ def validate_profile_parse_candidate( required_line_codes = { field.field_code - for table in profile.table_regions + for table in business_tables for layout in table.line_layouts for field in layout.field_regions if field.scope == 'line' @@ -245,8 +252,13 @@ def _line_region_coverage_shift_tolerant( """ if not profile.table_regions: return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} + business_tables = [ + table for table in profile.table_regions + if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines' + ] + tables_for_lines = business_tables or list(profile.table_regions) line_fields = [ - field for table in profile.table_regions for layout_item in table.line_layouts + field for table in tables_for_lines for layout_item in table.line_layouts for field in layout_item.field_regions if field.scope == 'line' ] if not line_fields: @@ -254,9 +266,9 @@ def _line_region_coverage_shift_tolerant( 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 上的物理表;取重叠面积最大者。 + # 定位与主表区(首个 business_lines 且含 line_layouts)重叠且在 page 上的物理表;取重叠面积最大者。 primary_region = next( - (table for table in profile.table_regions if table.line_layouts), None, + (table for table in tables_for_lines if table.line_layouts), None, ) raw_table = _locate_overlapping_raw_table( primary_region=primary_region, layout=layout, page=page, profile=profile, 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 75c831b8..6143df48 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 @@ -5,6 +5,8 @@ services/shipping_notice/document_layout/order_profile_signature.py 依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。 逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。 另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。 + 单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。 + table_patterns 仅纳入 business_lines;line_field_supplement 不进匹配身份。 """ from __future__ import annotations @@ -16,6 +18,7 @@ import statistics from typing import Any from app.services.shipping_notice.document_layout.coordinate_region_text import ( + merge_header_identity_wrap_tokens, positioned_token_spans, read_coordinate_region_text, visual_glyph_rows, @@ -196,8 +199,9 @@ def build_layout_signature( """ 生成版面签名快照;相同输入必须得到相同 checksum。 - 核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合 - 中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。 + 核心逻辑:解析模板表区/表头/字段关系 → 仅对 business_lines 建 table_patterns → + 从样本区域读取固定文字 → 多样本聚合中位数与容差 → 过滤动态值与单样本噪声 → + 计算稳定 checksum。line_field_supplement 只服务按 LN 补料号,不进匹配身份。 Args: definition: 当前草稿或冻结 Profile 定义 JSON。 @@ -223,11 +227,15 @@ def build_layout_signature( order_field_layouts=definition.get('order_field_layouts') or [], ) - # [STEP 2] 页面与表区几何模式 + # [STEP 2] 页面与主表明细几何模式(排除 line_field_supplement) page_patterns = _build_page_patterns(sample_layouts=sample_layouts) + matching_tables = [ + table for table in profile.table_regions + if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines' + ] table_patterns = [ _build_table_pattern(table=table, sample_layouts=sample_layouts) - for table in profile.table_regions + for table in matching_tables ] field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts) evidence_quality = _build_evidence_quality( @@ -353,12 +361,15 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) -> default=0, ) + # 1 个 header_layout = 逻辑一行表头(可含格内折行);多 layout 才是多行正式表头。 + single_logical_header_row = len(header_layouts) <= 1 for layout in sample_layouts: observed = _observe_sample_table( layout, target_region=region, header_region=header_region, table_region=table, + single_logical_header_row=single_logical_header_row, ) if observed is None: continue @@ -433,6 +444,7 @@ def _observe_sample_table( layout: dict[str, Any], *, target_region: RelativeRegion, header_region: RelativeRegion | None, table_region: Any | None = None, + single_logical_header_row: bool = True, ) -> dict[str, Any] | None: """读取样本中与标注区域重叠最高的真实表格及其页级字符几何。""" tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] @@ -469,7 +481,10 @@ def _observe_sample_table( table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox, ) header_tokens, centers, widths = _header_observation( - header_glyphs, page=page, bbox=bbox, + header_glyphs, + page=page, + bbox=bbox, + single_logical_header_row=single_logical_header_row, ) header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None termination_rules = [ @@ -556,9 +571,18 @@ def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | N def _header_observation( - glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float], + glyphs: list[dict[str, Any]], + *, + page: dict[str, Any], + bbox: list[float], + single_logical_header_row: bool = True, ) -> tuple[list[str], list[float], list[float]]: - """从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。""" + """ + 从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。 + + 核心逻辑:读出带内全部视觉行后,对逻辑一行表头按列中心回退把折行副标签并入 + 所属列(保留 Vendor Item# / Date 文案);多行正式表头不做合并。 + """ try: page_width = float(page['width']) except (KeyError, TypeError, ValueError): @@ -571,6 +595,15 @@ def _header_observation( centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans] span = max(bbox[2] - bbox[0], 0.0001) widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans] + if single_logical_header_row: + merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens( + tokens, centers, widths, + ) + return ( + list(merged_tokens), + list(merged_centers or []), + list(merged_widths or []), + ) return tokens, centers, widths diff --git a/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py index f4b2e295..ead9d6d5 100644 --- a/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py +++ b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py @@ -3,7 +3,8 @@ services/shipping_notice/document_layout/runtime_parse_strategy.py 用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。 依赖:仅标准库;由正式抽取与模板质量验证共同调用。 -逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。 +逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用; + 二者业务值冲突时,若动态列能单侧确认其一则采用该侧(或更完整的动态结果),否则转 Review。 """ from __future__ import annotations @@ -75,6 +76,15 @@ def resolve_runtime_parse_strategy( baseline_rows = fixed_valid baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) else: + # [STEP] 固定/自适应业务值冲突:不得静默猜一侧;若动态列能单侧确认,再落选。 + resolved = _resolve_fixed_adaptive_ambiguity_with_dynamic( + page_nos=page_nos, + fixed_rows=fixed_valid, + adaptive_rows=adaptive_valid, + dynamic_rows=dynamic_valid, + ) + if resolved is not None: + return resolved return RuntimeParseStrategy( 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), ) @@ -103,6 +113,67 @@ def resolve_runtime_parse_strategy( ) +def _resolve_fixed_adaptive_ambiguity_with_dynamic( + *, + page_nos: tuple[int, ...], + fixed_rows: list[dict[str, Any]], + adaptive_rows: list[dict[str, Any]], + dynamic_rows: list[dict[str, Any]], +) -> RuntimeParseStrategy | None: + """ + 固定与自适应冲突时,用动态列做单侧确认。 + + 核心逻辑:动态相对某一侧可覆盖(baseline/dynamic preferred),且相对另一侧 + 仍 ambiguous,则采用被确认的一侧;两侧都被动态确认且动态更完整时采用动态。 + 无动态证据或仍双边不清时返回 None,由调用方转 Review。 + + Args: + page_nos: 当前有坐标证据的页码。 + fixed_rows: 有效固定子行。 + adaptive_rows: 有效自适应行。 + dynamic_rows: 有效动态列行;空则无法仲裁。 + + Returns: + 可安全选中的策略;无法仲裁时为 None。 + """ + if not dynamic_rows: + return None + fixed_vs_dyn = _compare_dynamic_row_coverage( + baseline_rows=fixed_rows, dynamic_rows=dynamic_rows, + ) + adaptive_vs_dyn = _compare_dynamic_row_coverage( + baseline_rows=adaptive_rows, dynamic_rows=dynamic_rows, + ) + fixed_ok = fixed_vs_dyn != 'ambiguous' + adaptive_ok = adaptive_vs_dyn != 'ambiguous' + if fixed_ok and adaptive_ok: + if fixed_vs_dyn == 'dynamic_preferred' or adaptive_vs_dyn == 'dynamic_preferred': + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + # 动态完整覆盖两侧且无额外行:冲突本身未消除,不能借动态消歧。 + return None + if fixed_ok and not adaptive_ok: + if fixed_vs_dyn == 'dynamic_preferred': + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + return RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + if adaptive_ok and not fixed_ok: + if adaptive_vs_dyn == 'dynamic_preferred': + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + return RuntimeParseStrategy( + 'selected', page_nos, 'adaptive_record_columns', + ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',), + ) + return None + + def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]: """为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。 @@ -210,29 +281,33 @@ def _compare_row_field_completeness( def _compare_dynamic_row_coverage( *, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]], ) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']: - """仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。""" + """仅当动态结果无冲突地覆盖基线,并额外恢复记录或严格加长字段值时才切换策略。""" if len(dynamic_rows) < len(baseline_rows): return 'baseline_preferred' remaining = [_row_fields(row) for row in dynamic_rows] + extended = False for baseline in baseline_rows: baseline_fields = _row_fields(baseline) matches = [] for index, dynamic_fields in enumerate(remaining): if not baseline_fields.keys() <= dynamic_fields.keys(): continue - if all( - dynamic_fields[code] == value - or ( - dynamic_fields[code].startswith(value) - and len(dynamic_fields[code]) > len(value) - ) - for code, value in baseline_fields.items() - ): + compatible = True + for code, value in baseline_fields.items(): + dyn_value = dynamic_fields[code] + if dyn_value == value: + continue + if dyn_value.startswith(value) and len(dyn_value) > len(value): + extended = True + continue + compatible = False + break + if compatible: matches.append(index) if len(matches) != 1: return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred' remaining.pop(matches[0]) - return 'dynamic_preferred' if remaining else 'baseline_preferred' + return 'dynamic_preferred' if remaining or extended else 'baseline_preferred' def _row_fields(row: dict[str, Any]) -> dict[str, str]: 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 6c3a2a49..51d89685 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -2,9 +2,11 @@ services/shipping_notice/document_profile_quality_service.py 用途:治理订单文档 Profile 的盲测候选、样本、执行结果和确定性自动建单资格。 -依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、Profile 纯解析器与质量 ORM 模型。 +依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、坐标重建与运行时策略、Profile 纯解析器与质量 ORM 模型。 逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对; 共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验; + 策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected; + 盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号; 盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。 """ @@ -41,7 +43,6 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import from app.services.shipping_notice.document_layout.order_field_extraction import ( _is_placeholder_anchor_text, extract_order_fields, ) -from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.order_document_profile_service import ( @@ -51,7 +52,7 @@ from app.services.shipping_notice.order_document_profile_service import ( from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.reservation_region import ( apply_reservation_region_candidates, - extract_reservation_from_region_text, + reservation_region_candidates_from_layout, ) @@ -378,6 +379,17 @@ def _candidate_for_sample( evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list): raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + # 明细页坐标可能尚未因订单头字段补齐;盲测重建前先确保表所在页有整页证据。 + if isinstance(raw_table, dict): + try: + table_page_no = int(raw_table.get('page_no') or 1) + except (TypeError, ValueError): + table_page_no = 1 + if table_page_no > 0: + layout = _ensure_page_coordinate_evidence( + document=document, layout=layout, page_no=table_page_no, + ) + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} if not any(isinstance(value, list) and value for value in page_glyphs.values()): @@ -388,6 +400,9 @@ def _candidate_for_sample( # layout. They are valid template regions, but cannot reconstruct rows. if not region.line_layouts: continue + # COO 等补充表不进入盲测主明细行;稍后按 LN 合并料号。 + if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement': + continue # ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中 # 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。 eligible_pages = [ @@ -450,8 +465,32 @@ def _candidate_for_sample( line_start_field_code=region.line_start_field_code, schema_field_metadata=list(schema_fields.values()), ) - if strategy.status == 'selected': - rows.extend(item.fields for item in chosen_rows if not item.issues) + # selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。 + rows.extend(item.fields for item in chosen_rows if not item.issues) + # 与正式解析共用:按 LN 合并 line_field_supplement(如 COO)料号。 + from app.services.shipping_notice.order_extraction_workflow import ( + _reconstruct_line_field_supplement_rows, + ) + from app.services.shipping_notice.line_field_supplement_merge import ( + merge_line_field_supplement, + ) + supplement_rows, line_start = _reconstruct_line_field_supplement_rows( + raw_profile={ + 'definition': profile.definition_json if isinstance(profile.definition_json, dict) else {}, + 'profile_code': profile.profile_code, + 'version': profile.version, + 'checksum': profile.checksum, + }, + layout=layout, + schema_fields=schema_fields, + ) + supplement_reasons: list[str] = [] + if supplement_rows: + rows, supplement_reasons = merge_line_field_supplement( + rows, + supplement_rows, + line_start_field_code=line_start or 'customer_po_line_no', + ) order_fields = [ { 'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status, @@ -465,55 +504,58 @@ def _candidate_for_sample( allow_fixed_region_confirmation=True, ) ] - # 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。 + # 盲测与正式解析共用 Vendor Comments→Terms 锚点;page_no/region 仅表示专区已启用。 profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} - reservation_region = profile_definition.get('reservation_id_region') - if isinstance(reservation_region, dict): - region = reservation_region.get('region') - try: - reservation_page_no = int(reservation_region.get('page_no') or 0) - except (TypeError, ValueError): - reservation_page_no = 0 - if isinstance(region, dict) and reservation_page_no > 0: - layout = _ensure_page_coordinate_evidence( - document=document, layout=layout, page_no=reservation_page_no, + if isinstance(profile_definition.get('reservation_id_region'), dict): + from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ( + ensure_on_demand_coordinate_evidence, + ) + layout = ensure_on_demand_coordinate_evidence( + document=document, layout=layout, page_nos=None, + ) + reservation = reservation_region_candidates_from_layout( + definition=profile_definition, layout=layout, + ) + candidates = list(reservation.get('candidates') or []) + reservation_reason = reservation.get('reason') + reservation_fields = { + str(field.get('scope') or ''): field + for field in schema_fields.values() + if str(field.get('field_code') or '') == 'reservation_id' + } + review_reasons: list[str] = [str(reservation_reason)] if reservation_reason else [] + if candidates: + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None, + line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None, + line_count=len(rows), ) - evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - page = (evidence.get('pages') or {}).get(str(reservation_page_no)) - glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no)) - if isinstance(page, dict) and isinstance(glyphs, list): - candidates = extract_reservation_from_region_text( - read_coordinate_region_text(glyphs=glyphs, page=page, region=region), - ) - reservation_fields = { - str(field.get('scope') or ''): field - for field in schema_fields.values() - if str(field.get('field_code') or '') == 'reservation_id' - } - applied = apply_reservation_region_candidates( - candidates=candidates, - header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None, - line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None, - line_count=len(rows), - ) - if applied.header_value and reservation_fields.get('header'): - header = reservation_fields['header'] - order_fields.append({ - 'field_code': str(header.get('field_code') or ''), 'value': applied.header_value, - 'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header', - 'page_no': reservation_page_no, 'issues': [], - }) - if reservation_fields.get('line'): - for line_no, value in applied.line_values.items(): - if isinstance(rows[line_no - 1], dict): - rows[line_no - 1]['reservation_id'] = value - if applied.needs_review: - return { - 'document_id': document.id, 'table_id': str(table_id), 'rows': rows, - 'order_fields': order_fields, 'reservation_region_status': 'needs_review', - 'reservation_region_review_reasons': list(applied.review_reasons), - } - return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields} + if applied.header_value and reservation_fields.get('header'): + header = reservation_fields['header'] + order_fields.append({ + 'field_code': str(header.get('field_code') or ''), 'value': applied.header_value, + 'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header', + 'page_no': 1, 'issues': [], + }) + if reservation_fields.get('line'): + for line_no, value in applied.line_values.items(): + if isinstance(rows[line_no - 1], dict): + rows[line_no - 1]['reservation_id'] = value + if applied.needs_review: + review_reasons.extend(list(applied.review_reasons)) + if review_reasons: + return { + 'document_id': document.id, 'table_id': str(table_id), 'rows': rows, + 'order_fields': order_fields, 'reservation_region_status': 'needs_review', + 'reservation_region_review_reasons': list(dict.fromkeys(review_reasons)), + 'line_field_supplement_reasons': list(supplement_reasons), + } + return { + 'document_id': document.id, 'table_id': str(table_id), 'rows': rows, + 'order_fields': order_fields, + 'line_field_supplement_reasons': list(supplement_reasons), + } raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/inventory_configuration_test.py index 9c806b82..61e8188e 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/inventory_configuration_test.py @@ -356,8 +356,20 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow() db.session.commit() return _payload(run) - path = Path(str(payload.get('file_path') or '')) - if not path.is_file(): + # Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到 + # SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。 + raw_file_path = str(payload.get('file_path') or '').strip() + path: Path | None = None + from app.services.shipping_notice.rpa import inventory_drop_dir + from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file + drop_root = inventory_drop_dir() + if drop_root is not None: + path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root) + if path is None: + candidate = Path(raw_file_path) + if candidate.is_file(): + path = candidate + if path is None or not path.is_file(): run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow() db.session.commit() return _payload(run) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 15acc0fc..8a257feb 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -5,7 +5,8 @@ services/shipping_notice/inventory_rpa_workflow.py 依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、 inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。 逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新; - 库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。 + 库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取; + 复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。 """ from __future__ import annotations @@ -148,7 +149,8 @@ def _try_reuse_inventory_snapshot( 优先复用未过期库存快照,避免重复触发 RPA。 【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。 - 核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。 + 核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则用 + preparation 软绑定并进入待匹配状态(动态仓未决不视为缺文件)。 retry_rpa 必须跳过缓存强制重新导出。 """ if mode == "retry_rpa": @@ -163,7 +165,7 @@ def _try_reuse_inventory_snapshot( if not snapshot: return None - link = link_snapshot_to_task( + link = link_snapshot_to_task_for_preparation( task, snapshot, reason="reuse_latest", diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 30608a44..43bd5f76 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -6,7 +6,8 @@ services/shipping_notice/inventory_workflow.py 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。 + STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File; + 动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。 """ from __future__ import annotations @@ -65,8 +66,9 @@ def _link_ready_candidate_prep_or_block( STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。 核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded - 快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human, - 禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。 + 快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定 + (pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成 + inventory_file_missing。仅当真的无法绑定文件时才 needs_human。 Args: task: 已冻结候选源的订单任务。 @@ -78,7 +80,9 @@ def _link_ready_candidate_prep_or_block( """ 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 + from app.services.shipping_notice.inventory_snapshot_store import ( + link_snapshot_to_task_for_preparation, + ) # [STEP 1] 已绑定则无需重复 link。 if active_inventory_file_for_task(task) is not None: @@ -109,11 +113,12 @@ def _link_ready_candidate_prep_or_block( ) link = None if inv_file is not None: - link = link_snapshot_to_task( + # [STEP] 与 RPA 回调同权:文件事实先挂 OT;动态仓未决 → pending_matching, + # 不因 warehouse_configuration_invalid 谎称「库存文件未准备」。 + link = link_snapshot_to_task_for_preparation( 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 []), @@ -123,7 +128,7 @@ def _link_ready_candidate_prep_or_block( db.session.flush() return None - # [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。 + # [STEP 3] 真的没有可绑定文件:软阻断,勿让 Gate Job 因 ValueError 失败。 apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, diff --git a/backend/app/services/shipping_notice/line_field_supplement_merge.py b/backend/app/services/shipping_notice/line_field_supplement_merge.py new file mode 100644 index 00000000..e6e756d3 --- /dev/null +++ b/backend/app/services/shipping_notice/line_field_supplement_merge.py @@ -0,0 +1,278 @@ +""" +services/shipping_notice/line_field_supplement_merge.py + +用途:将同文档「明细字段补充表」(如 Hyve COO)按 LN 保守合并进主表明细。 +依赖:无外部 IO;仅字符串规范化与行字典读写。 +逻辑:由正式解析 / 盲测 / 验证在主表重建后调用;只补 customer_part_number、part_number; + 空值直补、主表为补充值前缀则补全、冲突不覆盖并写稳定 reason。不改数量/单价/金额。 + ``REASON_APPLIED`` 仅写入表级 reasons 审计,不进入行 ``issues``(成功补齐不得触发 row_needs_review)。 +""" + +from __future__ import annotations + +import copy +import re +from typing import Any + +LINE_FIELD_SUPPLEMENT_CODES = frozenset({'customer_part_number', 'part_number'}) +DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no' + +REASON_APPLIED = 'line_field_supplement_applied' +REASON_CONFLICT = 'line_field_supplement_conflict' +REASON_LN_AMBIGUOUS = 'line_field_supplement_ln_ambiguous' +REASON_LN_MISSING = 'line_field_supplement_ln_missing' + +# 表级审计码:不得当作行级缺陷拦截确定性建单。 +NON_BLOCKING_ROW_ISSUE_CODES = frozenset({REASON_APPLIED}) + + +def normalize_line_start_key(raw: Any) -> str: + """ + 将行号规范为对齐键:去空白;纯数字去掉无意义前导零(保留至少一位)。 + + Args: + raw: 主表或补充表上的起行字段值。 + + Returns: + 非空对齐键;无法规范化时返回空串。 + """ + text = re.sub(r'\s+', '', str(raw or '')).strip() + if not text: + return '' + if text.isdigit(): + return str(int(text)) + return text + + +def normalize_part_value(raw: Any) -> str: + """料号比较用:去掉空白,保留连字符等符号。""" + return re.sub(r'\s+', '', str(raw or '')).strip() + + +def _row_field_map(row: dict[str, Any]) -> dict[str, str]: + """将扁平行或 workflow ``fields`` 列表统一为 field_code -> 文本值。""" + if not isinstance(row, dict): + return {} + fields = row.get('fields') + if isinstance(fields, list): + result: dict[str, str] = {} + for item in fields: + if not isinstance(item, dict): + continue + code = str(item.get('field_code') or '').strip() + if not code: + continue + result[code] = str(item.get('value') or '').strip() + return result + return { + str(key): str(value or '').strip() + for key, value in row.items() + if key not in {'fields', 'issues', 'status', 'row_index', 'role', 'source_row_indices'} + and not str(key).startswith('_') + } + + +def _set_row_field(row: dict[str, Any], field_code: str, value: str) -> None: + """按行形态写回字段值;workflow 行写入 ``fields`` 列表。""" + fields = row.get('fields') + if isinstance(fields, list): + target = next( + ( + item for item in fields + if isinstance(item, dict) and str(item.get('field_code') or '') == field_code + ), + None, + ) + if target is None: + fields.append({'field_code': field_code, 'value': value}) + else: + target['value'] = value + return + row[field_code] = value + + +def _append_row_issue(row: dict[str, Any], code: str) -> None: + """为 workflow 行追加 issue;扁平行写入 ``issues`` 列表供调用方读取。""" + issues = row.get('issues') + if not isinstance(issues, list): + row['issues'] = [code] + return + if code not in issues: + issues.append(code) + + +def _index_rows_by_line( + rows: list[dict[str, Any]], + *, + line_start_field_code: str, +) -> tuple[dict[str, dict[str, Any]], set[str], list[str]]: + """ + 按规范化 LN 建唯一索引。 + + Returns: + (唯一行映射, 重复 LN 集合, 缺 LN 的全局 reasons) + """ + buckets: dict[str, list[dict[str, Any]]] = {} + missing_reasons: list[str] = [] + for row in rows: + key = normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) + if not key: + missing_reasons.append(REASON_LN_MISSING) + continue + buckets.setdefault(key, []).append(row) + unique: dict[str, dict[str, Any]] = {} + ambiguous: set[str] = set() + for key, items in buckets.items(): + if len(items) != 1: + ambiguous.add(key) + continue + unique[key] = items[0] + return unique, ambiguous, missing_reasons + + +def merge_line_field_supplement( + main_rows: list[dict[str, Any]], + supplement_rows: list[dict[str, Any]], + *, + line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE, + field_codes: frozenset[str] = LINE_FIELD_SUPPLEMENT_CODES, +) -> tuple[list[dict[str, Any]], list[str]]: + """ + 按 LN 将补充表料号合并进主表明细。 + + 核心逻辑:只处理 ``field_codes``;空值直补;主表规范化值是补充值前缀则补全; + 两边完整且不同则写冲突 reason 且不覆盖;补充侧或主侧 LN 重复/缺失则跳过该键。 + 成功补齐仅写入返回的 reasons(``REASON_APPLIED``),不写入行 ``issues``。 + + Args: + main_rows: 主表明细(扁平 dict 或含 ``fields`` 的 workflow 行)。 + supplement_rows: 补充表重建行,形态同主表。 + line_start_field_code: 对齐用起行字段,默认 customer_po_line_no。 + field_codes: 允许补齐的字段集合。 + + Returns: + (合并后的主表行深拷贝, 稳定 reason 列表;可含表级审计码与行级冲突码) + """ + if not main_rows or not supplement_rows: + return [copy.deepcopy(row) for row in main_rows], [] + + merged = [copy.deepcopy(row) for row in main_rows] + main_index, main_ambiguous, main_missing = _index_rows_by_line( + merged, line_start_field_code=line_start_field_code, + ) + supplement_index, supplement_ambiguous, supplement_missing = _index_rows_by_line( + supplement_rows, line_start_field_code=line_start_field_code, + ) + + reasons: list[str] = [] + reasons.extend(main_missing) + reasons.extend(supplement_missing) + for key in sorted(main_ambiguous | supplement_ambiguous): + reasons.append(REASON_LN_AMBIGUOUS) + if key in main_index: + _append_row_issue(main_index[key], REASON_LN_AMBIGUOUS) + for row in merged: + if normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) == key: + _append_row_issue(row, REASON_LN_AMBIGUOUS) + + for line_key, main_row in main_index.items(): + if line_key in main_ambiguous or line_key in supplement_ambiguous: + continue + supplement_row = supplement_index.get(line_key) + if supplement_row is None: + continue + main_fields = _row_field_map(main_row) + supplement_fields = _row_field_map(supplement_row) + for code in sorted(field_codes): + supplement_raw = supplement_fields.get(code) or '' + if not supplement_raw: + continue + main_raw = main_fields.get(code) or '' + main_norm = normalize_part_value(main_raw) + supplement_norm = normalize_part_value(supplement_raw) + if not supplement_norm: + continue + if not main_norm: + # [STEP] 成功直补:只记表级审计,不写行 issues(避免误判 row_needs_review)。 + _set_row_field(main_row, code, supplement_raw) + reasons.append(REASON_APPLIED) + continue + if main_norm == supplement_norm: + continue + if supplement_norm.startswith(main_norm) and len(supplement_norm) > len(main_norm): + # [STEP] 前缀补全成功:同上,审计进 reasons,不写入 issues。 + _set_row_field(main_row, code, supplement_raw) + reasons.append(REASON_APPLIED) + continue + _append_row_issue(main_row, REASON_CONFLICT) + reasons.append(REASON_CONFLICT) + + # 保持 reason 顺序稳定且去重保留首次出现,便于审计对照。 + deduped: list[str] = [] + seen: set[str] = set() + for code in reasons: + if code in seen: + continue + seen.add(code) + deduped.append(code) + return merged, deduped + + +def project_line_field_supplement_onto_validation_evidence( + evidence: dict[str, Any], + *, + supplement_rows: list[dict[str, Any]], + line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE, +) -> tuple[dict[str, Any], list[str]]: + """ + 将补充表合并结果写回验证证据的 lines 字段。 + + Args: + evidence: 含 header_fields / lines 的验证 DTO。 + supplement_rows: workflow 或扁平行。 + line_start_field_code: LN 对齐字段。 + + Returns: + (更新后的 evidence 深拷贝, reason 列表) + """ + if not isinstance(evidence, dict) or not supplement_rows: + return copy.deepcopy(evidence) if isinstance(evidence, dict) else {}, [] + result = copy.deepcopy(evidence) + lines = result.get('lines') if isinstance(result.get('lines'), list) else [] + main_rows: list[dict[str, Any]] = [] + for line in lines: + if not isinstance(line, dict): + continue + fields = [] + for item in line.get('fields') or []: + if not isinstance(item, dict): + continue + fields.append({ + 'field_code': str(item.get('field_code') or ''), + 'value': str(item.get('raw_value') or item.get('normalized_value') or ''), + }) + main_rows.append({'fields': fields, 'issues': []}) + if not main_rows: + return result, [] + merged, reasons = merge_line_field_supplement( + main_rows, supplement_rows, line_start_field_code=line_start_field_code, + ) + for index, row in enumerate(merged): + if index >= len(lines) or not isinstance(lines[index], dict): + continue + values = _row_field_map(row) + issues = list(row.get('issues') or []) + for field in lines[index].get('fields') or []: + if not isinstance(field, dict): + continue + code = str(field.get('field_code') or '') + if code not in LINE_FIELD_SUPPLEMENT_CODES or code not in values: + continue + value = values[code] + field['raw_value'] = value or None + field['normalized_value'] = value or None + field['status'] = 'passed' if value else field.get('status') or 'missing' + if issues: + field['issues'] = list(dict.fromkeys([*(field.get('issues') or []), *issues])) + result['line_field_supplement_reasons'] = list(reasons) + return result, reasons diff --git a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py index 3f9d296c..b2c23970 100644 --- a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py @@ -265,14 +265,21 @@ def _resolve_overlap_run( def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: ShippingOrderDocumentProfileValidationRun | None, revision: ShippingOrderDocumentProfileDraftRevision) -> list[dict[str, Any]]: - """将重叠验证摘要转为发布阻断项。""" + """ + 将重叠验证摘要转为发布阻断项。 + + 核心逻辑:仅在 definition_checksum 漂移时标为 stale;当前草稿上的 failed 运行 + 必须展开真实门禁(如 self_match_not_unique),禁止误报“验证已过期”。 + """ blocking: list[dict[str, Any]] = [] if overlap_run is None: blocking.append({'key': 'overlap_validation_required', 'message': 'Cross-template overlap validation is required.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'}) return blocking - if overlap_run.definition_checksum != revision.definition_checksum or overlap_run.status != 'passed': + # [STEP 1] checksum 漂移才是 stale;failed≠过期。 + if overlap_run.definition_checksum != revision.definition_checksum: blocking.append({'key': 'overlap_validation_stale', 'message': 'Cross-template overlap validation is stale.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'}) return blocking + # [STEP 2] 当前草稿的 passed/failed 一律按摘要指标展开,避免掩盖真实阻断原因。 summary = summary or dict(overlap_run.summary_json or {}) snapshot = dict(overlap_run.result_snapshot_json or {}) if float(summary.get('self_unique_hit_rate_training') or 0) < 1.0: @@ -303,6 +310,9 @@ def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: Shipping 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED', 'conflict_profiles': list(snapshot.get('conflict_profiles') or []), }) + # [STEP 3] failed 但摘要未给出可映射指标时,回落为明确失败文案,禁止冒充 stale。 + if not blocking and overlap_run.status != 'passed': + blocking.append({'key': 'overlap_validation_failed', 'message': 'Cross-template overlap validation failed.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'}) return blocking 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 d5bbc3d8..1312465b 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -75,7 +75,6 @@ from app.services.shipping_notice.order_profile_value_adapter import ( OrderProfileValueAdapter, get_value_adapter, ) -from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -1155,7 +1154,22 @@ def read_preview_page_region_text( db.session.commit() result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'} if data.get('purpose') == 'reservation_id_region': - result['reservation_candidates'] = extract_reservation_from_region_text(text) + # 画布预览候选与正式解析共用 Vendor Comments→Terms;矩形 text 仅作圈选回显。 + from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ( + ensure_on_demand_coordinate_evidence, + ) + from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout + + full_layout = ensure_on_demand_coordinate_evidence( + document=document, layout=_document_layout(document), page_nos=None, + ) + scanned = reservation_region_candidates_from_layout( + definition={'reservation_id_region': {'page_no': int(page_no), 'region': region}}, + layout=full_layout, + ) + result['reservation_candidates'] = scanned.get('candidates') or [] + if scanned.get('reason'): + result['reservation_region_reason'] = scanned['reason'] return result @@ -1275,6 +1289,9 @@ def preview_profile_region( # Header-only pages document column semantics but must never emit data rows. if not table_region.line_layouts: continue + # 补充表不进入预览主网格;验证/正式路径另行按 LN 合并。 + if str(getattr(table_region, 'region_role', None) or 'business_lines') == 'line_field_supplement': + continue # 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema # 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。 reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump()) 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 1ca8cf97..69cffb18 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 @@ -2,10 +2,12 @@ services/shipping_notice/order_document_profile_validation_service.py 用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。 -依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、Profile 保存服务及编辑租约服务。 -逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;XFA current-sample 另附脱敏字段级 Header/Line; - 签名成功后更新 Profile 轻量引用;跨模板重叠验证消费已发布快照与统一 matcher; - 查询时根据当前 checksum 派生 stale,绝不改写历史运行。 +依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、 + Profile 保存服务、编辑租约服务、Reservation 专区锚点投影、line_field_supplement_merge。 +逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/ + 表头试读后投影 Vendor Comments Reservation,并按 LN 合并 COO 等补充表料号; + XFA current-sample 另附脱敏字段级 Header/Line;签名成功后更新 Profile 轻量引用; + 查询时根据当前 checksum 派生 stale。 """ from __future__ import annotations @@ -344,6 +346,14 @@ def _extract_coordinate_current_sample( actor_id: int | None, ) -> tuple[str, dict[str, Any], dict[str, Any]]: """通过 coordinate value adapter 生成与 XFA 相同的当前样本结果 DTO。""" + from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ( + ensure_on_demand_coordinate_evidence, + ) + from app.services.shipping_notice.reservation_region import ( + project_reservation_onto_validation_evidence, + reservation_region_candidates_from_layout, + ) + table_id = profile_service.resolve_profile_sample_table_id(profile, sample) preview = profile_service.preview_profile_region(profile.id, data={ 'document_id': sample.document_id, 'table_id': table_id, @@ -385,11 +395,70 @@ def _extract_coordinate_current_sample( header_required_missing_count=len(required_header_ids - readable_header_ids), sample_role=sample.sample_role, ) - summary['validation_evidence'] = _build_coordinate_validation_evidence( + evidence = _build_coordinate_validation_evidence( rows=list(rows[1:]) if isinstance(rows, list) else [], field_codes=list(fields or []), header_fields=list(header_fields), ) + # [STEP] Reservation 专区与正式解析共用 Vendor Comments 锚点;验证页必须展示同一结果。 + if isinstance(definition.get('reservation_id_region'), dict): + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + layout = _load_sample_layout(sample) if document is not None else {} + if document is not None and isinstance(layout, dict): + layout = ensure_on_demand_coordinate_evidence( + document=document, layout=layout, page_nos=None, + ) + reservation = reservation_region_candidates_from_layout(definition=definition, layout=layout) + schema_fields = { + str(item.get('field_id') or ''): item + for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id') + } + evidence = project_reservation_onto_validation_evidence( + evidence, + candidates=list(reservation.get('candidates') or []), + reason=reservation.get('reason'), + schema_fields=schema_fields, + ) + # [STEP] COO 等明细字段补充表按 LN 合并进验证 lines(与正式/盲测同契约)。 + if any( + isinstance(item, dict) and str(item.get('region_role') or '') == 'line_field_supplement' + for item in definition.get('table_regions') or [] + ): + from app.services.shipping_notice.line_field_supplement_merge import ( + project_line_field_supplement_onto_validation_evidence, + ) + from app.services.shipping_notice.order_extraction_workflow import ( + _reconstruct_line_field_supplement_rows, + ) + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + layout = _load_sample_layout(sample) if document is not None else {} + if document is not None and isinstance(layout, dict): + layout = ensure_on_demand_coordinate_evidence( + document=document, layout=layout, page_nos=None, + ) + schema_fields = { + str(item.get('field_id') or ''): item + for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id') + } + supplement_rows, line_start = _reconstruct_line_field_supplement_rows( + raw_profile={ + 'definition': definition, + 'profile_code': profile.profile_code, + 'version': profile.version, + 'checksum': profile.checksum, + }, + layout=layout if isinstance(layout, dict) else {}, + schema_fields=schema_fields, + ) + if supplement_rows: + evidence, _reasons = project_line_field_supplement_onto_validation_evidence( + evidence, + supplement_rows=supplement_rows, + line_start_field_code=line_start or 'customer_po_line_no', + ) + summary['validation_evidence'] = evidence return status, summary, snapshot 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 ac3aa03b..9044acae 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -1201,6 +1201,88 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool: return 'layout_pending' in order_extraction_layout_prerequisite_issues(run).values() +_EXTRACT_DONE_UNIT_STATUSES = frozenset({ + 'candidate_ready', 'review_required', 'failed', 'cancelled', +}) +# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队, +# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。 +_ORDER_EXTRACTION_READY_PRIORITY = 10 + + +def _enqueue_ready_order_extraction_job( + run: ShippingOrderProcessingRun, *, message: str, +) -> int: + """ + 为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。 + + 核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到 + _ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。 + """ + from app.jobs.queue import enqueue + from app.jobs.types import JobType + + job_id = enqueue( + JobType.SHIPPING_ORDER_EXTRACTION, + {'run_no': run.run_no}, + domain='shipping_notice', + business_ref=run.run_no, + created_by_id=run.user_id, + priority=_ORDER_EXTRACTION_READY_PRIORITY, + max_attempts=3, + message=message, + commit=False, + ) + job = db.session.get(Job, int(job_id)) + if ( + job is not None + and str(job.status or '') == 'queued' + and int(job.priority or 0) < _ORDER_EXTRACTION_READY_PRIORITY + ): + job.priority = _ORDER_EXTRACTION_READY_PRIORITY + job.message = message + return int(job_id) + + +def order_extraction_ready_document_ids(run: ShippingOrderProcessingRun) -> set[int]: + """ + 返回本 Run 快照中已通过版面前置条件、可立即抽取的订单 PDF Document ID。 + + 核心逻辑:复用 order_extraction_layout_prerequisite_issues;未出现在 issues 中的 PDF + 视为 ready。非 PDF 不参与。 + """ + issues = order_extraction_layout_prerequisite_issues(run) + ready: set[int] = set() + for document in _run_layout_documents(run): + if Path(str(document.filename or '')).suffix.lower() != '.pdf': + continue + document_id = int(document.id) + if document_id not in issues: + ready.add(document_id) + return ready + + +def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun) -> bool: + """ + 判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。 + + 核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应 + Unit 未到 candidate_ready/review_required/failed/cancelled)。 + """ + ready_ids = order_extraction_ready_document_ids(run) + if not ready_ids: + return False + plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first() + if plan is None or int(plan.unit_count or 0) <= 0: + return True + units = ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all() + for unit in units: + if int(unit.document_id or 0) not in ready_ids: + continue + if str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES: + return True + return False + + def order_extraction_layouts_failed(run: ShippingOrderProcessingRun) -> bool: """判断当前应消费的布局是否最终失败;历史失败版本不得污染后续成功重识别。 @@ -1311,17 +1393,63 @@ def schedule_order_extraction_layouts( def resume_runs_waiting_for_layout(*, document_id: int) -> int: - """布局任务完成后唤醒所有已具备完整布局的 Run,确保订单任务不会早于版面快照执行。""" - from app.jobs.queue import enqueue - from app.jobs.types import JobType + """ + 单份附件布局完成后唤醒仍等待版式的 Run。 + 核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document, + 即以抬高 priority 入队(或复用活跃)shipping_order_extraction,避免被剩余 layout + FIFO 堵住。无 ready 活且无 pending、仅有失败版式、且尚未抽出任何 Unit 时整 Run 失败。 + """ resumed = 0 - runs = ShippingOrderProcessingRun.query.filter_by(status='queued', phase='waiting_layout').with_for_update().all() + # processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。 + runs = ( + ShippingOrderProcessingRun.query.filter( + ShippingOrderProcessingRun.status.in_(('queued', 'processing')), + ShippingOrderProcessingRun.phase == 'waiting_layout', + ) + .with_for_update() + .all() + ) for run in runs: - if int(document_id) not in _run_snapshot_document_ids(run) or order_extraction_layouts_pending(run): + if int(document_id) not in _run_snapshot_document_ids(run): + continue + if order_extraction_has_extractable_ready_work(run): + job_id = _enqueue_ready_order_extraction_job( + run, message='附件解析完成,等待订单识别', + ) + run.current_job_id = job_id + # 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume; + # 已无 pending 则改为 queued,表示本轮可抽尽。 + run.phase = 'waiting_layout' if order_extraction_layouts_pending(run) else 'queued' + record_run_progress( + run=run, + event_code='layout_parsing_completed', + summary={'document_id': int(document_id), 'partial': order_extraction_layouts_pending(run)}, + commit=False, + ) + resumed += 1 + continue + if order_extraction_layouts_pending(run): continue if order_extraction_layouts_failed(run): - transition_order_extraction_run(run, target_status='processing', phase='layout_failed') + plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first() + progressed = False + if plan is not None: + progressed = any( + str(unit.status or '') in _EXTRACT_DONE_UNIT_STATUSES + for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all() + ) + if progressed: + # 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。 + job_id = _enqueue_ready_order_extraction_job( + run, message='部分附件版式失败,等待订单识别收口', + ) + run.current_job_id = job_id + run.phase = 'queued' + resumed += 1 + continue + if run.status == 'queued': + transition_order_extraction_run(run, target_status='processing', phase='layout_failed') transition_order_extraction_run( run, target_status='failed', phase='layout_failed', error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', @@ -1332,16 +1460,6 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int: reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False, ) resumed += 1 - continue - job_id = enqueue( - JobType.SHIPPING_ORDER_EXTRACTION, - {'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no, - created_by_id=run.user_id, max_attempts=3, message='附件解析完成,等待订单识别', commit=False, - ) - run.current_job_id = job_id - run.phase = 'queued' - record_run_progress(run=run, event_code='layout_parsing_completed', commit=False) - resumed += 1 if resumed: db.session.commit() return resumed @@ -1355,7 +1473,8 @@ def materialize_order_extraction_run_inputs( AI 触发时机:仅订单抽取 Job 开始时调用;HTTP 发送路径严禁调用。 核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮; - 布局任务尚未完成时只刷新 Document 快照,待布局就绪后再冻结计划。 + 允许在部分 PDF 版式仍 pending 时 finalize Plan(未 ready 的 Unit 挂 pending), + 供按 Unit 流水线抽取;已存在 Plan 时只刷新各 Document 的当前布局证据。 """ from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan @@ -2266,8 +2385,8 @@ def create_order_extraction_run( from app.jobs.queue import enqueue from app.jobs.types import JobType - # 立即建立 Job 保持 Run 的可追踪性;Handler 发现 waiting_layout 后只安全收口, - # 绝不开始订单提取。最后一份布局完成会创建真正可执行的后继 Job。 + # 立即建立 Job 保持 Run 的可追踪性;Handler 在零 ready 时只安全收口, + # 有 ready PDF 时按 Unit 抽取。任一布局完成即可 resume 后继 Job(无需等齐)。 job_id = enqueue( JobType.SHIPPING_ORDER_EXTRACTION, {'run_no': run.run_no}, diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 73a94f1c..f694d47f 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -3,11 +3,12 @@ backend/app/services/shipping_notice/order_extraction_workflow.py 用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。 依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、 - order_extraction_route_contract、xfa_profile_*、统一错误类型。 + order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。 逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值; datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review; 唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败; 路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格; + 主明细仅来自 region_role=business_lines;line_field_supplement 按 LN 补料号; 模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。 """ @@ -38,6 +39,10 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import resolve_runtime_parse_strategy, select_runtime_region_ids, ) +from app.services.shipping_notice.line_field_supplement_merge import ( + NON_BLOCKING_ROW_ISSUE_CODES, + merge_line_field_supplement, +) from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchResult, @@ -58,7 +63,6 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value from app.services.shipping_notice.reservation_region import ( apply_reservation_region_candidates, - extract_reservation_from_vendor_comments_pages, ) @@ -380,6 +384,9 @@ def _coordinate_profile_rows( # 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。 if region.region_id not in runtime_region_ids: continue + # 补充表不参与主明细重建,避免 COO 等副表进入 matches / multiple_business_tables。 + if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement': + continue # A continuation page may carry column headers only; it is not a data layout. if not region.line_layouts: continue @@ -470,6 +477,239 @@ def _coordinate_profile_rows( return rows +def _pick_overlapping_layout_table( + *, + layout_tables: list[Any], + page_no: int, + region_relative: dict[str, Any], + page_size: dict[str, Any], + reference_page_frame: dict[str, Any] | None = None, + coordinate_transform: dict[str, Any] | None = None, +) -> tuple[str | None, dict[str, float] | None]: + """ + 在同页 layout.tables 中选取与补充表相对区重叠的物理表。 + + 核心逻辑:将相对区投影为页绝对框后与 MinerU 表求交,取纵向重叠面积最大者。 + 用于样本仅 1 行 COO 时,盲测多行仍能纵向扩到整张物理表读 glyph。 + + Args: + layout_tables: layout.tables 列表。 + page_no: 当前页号。 + region_relative: 补充表区相对 bbox。 + page_size: 当前页宽高。 + reference_page_frame: 可选参考页框;缺省用 page_size。 + coordinate_transform: 可选坐标变换。 + + Returns: + (table_id, 绝对 bbox) 或 (None, None)。 + """ + projected = apply_coordinate_transform_to_region( + region_relative, coordinate_transform=coordinate_transform, + ) + if projected is None: + return None, None + try: + ref_w = float(reference_page_frame['width']) if reference_page_frame is not None else float(page_size['width']) + ref_h = float(reference_page_frame['height']) if reference_page_frame is not None else float(page_size['height']) + region_bbox = { + 'x0': float(projected['x0']) * ref_w, + 'y0': float(projected['y0']) * ref_h, + 'x1': float(projected['x1']) * ref_w, + 'y1': float(projected['y1']) * ref_h, + } + except (KeyError, TypeError, ValueError): + return None, None + best_id: str | None = None + best_bbox: dict[str, float] | None = None + best_overlap = 0.0 + for item in layout_tables: + if not isinstance(item, dict): + continue + if int(item.get('page_no') or 1) != int(page_no): + continue + bbox = item.get('bbox') + if not isinstance(bbox, dict): + continue + try: + x0, y0, x1, y1 = float(bbox['x0']), float(bbox['y0']), float(bbox['x1']), float(bbox['y1']) + except (KeyError, TypeError, ValueError): + continue + if not (x0 < region_bbox['x1'] and x1 > region_bbox['x0'] and y0 < region_bbox['y1'] and y1 > region_bbox['y0']): + continue + overlap_h = max(0.0, min(x1, region_bbox['x1']) - max(x0, region_bbox['x0'])) + overlap_v = max(0.0, min(y1, region_bbox['y1']) - max(y0, region_bbox['y0'])) + overlap_area = overlap_h * overlap_v + if overlap_area <= best_overlap: + continue + best_overlap = overlap_area + best_id = str(item.get('table_id') or '') or None + best_bbox = {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1} + return best_id, best_bbox + + +def _reconstruct_line_field_supplement_rows( + *, + raw_profile: dict[str, Any], + layout: dict[str, Any], + schema_fields: dict[str, dict[str, Any]], + coordinate_transform: dict[str, Any] | None = None, +) -> tuple[list[dict[str, Any]], str | None]: + """ + 从 Profile 的 line_field_supplement 表区按页坐标重建补充行(如 COO)。 + + 核心逻辑:不把补充表当作业务表命中源;在补充区相对框内读 page_glyphs。 + 若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox 纵向扩展字符范围 + (样本单行 / 盲测多行时仍能读到整张 COO)。再以 with_strategy 取最佳努力行供 LN 合并。 + + Returns: + (workflow 形态行列表, line_start_field_code 或 None) + """ + try: + profile = _frozen_coordinate_profile(raw_profile) + except (TypeError, ValueError, ValidationError): + return [], None + supplement_regions = [ + region for region in profile.table_regions + if str(getattr(region, 'region_role', None) or '') == 'line_field_supplement' + and region.line_layouts + ] + if not supplement_regions: + return [], None + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + layout_tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] + rows: list[dict[str, Any]] = [] + line_start = None + for region in supplement_regions: + line_start = region.line_start_field_code or 'customer_po_line_no' + runtime_ids = set(select_runtime_region_ids( + table_regions=[_coordinate_object_mapping(item) for item in profile.table_regions], + page_no=int(region.page_no or 1) if region.page_scope == 'exact_page' else 1, + )) + # exact_page 补充区按其页;all_pages/first_page 扫有 glyph 的页。 + if region.page_scope == 'exact_page': + candidate_pages = [int(region.page_no or 1)] + else: + candidate_pages = sorted( + int(page_no) for page_no in page_glyphs + if str(page_no).isdigit() and isinstance(page_glyphs.get(str(page_no)), list) + ) + if region.page_scope == 'first_page': + candidate_pages = [page for page in candidate_pages if page == 1] or [1] + for page_no in candidate_pages: + if region.page_scope == 'exact_page' and region.region_id not in runtime_ids and str(page_no) not in {str(region.page_no)}: + continue + page_size = pages.get(str(page_no)) + characters = page_glyphs.get(str(page_no)) + if not isinstance(page_size, dict) or not isinstance(characters, list) or not characters: + continue + try: + page_bbox = { + 'x0': 0, 'y0': 0, + 'x1': float(page_size['width']), 'y1': float(page_size['height']), + } + except (KeyError, TypeError, ValueError): + continue + 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, + 'x1': reference_page_frame.width, 'y1': reference_page_frame.height, + } + if reference_page_frame is not None else page_bbox + ) + relative_region = _coordinate_region_mapping(region.region) + if relative_region is None: + continue + ref_frame_mapping = ( + _coordinate_object_mapping(reference_page_frame) + if reference_page_frame is not None else None + ) + # [STEP 1] 样本单行标注的相对框常盖不住盲测多行;重叠物理表纵向扩 glyph。 + overlap_table_id, overlap_table_bbox = _pick_overlapping_layout_table( + layout_tables=layout_tables, + page_no=page_no, + region_relative=_coordinate_object_mapping(region.region), + page_size=page_size, + reference_page_frame=ref_frame_mapping, + coordinate_transform=coordinate_transform, + ) + filtered, _ = coordinate_profile_character_candidates( + table_region=_coordinate_object_mapping(region.region), + page_size=page_size, + reference_page_frame=ref_frame_mapping, + page_characters=characters, + table_characters=None, + raw_table_bbox=overlap_table_bbox, + table_id=overlap_table_id, + page_no=page_no, + coordinate_transform=coordinate_transform, + allow_table_fallback=False, + ) + if not isinstance(filtered, list) or not filtered: + continue + chosen_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=[item for item in filtered if isinstance(item, dict)], + table_bbox=reconstruction_page_bbox, + line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts], + table_region=relative_region, + termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules], + exclusion_regions=reconstruction_exclusion_regions(_coordinate_object_mapping(region)), + line_start_field_code=region.line_start_field_code, + schema_field_metadata=list(schema_fields.values()), + coordinate_transform=coordinate_transform, + page_no=page_no, + ) + for reconstructed in chosen_rows: + values = [ + {'field_code': code, 'value': str(raw or '')} + for code, raw in reconstructed.fields.items() + ] + rows.append({ + 'fields': values, + 'issues': list(reconstructed.issues), + 'page_no': page_no, + }) + return rows, line_start + + +def _apply_line_field_supplement( + *, + raw_profile: dict[str, Any], + layout: dict[str, Any], + parsed_rows: list[dict[str, Any]], + schema_fields: dict[str, dict[str, Any]], + coordinate_transform: dict[str, Any] | None = None, +) -> tuple[list[dict[str, Any]], list[str]]: + """主表明细重建后,按 LN 合并 line_field_supplement 料号。""" + supplement_rows, line_start = _reconstruct_line_field_supplement_rows( + raw_profile=raw_profile, + layout=layout, + schema_fields=schema_fields, + coordinate_transform=coordinate_transform, + ) + if not supplement_rows: + return parsed_rows, [] + merged, reasons = merge_line_field_supplement( + parsed_rows, + supplement_rows, + line_start_field_code=line_start or 'customer_po_line_no', + ) + for row in merged: + issue_list = row.get('issues') if isinstance(row.get('issues'), list) else [] + if any( + code in {'line_field_supplement_conflict', 'line_field_supplement_ln_ambiguous'} + for code in issue_list + ): + row['status'] = 'needs_review' + return merged, reasons + + def _selected_coordinate_transform( *, profile_match: dict[str, Any], raw_profile: dict[str, Any], ) -> dict[str, Any] | None: @@ -621,10 +861,11 @@ def _physical_table_targets_profile_region( ): return False return True - # [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。 + # [STEP 2] 仅含 line_layouts 的业务明细区才是重建目标;纯表头壳与补充表直接跳过。 active_regions = [ region for region in page_regions if region.get('line_layouts') + and str(region.get('region_role') or 'business_lines') != 'line_field_supplement' ] if not active_regions: return False @@ -1043,6 +1284,18 @@ def _profile_table_candidates( issues.append('order_profile_multiple_matches') continue raw_profile, parsed = matches[0] + coordinate_transform = _selected_coordinate_transform( + profile_match=profile_match, raw_profile=raw_profile, + ) + parsed, supplement_reasons = _apply_line_field_supplement( + raw_profile=raw_profile, + layout=layout, + parsed_rows=parsed, + schema_fields=schema_fields, + coordinate_transform=coordinate_transform, + ) + if any(code.endswith('_conflict') or code.endswith('_ambiguous') for code in supplement_reasons): + issues.extend(supplement_reasons) reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout) result_tables.append({ 'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'), @@ -1053,6 +1306,7 @@ def _profile_table_candidates( 'page_no': int(raw_table.get('page_no') or 1), 'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed, + 'line_field_supplement_reasons': list(supplement_reasons), 'reservation_region_candidates': reservation_region['candidates'], 'reservation_region_reason': reservation_region['reason'], 'runtime_parse_strategy': { @@ -1876,19 +2130,10 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile: def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]: """仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。""" + from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} - configured = definition.get('reservation_id_region') - if not isinstance(configured, dict): - return {'candidates': [], 'reason': None} - evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - pages = [ - (int(page_no), glyphs) - for page_no, glyphs in page_glyphs.items() - if str(page_no).isdigit() and isinstance(glyphs, list) - ] - candidates, reason = extract_reservation_from_vendor_comments_pages(pages) - return {'candidates': candidates, 'reason': reason} + return reservation_region_candidates_from_layout(definition=definition, layout=layout) def _build_approved_profile_order_result( @@ -1935,7 +2180,13 @@ def _build_approved_profile_order_result( # Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。 if not isinstance(row, dict) or row.get('status') == 'deleted': continue - if row.get('status') != 'parsed' or row.get('issues'): + # [STEP] 忽略成功补料号等非阻塞审计码;仅真实缺陷才触发 row_needs_review。 + raw_issues = row.get('issues') if isinstance(row.get('issues'), list) else [] + blocking_issues = [ + code for code in raw_issues + if str(code or '').strip() and str(code) not in NON_BLOCKING_ROW_ISSUE_CODES + ] + if row.get('status') != 'parsed' or blocking_issues: if not allow_manual_review: return None, 'row_needs_review' has_review_rows = True diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index 112ebee3..d463128a 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -1,7 +1,8 @@ """把冻结 EML 正文补充事实保守合并到 PDF 确定性订单。 -依赖:Run 冻结 Schema、正文补充表契约和 PO 标准化。 -逻辑:优先 PO+MPN;仅唯一 Reservation 的 PO 可降级广播,歧义只写复核原因。 +依赖:Run 冻结 Schema、正文补充表契约、PO 标准化、Reservation ID 校验。 +逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播; + 歧义只写复核原因。reservation 对齐与「PO+料号灌预约号」同趟单次合并,不互相重入。 """ from __future__ import annotations @@ -11,6 +12,7 @@ from typing import Any from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.po_number import normalize_atomic_po_number +from app.services.shipping_notice.reservation_id import validated_reservation_id def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]: @@ -51,6 +53,27 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str] } +def _validated_reservation_set(values: set[str]) -> set[str]: + """将原始预约号集合收成合法 5/10 位数字键;非法值不参与对齐。""" + return { + reservation + for raw in values + if (reservation := validated_reservation_id(raw)) + } + + +def _line_reservation_values(line: dict[str, Any], ids: dict[str, str]) -> set[str]: + """读取 PDF 行上已抽取的合法 reservation_id 集合。""" + return _validated_reservation_set( + _values(line.get('fields'), 'reservation_id', {v: k for k, v in ids.items()}), + ) + + +def _row_reservation_value(row: dict[str, Any]) -> str: + """读取邮件补充行的合法 reservation_id;非法或空返回空串。""" + return validated_reservation_id(row.get('reservation_id')) + + def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any: """返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。 @@ -250,7 +273,12 @@ def _supplement_multi_value_conflict( def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]: - """按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。""" + """ + 按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。 + + 核心逻辑:同趟单次合并,优先级为 po_mpn → po_reservation → po_fallback → mpn_fallback; + 不因写入 reservation 再重入。po_reservation 按行对齐合法预约号,用于灌入库存源线索等。 + """ configs = { str(item.get('field_code') or ''): item for item in schema_definition.get('fields') or [] @@ -280,6 +308,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta exact = [row for row in candidates if _schema_field_values(row, part_codes) & order_part_values] selected = exact relation = 'po_mpn' + # [STEP] 料号对不上时,用 PDF 已有合法预约号与邮件行对齐(allocation 表常见 APN≠MPN)。 + if not selected and candidates: + order_reservation_values: set[str] = set() + for line in order.get('lines') or []: + if isinstance(line, dict): + order_reservation_values.update(_line_reservation_values(line, ids)) + reservation_exact = [ + row for row in candidates + if (reservation := _row_reservation_value(row)) and reservation in order_reservation_values + ] + if reservation_exact: + selected = reservation_exact + relation = 'po_reservation' if not selected and candidates: row_signatures = {tuple(str(row.get(code) or '').strip().upper() for code in configs if code not in {'customer_po_number', 'po_number'}) for row in candidates} if len(row_signatures) == 1: @@ -307,12 +348,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta continue for source_row in selected: row_part_values = _schema_field_values(source_row, part_codes) + row_reservation = _row_reservation_value(source_row) indexed_target_lines = [ (index, line) for index, line in enumerate(order.get('lines') or []) if isinstance(line, dict) ] - if relation != 'po_fallback': + if relation == 'po_reservation': + # 预约号精确命中只写入同 reservation 的 PDF 行,禁止跨行广播多站点线索。 + indexed_target_lines = [ + (index, line) for index, line in indexed_target_lines + if row_reservation and row_reservation in _line_reservation_values(line, ids) + ] + elif relation != 'po_fallback': # 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。 indexed_target_lines = [ (index, line) for index, line in indexed_target_lines @@ -324,7 +372,6 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta if not indexed_target_lines: order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'}) continue - target_lines = [line for _, line in indexed_target_lines] for target_code, config in configs.items(): target_groups = ( [(-1, order.get('header_fields'))] diff --git a/backend/app/services/shipping_notice/reservation_region.py b/backend/app/services/shipping_notice/reservation_region.py index 62984a02..4d897f78 100644 --- a/backend/app/services/shipping_notice/reservation_region.py +++ b/backend/app/services/shipping_notice/reservation_region.py @@ -1,9 +1,11 @@ """ Reservation ID 专用证据区域解析器。 -用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。 -依赖:reservation_id 的统一格式校验。 -逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。 +用途:从已启用的 Vendor Comments→Terms 锚点窗提取 Reservation ID 与可选行号, + 并投影到验证证据 / 订单归属契约。 +依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。 +逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的 + 锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。 """ from __future__ import annotations @@ -17,10 +19,21 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id _ID_RE = re.compile(r"(? list[ReservationRegionCandidate]: - """从区域原文提取候选;有行号归明细,无行号归订单头。""" + """从区域原文提取候选;有行号归明细,无行号归订单头。 + + 核心逻辑:同行须含 Reservation 标签;行号支持 ``line#1`` / ``for line#1`` / + ``L#1`` / ``LN#1`` 等写法,命中后 scope=line,禁止误写入订单头。 + """ candidates: list[ReservationRegionCandidate] = [] for raw_line in (str(text or '').splitlines() or [str(text or '')]): line = raw_line.strip() @@ -58,7 +75,8 @@ def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidat line_match = _LINE_RE.search(line) line_no = None if line_match: - line_no = int(line_match.group(1) or line_match.group(2)) + captured = next((group for group in line_match.groups() if group is not None), None) + line_no = int(captured) if captured is not None else None scope = 'line' if line_no is not None else 'header' status = 'mapped' if line_no is not None else 'header' for value in dict.fromkeys(ids): @@ -86,22 +104,147 @@ def extract_reservation_from_vendor_comments_pages( """从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。 核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定 - 页码或矩形取值依据。缺少起止锚点时返回稳定原因,由调用方转人工复核。 + 页码或矩形取值依据。起止标题按行首短语匹配(允许「Terms and Conditions of …」等 + 加长标题);缺少起始锚点时不扫描;缺少结束锚点时仍返回已累计窗内候选,但附带稳 + 定原因,由调用方标 Review,禁止当成可自动建单封闭证据。 """ started = False window_lines: list[str] = [] for _page_no, glyphs in sorted(pages, key=lambda item: item[0]): for line in visual_text_lines(glyphs): if not started: - if _VENDOR_COMMENTS_HEADING_RE.fullmatch(line): + if _VENDOR_COMMENTS_HEADING_RE.match(line): started = True continue - if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line): + if _TERMS_AND_CONDITIONS_HEADING_RE.match(line): return extract_reservation_from_region_text('\n'.join(window_lines)), None window_lines.append(line) if not started: return [], 'vendor_comments_anchor_missing' - return [], 'terms_and_conditions_anchor_missing' + # 结束锚点缺失:保留窗内候选供验证/盲测展示与人工复核,不能假装封闭成功。 + return extract_reservation_from_region_text('\n'.join(window_lines)), 'terms_and_conditions_anchor_missing' + + +def reservation_region_candidates_from_layout( + *, + definition: dict[str, Any] | None, + layout: dict[str, Any] | None, +) -> dict[str, Any]: + """仅当模板标注了 reservation_id_region 时,按 Vendor Comments→Terms 提取候选。 + + 核心逻辑:page_no/region 只表示专区已启用,正式取值必须与画布预览、盲测、 + 正式解析共用同一锚点窗,禁止再按保存矩形截取。 + + Args: + definition: Profile definition;无 reservation_id_region 时不扫描。 + layout: 含 coordinate_evidence.page_glyphs 的版面快照。 + + Returns: + ``{'candidates': [...], 'reason': str | None}``;reason 非空表示锚点异常。 + """ + raw = definition if isinstance(definition, dict) else {} + if not isinstance(raw.get('reservation_id_region'), dict): + return {'candidates': [], 'reason': None} + evidence = layout.get('coordinate_evidence') if isinstance(layout, dict) else None + evidence = evidence if isinstance(evidence, dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + pages = [ + (int(page_no), glyphs) + for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) + ] + candidates, reason = extract_reservation_from_vendor_comments_pages(pages) + return {'candidates': candidates, 'reason': reason} + + +def project_reservation_onto_validation_evidence( + evidence: dict[str, Any], + *, + candidates: list[dict[str, object]], + reason: str | None, + schema_fields: dict[str, dict[str, Any]], +) -> dict[str, Any]: + """将专区候选投影到验证页共用的 header_fields / lines 证据 DTO。 + + 核心逻辑:复用 apply_reservation_region_candidates 归属契约;锚点缺失或冲突时 + 写入 reservation_region_*,不臆造字段值。 + + Args: + evidence: 现有 validation_evidence。 + candidates: 锚点窗候选。 + reason: 锚点扫描失败原因;有值时强制 needs_review。 + schema_fields: field_id → Schema 字段(须含 enabled reservation_id)。 + + Returns: + 新的 evidence 字典;未启用专区字段时仅透传或附加 review 元数据。 + """ + projected = { + 'header_fields': [ + dict(item) for item in (evidence.get('header_fields') or []) if isinstance(item, dict) + ], + 'lines': [ + { + 'row_index': int(line.get('row_index') or index), + 'fields': [ + dict(field) for field in (line.get('fields') or []) if isinstance(field, dict) + ], + } + for index, line in enumerate(evidence.get('lines') or []) + if isinstance(line, dict) + ], + 'cross_checks': dict(evidence.get('cross_checks') or {}), + } + reservation_scope = { + str(item.get('scope') or ''): item + for item in schema_fields.values() + if isinstance(item, dict) and str(item.get('field_code') or '') == 'reservation_id' + } + if reason: + projected['reservation_region_status'] = 'needs_review' + projected['reservation_region_review_reasons'] = [str(reason)] + if not candidates and not reason: + return projected + + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None, + line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None, + line_count=len(projected['lines']), + ) + header_target = reservation_scope.get('header') + if applied.header_value and header_target: + projected['header_fields'] = [ + item for item in projected['header_fields'] + if str(item.get('field_code') or '') != 'reservation_id' + ] + [{ + 'field_id': str(header_target.get('field_id') or ''), + 'field_code': 'reservation_id', + 'raw_value': applied.header_value, + 'normalized_value': applied.header_value, + 'status': 'passed', + 'issues': [], + }] + line_target = reservation_scope.get('line') + if line_target: + for line_no, value in applied.line_values.items(): + if line_no < 1 or line_no > len(projected['lines']): + continue + line = projected['lines'][line_no - 1] + line['fields'] = [ + item for item in line['fields'] + if str(item.get('field_code') or '') != 'reservation_id' + ] + [{ + 'field_id': str(line_target.get('field_id') or ''), + 'field_code': 'reservation_id', + 'raw_value': value, + 'normalized_value': value, + 'status': 'passed', + 'issues': [], + }] + if applied.needs_review: + projected['reservation_region_status'] = 'needs_review' + projected['reservation_region_review_reasons'] = list(applied.review_reasons) + return projected def apply_reservation_region_candidates( diff --git a/backend/pytest.ini b/backend/pytest.ini index 821d6622..128fd7e5 100644 --- a/backend/pytest.ini +++ b/backend/pytest.ini @@ -1,5 +1,6 @@ [pytest] markers = + integration: optional integration tests that require external services or local DB snapshots pure_unit: skip Flask app/DB creation unless the test requests the app fixture auto_rpa: enable shipping notice auto RPA / auto progress in test config inventory_source_gate: skip default Dublin destination injection for inventory source gate tests diff --git a/backend/tests/test_contract_payment_ledger_focus.py b/backend/tests/test_contract_payment_ledger_focus.py new file mode 100644 index 00000000..23f21fd9 --- /dev/null +++ b/backend/tests/test_contract_payment_ledger_focus.py @@ -0,0 +1,117 @@ +""" +backend/tests/test_contract_payment_ledger_focus.py + +用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。 +依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。 +逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。 +""" + +from __future__ import annotations + +from datetime import date + +from app import db +from app.models import ContractPaymentContract, ContractPaymentNode, User +from app.services.contract_payment.ledger_focus import ledger_focus_counts + + +def _create_user(*, username: str) -> User: + """创建具备合同付款预警访问权的落库用户。""" + user = User( + username=username, + email=f'{username}@example.com', + role='user', + status='active', + real_name=f'{username}-实名', + employee_id=f'{username.upper()}-EMP', + department='采购部', + ) + user.set_feature_permissions({'contract_payment.access': True}) + user.set_password('password123') + db.session.add(user) + db.session.commit() + db.session.refresh(user) + db.session.expunge(user) + return user + + +def _auth_headers(user: User) -> dict[str, str]: + """生成测试鉴权头。""" + return { + 'X-User-Id': str(user.id), + 'X-Username': user.username, + 'Content-Type': 'application/json', + } + + +def _add_contract(*, contract_no: str, status: str = 'active') -> ContractPaymentContract: + """写入一份已进入台账的合同。""" + contract = ContractPaymentContract( + contract_no=contract_no, + parse_status='parsed', + status=status, + ) + db.session.add(contract) + db.session.flush() + return contract + + +def _add_node(contract: ContractPaymentContract, *, due: date | None, node_status: str = 'active') -> None: + """写入一个付款节点,供汇总卡按到期日分类。""" + db.session.add(ContractPaymentNode( + contract_id=contract.id, + node_code=f'prepayment-{contract.id}', + node_type='prepayment', + status=node_status, + due_date=due, + offset_days=0, + reminder_days=14, + )) + + +def _seed_focus_contracts() -> None: + """构造四张汇总卡各自至少命中一份的台账合同。""" + today = date(2026, 9, 10) + due = _add_contract(contract_no='HT-FOCUS-DUE') + _add_node(due, due=today.replace(day=14)) + overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE') + _add_node(overdue, due=date(2026, 8, 20)) + _add_contract(contract_no='HT-FOCUS-NEEDS') + month = _add_contract(contract_no='HT-FOCUS-MONTH') + _add_node(month, due=date(2026, 9, 28)) + db.session.commit() + + +def test_ledger_focus_counts_by_contract(app): + """四张汇总卡均按合同计数;本月应付只含本自然月未付合同。""" + with app.app_context(): + _seed_focus_contracts() + counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10)) + # 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。 + assert counts['due'] == 1 + assert counts['overdue'] == 1 + assert counts['needs_completion'] == 1 + assert counts['due_this_month'] == 2 + + +def test_list_contracts_focus_filters_ledger(client, app, monkeypatch): + """点汇总卡后列表只返回对应合同;汇总接口不跟 keyword。""" + monkeypatch.setattr( + 'app.services.contract_payment.ledger_focus.business_today', + lambda today=None: today or date(2026, 9, 10), + ) + with app.app_context(): + user = _create_user(username='cp_focus_list') + _seed_focus_contracts() + + headers = _auth_headers(user) + overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers) + summary = client.get('/api/contract-payment/contracts/summary', headers=headers) + empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers) + # 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。 + assert overdue.status_code == 200 + data = overdue.get_json()['data'] + assert data['total'] == 1 + assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE' + assert summary.get_json()['data']['overdue'] == 1 + assert empty.get_json()['data']['total'] == 0 diff --git a/backend/tests/test_contract_payment_list.py b/backend/tests/test_contract_payment_list.py new file mode 100644 index 00000000..b3502c49 --- /dev/null +++ b/backend/tests/test_contract_payment_list.py @@ -0,0 +1,98 @@ +""" +backend/tests/test_contract_payment_list.py + +用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。 +依赖:Flask test client、ContractPaymentContract、用户功能权限。 +逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。 +""" + +from __future__ import annotations + +from app import db +from app.models import ContractPaymentContract, User + + +def _create_user(*, username: str) -> User: + """创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。""" + user = User( + username=username, + email=f'{username}@example.com', + role='user', + status='active', + real_name=f'{username}-实名', + employee_id=f'{username.upper()}-EMP', + department='采购部', + ) + user.set_feature_permissions({'contract_payment.access': True}) + user.set_password('password123') + db.session.add(user) + db.session.commit() + db.session.refresh(user) + db.session.expunge(user) + return user + + +def _auth_headers(user: User) -> dict[str, str]: + """生成测试鉴权头。""" + return { + 'X-User-Id': str(user.id), + 'X-Username': user.username, + 'Content-Type': 'application/json', + } + + +def _seed_parsed_contracts() -> None: + """写入两份已进入台账的合同,供应商名称可区分。""" + db.session.add_all( + [ + ContractPaymentContract( + contract_no='HT-20260903-30622-0', + workflow_no='5203-2609020001', + purchase_order_no='5203-2609020001', + supplier_name='诺亘(上海)工业自动化有限公司', + parse_status='parsed', + status='active', + ), + ContractPaymentContract( + contract_no='HT-20260903-30612-0', + workflow_no='5203-2608270005', + purchase_order_no='5203-2608270005', + supplier_name='无锡市质谨机电科技有限公司', + parse_status='parsed', + status='active', + ), + ] + ) + db.session.commit() + + +def test_list_contracts_filters_by_supplier_name(client, app): + """关键词命中供应商名称时只返回对应合同,不误伤其他供应商。""" + with app.app_context(): + user = _create_user(username='cp_list_supplier') + _seed_parsed_contracts() + + headers = _auth_headers(user) + res = client.get('/api/contract-payment/contracts?keyword=诺亘', headers=headers) + assert res.status_code == 200 + data = res.get_json()['data'] + # 关键断言:供应商模糊匹配生效,且仍走 parsed 台账口径。 + assert data['total'] == 1 + assert data['items'][0]['supplier_name'] == '诺亘(上海)工业自动化有限公司' + assert data['items'][0]['contract_no'] == 'HT-20260903-30622-0' + + +def test_list_contracts_keyword_still_matches_contract_and_po(client, app): + """合同号、采购单号原有检索不能被供应商筛选挤掉。""" + with app.app_context(): + user = _create_user(username='cp_list_keyword') + _seed_parsed_contracts() + + headers = _auth_headers(user) + by_po = client.get('/api/contract-payment/contracts?keyword=5203-2608270005', headers=headers) + by_contract = client.get('/api/contract-payment/contracts?keyword=HT-20260903-30622-0', headers=headers) + # 关键断言:原合同号/采购单号路径仍精确命中。 + assert by_po.get_json()['data']['total'] == 1 + assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005' + assert by_contract.get_json()['data']['total'] == 1 + assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0' diff --git a/backend/tests/test_contract_payment_parse.py b/backend/tests/test_contract_payment_parse.py index f1685fb5..8731aa2a 100644 --- a/backend/tests/test_contract_payment_parse.py +++ b/backend/tests/test_contract_payment_parse.py @@ -1,9 +1,9 @@ """ backend/tests/test_contract_payment_parse.py -用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配及周汇总摘要。 -依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)。 -逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信。 +用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。 +依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。 +逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。 """ from datetime import date, datetime @@ -17,10 +17,17 @@ from app.models import ( ContractPaymentNode, User, ) +from io import BytesIO + +from openpyxl import load_workbook + from app.services.contract_payment.alert_service import ( bind_contract_owner_from_applicant, build_weekly_alert_summary, generate_alerts, + _alert_status_label, + _build_excel, + _recipient_display_name, ) from app.services.contract_payment import parse_service from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text @@ -549,6 +556,81 @@ def test_weekly_alert_summary_counts_pending_and_next_friday(app): assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z" +def test_weekly_excel_writes_recipient_real_name_not_role(app): + """关键断言:企微 Excel 列名为「收件人」,单元格写系统用户真实姓名,不再写岗位名称。""" + with app.app_context(): + owner = User( + username="excel-owner", + email="excel-owner@example.com", + status="active", + real_name="张三", + ) + db.session.add(owner) + db.session.flush() + contract = ContractPaymentContract( + contract_no="HT-EXCEL-1", + purchase_order_no="PO-1", + supplier_name="苏州供应商", + owner_user_id=owner.id, + status="active", + ) + db.session.add(contract) + db.session.flush() + node = ContractPaymentNode( + contract_id=contract.id, + node_code="shipment", + node_type="shipment", + status="active", + due_date=date(2026, 9, 1), + ) + db.session.add(node) + db.session.flush() + alert = ContractPaymentAlert( + contract_id=contract.id, + node_id=node.id, + trigger_key="round:1:date:2026-09-01", + recipient_user_id=owner.id, + alert_round=1, + status="pending", + ) + db.session.add(alert) + db.session.commit() + + data, summary = _build_excel([(alert, contract, node, owner)]) + wb = load_workbook(BytesIO(data)) + headers = [cell.value for cell in wb.active[1]] + row = [cell.value for cell in wb.active[2]] + + assert "收件岗位" not in headers + assert headers[10] == "收件人" + assert row[10] == "张三" + assert row[11] == "待发送" + assert "pending" not in row + assert "采购负责人" not in row + assert summary["total"] == 1 + + +def test_recipient_display_name_falls_back_to_username(app): + """关键断言:真实姓名为空时 Excel 收件人回退用户名,而不是岗位标签。""" + with app.app_context(): + named = User(username="buyer", email="named@example.com", status="active", real_name="李采购") + unnamed = User(username="buyer02", email="unnamed@example.com", status="active", real_name=" ") + + assert _recipient_display_name(named) == "李采购" + assert _recipient_display_name(unnamed) == "buyer02" + assert _recipient_display_name(None) == "—" + + +def test_alert_status_label_uses_chinese(): + """关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。""" + assert _alert_status_label("pending") == "待发送" + assert _alert_status_label("sent") == "已发送" + assert _alert_status_label("failed") == "发送失败" + assert _alert_status_label("resolved") == "已关闭" + assert _alert_status_label("unknown-code") == "unknown-code" + assert _alert_status_label(None) == "—" + + def test_erp_payment_amount_matches_the_corresponding_stage(): """关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。""" paid_node_ids = resolve_paid_node_ids( diff --git a/backend/tests/test_contract_payment_permissions.py b/backend/tests/test_contract_payment_permissions.py index ce7bf381..1a58b4a9 100644 --- a/backend/tests/test_contract_payment_permissions.py +++ b/backend/tests/test_contract_payment_permissions.py @@ -3,7 +3,7 @@ backend/tests/test_contract_payment_permissions.py 用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。 依赖:User 功能权限、Flask test client、contract_payment 蓝图。 -逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账;关闭 admin 覆盖后同样 403。 +逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。 """ from __future__ import annotations @@ -128,3 +128,23 @@ def test_contract_payment_api_allows_granted_user(client, app): body = list_res.get_json() assert body.get('success') is True assert 'items' in (body.get('data') or {}) + + +def test_contract_payment_jobs_require_admin(client, app): + """已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。""" + with app.app_context(): + granted = _create_user( + username='cp_api_jobs_denied', + feature_permissions={'contract_payment.access': True}, + ) + + headers = _auth_headers(granted) + # 关键断言:访问权不等于操作权,手动任务仅管理员。 + for path in ( + '/api/contract-payment/sync', + '/api/contract-payment/alerts/run', + '/api/contract-payment/alerts/weekly-run', + ): + res = client.post(path, headers=headers, json={}) + assert res.status_code == 403, path + assert _json_error(res)['code'] == 'CONTRACT_PAYMENT.ADMIN_REQUIRED' diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index 538c05c2..44cee41f 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -1,7 +1,8 @@ """验证 EML 正文补充表的确定性解析、关联和数量保护。 依赖:正文补充解析器与合并服务。 -逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威,歧义稳定进入复核。 +逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号, + 其次 PO+预约号,歧义稳定进入复核。 """ from __future__ import annotations @@ -345,6 +346,81 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_ assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn' +def test_email_supplement_po_reservation_injects_hint_when_parts_do_not_match(): + """同 PO 下 PDF 已有预约号、邮件仅 APN 不对料号时,按 reservation 对齐灌入库存源线索。 + + 回归:AWS allocation 表 Component APN 对不上 Wistron MPN 时,不得因缺 po_mpn + 把多行 VMI-* 线索整单丢掉。 + """ + order = { + '_hxops_intake_id': 1, + 'header_fields': [{'field_id': 'po', 'observations': [{'value': '16776707'}]}], + 'lines': [ + {'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]}, + {'field_id': 'reservation', 'observations': [{'value': '2000484577'}]}, + {'field_id': 'qty', 'observations': [{'value': 30}]}, + ]}, + {'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]}, + {'field_id': 'reservation', 'observations': [{'value': '2000484578'}]}, + {'field_id': 'qty', 'observations': [{'value': 24}]}, + ]}, + ], + 'conflicts': [], + } + supplement = { + 'document_id': 44, + 'rows': [ + { + 'customer_po_number': '16776707', + 'part_number': '504-006055-001', + 'reservation_id': '2000484577', + 'inventory_source_hint': 'VMI-RTM01', + 'evidence': {'inventory_source_hint': {'raw_value': 'VMI-RTM01'}}, + }, + { + 'customer_po_number': '16776707', + 'part_number': '504-006056-001', + 'reservation_id': '2000484578', + 'inventory_source_hint': 'VMI-DUB', + 'evidence': {'inventory_source_hint': {'raw_value': 'VMI-DUB'}}, + }, + ], + } + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA, + )[0] + # 关键断言:关联码为 po_reservation;两行分别灌入对应线索,数量不被覆盖。 + assert merged['_hxops_email_supplement_relation'] == 'po_reservation' + assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-RTM01' + assert _value(merged['lines'][1]['fields'], 'source') == 'VMI-DUB' + assert _value(merged['lines'][0]['fields'], 'qty') == 30 + assert _value(merged['lines'][1]['fields'], 'qty') == 24 + assert not any(item.get('reason') == 'supplement_relation_ambiguous' for item in merged['conflicts']) + + +def test_email_supplement_po_mpn_still_preferred_over_po_reservation(): + """料号能精确命中时仍走 po_mpn,不得因两边都有预约号改走 reservation 档。""" + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'reservation', 'observations': [{'value': '2000484577'}], + }) + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: {'document_id': 44, 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': 'D4-A08AR12000002', + 'reservation_id': '2000484577', + 'inventory_source_hint': 'DSB CMH', + 'evidence': {}, + }]}}, + schema_definition=SCHEMA, + )[0] + assert merged['_hxops_email_supplement_relation'] == 'po_mpn' + assert _value(merged['lines'][0]['fields'], 'source') == 'DSB CMH' + + def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match(): """唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。""" result = merge_email_supplements( diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index eda5a638..02c2d8a1 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -323,6 +323,57 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp assert not (failed_dir / trigger_path.name).exists() +def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tmp_path): + """配置测试无订单 Attempt/Gate 身份:不得 trigger_identity_invalid,须回调专用 ready。""" + worker = _load_freight_rpa_worker() + trigger_dir = tmp_path / "triggers" + drop_dir = tmp_path / "drop" + processed_dir = trigger_dir / "processed" + failed_dir = trigger_dir / "failed" + trigger_dir.mkdir() + drop_dir.mkdir() + run_no = "CONFIG-DSV360_AWSBI_BYAWSPRD01-20260909020428918536" + trigger_path = trigger_dir / f"inventory_export_batch_{run_no}.json" + # 与 inventory_configuration_test.start_test_export 写入形状一致: + # trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。 + trigger_path.write_text(json.dumps({ + "action": "inventory_export_batch", + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": f"{run_no}:batch:C1", + "batch_run_no": run_no, + "run_no": run_no, + "trigger_type": "configuration_test", + "configuration_test_run_id": 42, + "requested_at": "2026-09-09T02:04:28.918536", + "inventory_sources": [{ + "source_code": "DSV360_AWSBI_BYAWSPRD01", + "connector_type": "dbs", + "worker_connector_type": "dsv360", + "warehouse_id": "BYAWSPRD01", + "login_url": "https://s360.dbschenker.com/", + "entry_url": "https://s360.dbschenker.com/", + "navigation": {}, + "parameters": [], + "query": {}, + "credential_envelope": {}, + }], + }), encoding="utf-8") + callbacks: list[tuple[str, dict]] = [] + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) + + worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) + + assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks) + ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready")) + assert ready["run_no"] == run_no + assert ready["status"] == "success" + assert ready.get("file_path") + assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks) + assert (processed_dir / trigger_path.name).is_file() + assert not (failed_dir / trigger_path.name).exists() + + def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path): """Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。""" worker = _load_freight_rpa_worker() diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index cc65faaf..0804a083 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -165,6 +165,45 @@ def test_dsv_report_inventory_rows_returns_false_when_no_data_within_deadline(mo assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=2_500) is False +def test_ensure_dsv_inventory_rows_retries_view_report_then_allows_export_fallback(monkeypatch): + """DOM 无行时重试 View Report;仍无行不得抛空,应继续导出由 Excel 判空。""" + worker = _load_dsv_report_export() + clicks: list[str] = [] + waits: list[int] = [] + row_outcomes = iter([False, False]) + + monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000) + monkeypatch.setattr( + worker, + "_wait_dsv_report_inventory_rows", + lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)), + ) + monkeypatch.setattr( + worker, + "_click_dsv_view_report", + lambda page_arg: clicks.append("view"), + ) + monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms: None) + + worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location") + + assert clicks == ["view"] + assert waits == [5_000, 5_000] + + +def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeypatch): + """首次轮询已有明细行时不得再点 View Report。""" + worker = _load_dsv_report_export() + clicks: list[str] = [] + monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000) + monkeypatch.setattr(worker, "_wait_dsv_report_inventory_rows", lambda page_arg, timeout_ms: True) + monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view")) + + worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location") + + assert clicks == [] + + def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch): """单票 DSV 导出应走与批量相同的 session + export 函数。""" worker = _load_worker() diff --git a/backend/tests/test_inventory_configuration_test.py b/backend/tests/test_inventory_configuration_test.py index c537401c..d6b37079 100644 --- a/backend/tests/test_inventory_configuration_test.py +++ b/backend/tests/test_inventory_configuration_test.py @@ -145,6 +145,29 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp assert ShippingInventoryConfigurationTestRun.query.count() == 1 +def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, tmp_path): + """Worker 回传 Windows drop 路径时,必须映射到 Linux 共享目录再分析,不能报「文件不存在」。""" + drop_dir = tmp_path / 'inventory_drop' + drop_dir.mkdir() + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir) + with app.app_context(), patch( + 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', + ): + source = _source() + started = inventory_configuration_test.start_test_export(source['id'], actor_id=None) + result_file = drop_dir / f"inventory_{started['run_no']}_DSV360_BYAWSPRD01.xlsx" + _workbook(result_file) + windows_path = rf'C:\HxopsRpaTest\data\inventory_drop\{result_file.name}' + completed = inventory_configuration_test.report_test_export({ + 'run_no': started['run_no'], 'status': 'success', 'file_path': windows_path, + }) + assert completed['status'] == 'completed' + assert completed.get('error_message') in (None, '') + assert not ShippingInventoryFile.query.count() + + def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path): """已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。""" app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') diff --git a/backend/tests/test_inventory_rpa_download_save_fallback.py b/backend/tests/test_inventory_rpa_download_save_fallback.py new file mode 100644 index 00000000..2aca0357 --- /dev/null +++ b/backend/tests/test_inventory_rpa_download_save_fallback.py @@ -0,0 +1,117 @@ +""" +inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。 +""" + +from __future__ import annotations + +import importlib.util +import sys +import tempfile +from pathlib import Path + + +def _load_worker(): + module_path = ( + Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + ) + scripts_dir = str(module_path.parent) + if scripts_dir not in sys.path: + sys.path.insert(0, scripts_dir) + # common/ 需可 import download_artifact_fallback + common_dir = str(module_path.parent.parent / "common") + if common_dir not in sys.path: + sys.path.insert(0, common_dir) + spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _ClosedBrowserDownload: + """模拟 Playwright Download:save_as 时浏览器已关闭。""" + + suggested_filename = "OnHandInventory.xlsx" + + def save_as(self, dest: str) -> None: + raise RuntimeError("Download.save_as: Target page, context or browser has been closed") + + +def test_save_batch_download_falls_back_when_browser_closed(monkeypatch): + """save_as 因浏览器关闭失败、目录已有稳定 xlsx 时,应改名落盘并返回规范路径。""" + worker = _load_worker() + with tempfile.TemporaryDirectory() as tmp: + drop_dir = Path(tmp) / "drop" + drop_dir.mkdir() + (drop_dir / "noise.txt").write_text("old", encoding="utf-8") + landed = drop_dir / "chromium_download.xlsx" + landed.write_bytes(b"PK" + b"0" * 600) + + monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None) + + out = worker._save_batch_download( + _ClosedBrowserDownload(), + drop_dir, + "BATCH-RUN-1", + {"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"}, + baseline_names={"noise.txt"}, + ) + + assert out.exists() + assert out.parent == drop_dir + assert "DSV360_AWSSG" in out.name + assert "AWSSG" in out.name + assert out.suffix == ".xlsx" + assert not landed.exists() + + +def test_save_batch_download_reraises_when_fallback_missing(monkeypatch): + """浏览器关闭且目录无新文件时,应继续抛出原 save_as 错误。""" + worker = _load_worker() + with tempfile.TemporaryDirectory() as tmp: + drop_dir = Path(tmp) / "drop" + drop_dir.mkdir() + + monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None) + monkeypatch.setattr( + worker, + "_wait_for_new_download_file", + lambda **_kwargs: None, + ) + + try: + worker._save_batch_download( + _ClosedBrowserDownload(), + drop_dir, + "BATCH-RUN-2", + {"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"}, + baseline_names=set(), + fallback_timeout_seconds=0.1, + ) + raise AssertionError("expected RuntimeError") + except RuntimeError as exc: + # 断言:错误信息仍指向浏览器关闭,避免被吞成模糊失败 + assert "has been closed" in str(exc).lower() + + +def test_save_download_falls_back_when_browser_closed(monkeypatch): + """单票路径同样在 save_as 浏览器关闭后走目录兜底。""" + worker = _load_worker() + with tempfile.TemporaryDirectory() as tmp: + drop_dir = Path(tmp) / "drop" + drop_dir.mkdir() + landed = drop_dir / "raw.xlsx" + landed.write_bytes(b"PK" + b"0" * 600) + monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None) + + out = worker._save_download( + _ClosedBrowserDownload(), + drop_dir, + "OT-1", + "DSV360_AWSSG", + baseline_names=set(), + ) + + assert out.exists() + assert "DSV360_AWSSG" in out.name + assert not landed.exists() diff --git a/backend/tests/test_kb_source_file_download.py b/backend/tests/test_kb_source_file_download.py new file mode 100644 index 00000000..b153dc4c --- /dev/null +++ b/backend/tests/test_kb_source_file_download.py @@ -0,0 +1,80 @@ +""" +tests/test_kb_source_file_download.py + +用途:知识库源文件下载的 Content-Disposition 与中文文件名。 +依赖:kb.common.build_content_disposition、documents 路由、kb 模型。 +逻辑:纯函数校验 RFC 5987 头;API 用例确认 ?download=1 返回原名且正文为原件。 +""" +from pathlib import Path +from urllib.parse import quote + +from app import db +from app.api.kb.common import build_content_disposition +from app.core.auth.jwt import issue_local_access_token +from app.models import KbDocument, KbDocumentVersion, KbGroup, User + + +def test_build_content_disposition_quotes_ascii_and_keeps_utf8_filename(): + """ + ASCII 回退名必须加引号,真实中文名在 filename* 段。 + + 关键断言:不得出现无引号的 `filename=docx; filename*=...`,否则浏览器会把两段拼成怪名。 + """ + filename = '企业文化.docx' + header = build_content_disposition(filename, as_attachment=True) + assert header.startswith('attachment; filename="download.docx"; filename*=UTF-8\'\'') + assert quote(filename, safe='') in header + assert 'filename=docx;' not in header + + +def test_source_file_download_uses_original_filename(app, client, tmp_path): + """ + 工作台源文件下载应以下载附件返回,且 Content-Disposition 含原始中文文件名。 + + 关键断言:响应体是原件字节;filename* 为 企业文化.docx;ASCII 回退名带引号。 + """ + storage_root = tmp_path / 'kb-storage' + storage_root.mkdir() + source_name = '企业文化.docx' + source_path = storage_root / 'corp-culture.docx' + source_bytes = b'PK\x03\x04fake-docx' + source_path.write_bytes(source_bytes) + + app.config['KB_STORAGE_ROOT'] = str(storage_root) + + with app.app_context(): + user = User( + username='kb-download-admin', + email='kb-download-admin@example.com', + role='admin', + status='active', + ) + user.set_password('password123') + group = KbGroup(name='源文件下载分组') + document = KbDocument(group=group, title='企业文化', status='uploaded') + version = KbDocumentVersion( + document=document, + version_no=1, + status='uploaded', + is_current=True, + source_file_name=source_name, + source_file_path=str(source_path), + source_file_ext='docx', + source_file_size=len(source_bytes), + ) + db.session.add_all([user, group, document, version]) + db.session.commit() + version_id = version.id + token = issue_local_access_token(user) + + res = client.get( + f'/api/kb/document-versions/{version_id}/source-file?download=1', + headers={'Authorization': f'Bearer {token}'}, + ) + assert res.status_code == 200 + assert res.data == source_bytes + disposition = res.headers.get('Content-Disposition', '') + assert 'attachment' in disposition + assert f'filename*=UTF-8\'\'{quote(source_name, safe="")}' in disposition + assert 'filename="download.docx"' in disposition + assert 'filename=docx;' not in disposition diff --git a/backend/tests/test_line_field_supplement_merge.py b/backend/tests/test_line_field_supplement_merge.py new file mode 100644 index 00000000..fc21c48b --- /dev/null +++ b/backend/tests/test_line_field_supplement_merge.py @@ -0,0 +1,309 @@ +""" +tests/test_line_field_supplement_merge.py + +用途:覆盖同文档 COO/明细字段补充表按 LN 合并的契约。 +依赖:line_field_supplement_merge、order_profile.TableRegionProfile、 + order_extraction_workflow._pick_overlapping_layout_table。 +逻辑:断言空补、前缀补全、冲突不覆盖、LN 歧义/缺失与禁止改 qty; + 成功补齐仅表级 reasons、不写入 issues;以及补充区与 MinerU 表重叠时的物理表选取。 +""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile +from app.services.shipping_notice.line_field_supplement_merge import ( + REASON_APPLIED, + REASON_CONFLICT, + REASON_LN_AMBIGUOUS, + merge_line_field_supplement, + normalize_line_start_key, + normalize_part_value, +) +from app.services.shipping_notice.order_extraction_workflow import ( + _pick_overlapping_layout_table, +) + + +def test_normalize_line_start_and_part_values(): + """关键断言:行号去前导零对齐;料号仅去空白。""" + assert normalize_line_start_key(' 02 ') == '2' + assert normalize_line_start_key('00010') == '10' + assert normalize_part_value('WTP-B3- A08') == 'WTP-B3-A08' + + +def test_merge_fills_empty_and_prefix_without_touching_qty(): + """空值直补、截断前缀补全,数量保持主表原值。""" + main = [ + {'customer_po_line_no': '1', 'customer_part_number': '', 'part_number': 'B3-', 'qty': '30'}, + { + 'customer_po_line_no': '2', + 'customer_part_number': 'WTP-B3-', + 'part_number': '', + 'qty': '3', + }, + ] + supplement = [ + { + 'customer_po_line_no': '1', + 'customer_part_number': 'WTP-B3-A08AR11000001', + 'part_number': 'B3-A08AR11000001', + }, + { + 'customer_po_line_no': '2', + 'customer_part_number': 'WTP-B3-A08AR10000017-A6', + 'part_number': 'B3-A08AR10000017-A6', + }, + ] + + merged, reasons = merge_line_field_supplement(main, supplement) + + assert merged[0]['customer_part_number'] == 'WTP-B3-A08AR11000001' + assert merged[0]['part_number'] == 'B3-A08AR11000001' + assert merged[0]['qty'] == '30' + assert merged[1]['customer_part_number'] == 'WTP-B3-A08AR10000017-A6' + assert merged[1]['part_number'] == 'B3-A08AR10000017-A6' + assert merged[1]['qty'] == '3' + assert REASON_APPLIED in reasons + assert REASON_CONFLICT not in reasons + # 关键断言:成功补齐不得进入行 issues,否则正式建单会被误判为 row_needs_review。 + assert REASON_APPLIED not in (merged[0].get('issues') or []) + assert REASON_APPLIED not in (merged[1].get('issues') or []) + + +def test_merge_conflict_does_not_overwrite(): + """两边完整且不同时保留主表并记冲突。""" + main = [{'customer_po_line_no': '1', 'part_number': 'MAIN-ONLY', 'qty': '1'}] + supplement = [{'customer_po_line_no': '1', 'part_number': 'COO-OTHER'}] + + merged, reasons = merge_line_field_supplement(main, supplement) + + assert merged[0]['part_number'] == 'MAIN-ONLY' + assert merged[0]['qty'] == '1' + assert REASON_CONFLICT in reasons + assert REASON_CONFLICT in merged[0]['issues'] + + +def test_merge_skips_ambiguous_line_numbers(): + """主表或补充表 LN 重复时不补该键。""" + main = [ + {'customer_po_line_no': '1', 'part_number': ''}, + {'customer_po_line_no': '1', 'part_number': ''}, + ] + supplement = [{'customer_po_line_no': '1', 'part_number': 'B3-A08'}] + + merged, reasons = merge_line_field_supplement(main, supplement) + + assert merged[0]['part_number'] == '' + assert merged[1]['part_number'] == '' + assert REASON_LN_AMBIGUOUS in reasons + + +def test_merge_workflow_shaped_rows(): + """workflow fields 列表形态同样可补齐。""" + main = [{ + 'status': 'needs_review', + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': '2'}, + {'field_code': 'customer_part_number', 'value': 'WTP-B3-'}, + {'field_code': 'qty', 'value': '3'}, + ], + 'issues': [], + }] + supplement = [{ + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': '2'}, + {'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'}, + {'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'}, + ], + }] + + merged, reasons = merge_line_field_supplement(main, supplement) + values = {item['field_code']: item['value'] for item in merged[0]['fields']} + + assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6' + assert values['part_number'] == 'B3-A08AR10000017-A6' + assert values['qty'] == '3' + assert REASON_APPLIED in reasons + assert REASON_APPLIED not in (merged[0].get('issues') or []) + + +def test_apply_line_field_supplement_uses_reconstructed_coo_rows(monkeypatch): + """关键断言:正式路径在主表截断后用补充表重建行补全料号。""" + from app.services.shipping_notice import order_extraction_workflow as workflow + + def _fake_reconstruct(**_kwargs): + return ( + [{ + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': '2'}, + {'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'}, + {'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'}, + ], + 'issues': [], + }], + 'customer_po_line_no', + ) + + monkeypatch.setattr(workflow, '_reconstruct_line_field_supplement_rows', _fake_reconstruct) + parsed = [{ + 'status': 'parsed', + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': '2'}, + {'field_code': 'customer_part_number', 'value': 'WTP-B3-'}, + {'field_code': 'part_number', 'value': ''}, + {'field_code': 'qty', 'value': '3'}, + ], + 'issues': [], + }] + merged, reasons = workflow._apply_line_field_supplement( + raw_profile={'definition': {}}, + layout={}, + parsed_rows=parsed, + schema_fields={}, + ) + values = {item['field_code']: item['value'] for item in merged[0]['fields']} + assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6' + assert values['part_number'] == 'B3-A08AR10000017-A6' + assert values['qty'] == '3' + assert REASON_APPLIED in reasons + + +def test_project_supplement_onto_validation_evidence(): + """关键断言:验证证据 lines 可被 COO 补齐且保留其它列。""" + from app.services.shipping_notice.line_field_supplement_merge import ( + project_line_field_supplement_onto_validation_evidence, + ) + + evidence = { + 'header_fields': [], + 'lines': [{ + 'row_index': 0, + 'fields': [ + {'field_code': 'customer_po_line_no', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []}, + {'field_code': 'customer_part_number', 'raw_value': 'WTP-B3-', 'normalized_value': 'WTP-B3-', 'status': 'passed', 'issues': []}, + {'field_code': 'qty', 'raw_value': '3', 'normalized_value': '3', 'status': 'passed', 'issues': []}, + ], + }], + 'cross_checks': {}, + } + updated, reasons = project_line_field_supplement_onto_validation_evidence( + evidence, + supplement_rows=[{ + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': '2'}, + {'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'}, + ], + }], + ) + part = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'customer_part_number') + qty = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'qty') + assert part['raw_value'] == 'WTP-B3-A08AR10000017-A6' + assert qty['raw_value'] == '3' + assert REASON_APPLIED in reasons + + +def test_line_field_supplement_region_rejects_non_part_bindings(): + """补充表绑定数量等业务字段必须失败。""" + payload = { + 'region_id': 'coo_lines', + 'page_scope': 'exact_page', + 'page_no': 1, + 'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9}, + 'region_role': 'line_field_supplement', + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [ + { + 'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', + 'region': {'x0': .2, 'y0': 0, 'x1': .4, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }, + ], + }], + } + with pytest.raises(ValidationError, match='line_field_supplement may only bind'): + TableRegionProfile.model_validate(payload) + + +def test_line_field_supplement_region_accepts_part_bindings(): + """补充表仅绑 LN + 料号字段可通过。""" + region = TableRegionProfile.model_validate({ + 'region_id': 'coo_lines', + 'page_scope': 'exact_page', + 'page_no': 1, + 'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9}, + 'region_role': 'line_field_supplement', + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [ + { + 'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'cpn', 'field_code': 'customer_part_number', 'scope': 'line', + 'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'pn', 'field_code': 'part_number', 'scope': 'line', + 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }, + ], + }], + }) + assert region.region_role == 'line_field_supplement' + + +def test_pick_overlapping_layout_table_prefers_max_vertical_overlap(): + """关键断言:同页重叠表取纵向重叠面积最大者;无重叠返回空。""" + page_size = {'width': 100.0, 'height': 100.0} + region = {'x0': 0.05, 'y0': 0.67, 'x1': 0.9, 'y1': 0.70} + tables = [ + { + 'table_id': 'header-ish', + 'page_no': 1, + 'bbox': {'x0': 5.0, 'y0': 10.0, 'x1': 90.0, 'y1': 40.0}, + }, + { + 'table_id': 'coo-table', + 'page_no': 1, + 'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0}, + }, + { + 'table_id': 'other-page', + 'page_no': 2, + 'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0}, + }, + ] + + table_id, bbox = _pick_overlapping_layout_table( + layout_tables=tables, + page_no=1, + region_relative=region, + page_size=page_size, + ) + + assert table_id == 'coo-table' + assert bbox == {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0} + + empty_id, empty_bbox = _pick_overlapping_layout_table( + layout_tables=tables, + page_no=1, + region_relative={'x0': 0.05, 'y0': 0.90, 'x1': 0.9, 'y1': 0.95}, + page_size=page_size, + ) + assert empty_id is None + assert empty_bbox is None diff --git a/backend/tests/test_order_document_profile_publish_check_service.py b/backend/tests/test_order_document_profile_publish_check_service.py index ae2a7bfa..1cd12b53 100644 --- a/backend/tests/test_order_document_profile_publish_check_service.py +++ b/backend/tests/test_order_document_profile_publish_check_service.py @@ -14,6 +14,7 @@ from app.extensions import db from app.models import ( ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, + ShippingOrderDocumentProfileDraftRevision, ShippingOrderDocumentProfileValidationRun, User, ) @@ -196,12 +197,19 @@ def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch): def test_report_blocks_when_overlap_failed(app, monkeypatch): - """关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。""" + """关键断言:当前草稿上的 overlap failed 展开真实门禁,不得误报 overlap_validation_stale。""" with app.app_context(): monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None) schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-overlap-create') lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft) failed_overlap = _overlap_run(draft, status='failed') + failed_overlap.summary_json = { + **dict(failed_overlap.summary_json or {}), + 'self_unique_hit_rate_training': 0.0, + 'training_sample_count': 2, + 'blind_sample_count': 0, + } + db.session.commit() monkeypatch.setattr( validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': failed_overlap.id, 'status': 'failed', 'stored_status': 'failed'}, @@ -211,10 +219,37 @@ def test_report_blocks_when_overlap_failed(app, monkeypatch): actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-overlap-report', ) keys = {str(item.get('key')) for item in report['blocking_items']} - assert 'overlap_validation_stale' in keys or 'overlap_validation_required' in keys or 'self_match_not_unique' in keys + assert 'self_match_not_unique' in keys + assert 'overlap_validation_stale' not in keys assert report['overlap_validation_run_id'] == failed_overlap.id +def test_blocking_from_overlap_marks_stale_only_on_checksum_drift(app): + """关键断言:仅 definition_checksum 漂移才标 stale;同 checksum 的 failed 展开指标。""" + with app.app_context(): + schema = _schema_version() + draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-stale-vs-failed') + revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by( + profile_id=draft['id'], revision_no=draft['draft_revision']['revision_no'], + ).one() + stale_run = _overlap_run(draft, status='passed') + stale_run.definition_checksum = 'not-current-checksum' + db.session.commit() + stale_keys = {item['key'] for item in checks._blocking_from_overlap(None, stale_run, revision)} + assert stale_keys == {'overlap_validation_stale'} + + failed_run = _overlap_run(draft, status='failed') + failed_run.summary_json = { + **dict(failed_run.summary_json or {}), + 'self_unique_hit_rate_training': 0.0, + 'training_sample_count': 1, + } + db.session.commit() + failed_keys = {item['key'] for item in checks._blocking_from_overlap(dict(failed_run.summary_json), failed_run, revision)} + assert 'self_match_not_unique' in failed_keys + assert 'overlap_validation_stale' not in failed_keys + + def test_report_invalidates_when_signature_cleared(app, monkeypatch): """关键断言:草稿签名引用清空后既有报告查询即 invalidated。""" with app.app_context(): diff --git a/backend/tests/test_order_extraction_pdf_po_split.py b/backend/tests/test_order_extraction_pdf_po_split.py index fd186a75..cbf8c50a 100644 --- a/backend/tests/test_order_extraction_pdf_po_split.py +++ b/backend/tests/test_order_extraction_pdf_po_split.py @@ -64,6 +64,18 @@ def _two_page_layout() -> dict: } +def test_approved_pdf_ignores_line_field_supplement_applied_issue(): + """关键断言:COO 成功补齐的审计码不得触发 row_needs_review。""" + row = _row('PO-1', 'P-1') + row['issues'] = ['line_field_supplement_applied'] + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=DEFINITION, table={'rows': [row]}, + ) + assert reason is None + assert len(orders or []) == 1 + + def test_approved_pdf_rejects_multiple_pos_in_one_pdf(): """同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。""" orders, reason = _build_approved_profile_order_result( @@ -160,13 +172,22 @@ def test_profile_without_reservation_region_does_not_scan_vendor_comments(): def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing(): - """专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。""" + """专区缺少结束锚点时,窗内候选可展示/归属,但订单必须标 needs_review。""" orders, reason = _build_approved_profile_order_result( unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]}, + reservation_region_candidates=[{ + 'value': '1000143920', 'scope': 'line', 'line_no': 1, + 'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped', + }], reservation_region_reason='terms_and_conditions_anchor_missing', ) assert reason is None - assert (orders or [])[0]['reservation_region_status'] == 'needs_review' - assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing'] + order = (orders or [])[0] + assert order['reservation_region_status'] == 'needs_review' + assert order['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing'] + assert any( + item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '1000143920' + for item in order['lines'][0]['fields'] + ) diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index a95d6730..bb8829f9 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -1717,3 +1717,37 @@ def test_table_region_profile_freezes_confirmed_visual_geometry_source_only(): }).visual_evidence_source == 'acroform_widget_geometry' with pytest.raises(ValueError, match='visual_evidence_source'): TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'}) + + +def test_strategy_needs_review_still_returns_best_effort_rows_for_display(monkeypatch): + """策略需复核时仍返回最佳努力明细,盲测/验证才能展示,不能整表吞掉。""" + from app.services.shipping_notice.document_layout import runtime_parse_strategy as strategy_module + from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy + + def _force_review(**_kwargs): + return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)) + + monkeypatch.setattr(strategy_module, 'resolve_runtime_parse_strategy', _force_review) + rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=_glyphs( + [('1', 10), ('PART-A', 80)], + [('2', 10), ('PART-B', 80)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}}, + ], + }], + line_start_field_code='customer_po_line_no', + ) + + assert strategy.status == 'needs_review' + assert [row.fields for row in rows] == [ + {'customer_po_line_no': '1', 'part_number': 'PART-A'}, + {'customer_po_line_no': '2', 'part_number': 'PART-B'}, + ] diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index 78f6ca8c..e803c194 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -710,6 +710,59 @@ def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app): assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}] +def test_coordinate_blind_candidate_keeps_rows_when_strategy_needs_review(app, monkeypatch): + """关键断言:策略需复核时盲测预览仍展示最佳努力明细,不能整表吞掉。""" + from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy + + with app.app_context(): + profile, user, documents = _published_profile_with_samples() + profile.definition_json = { + 'document_match': {'required_anchors': []}, + 'table_regions': [{ + 'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [ + {'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', + 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + ], + }], + }], 'order_field_layouts': [], + } + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}} + for index, char in enumerate('20') + ] + [ + {'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}} + for index, char in enumerate('PART-A') + ] + record_inline_layout_snapshot(documents[1], { + 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1}], + 'coordinate_evidence': { + 'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + db.session.commit() + + def _force_review(**_kwargs): + return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)) + + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.runtime_parse_strategy.resolve_runtime_parse_strategy', + _force_review, + ) + candidate = quality._candidate_for_sample( + profile=profile, document_id=documents[1].id, table_id='table-1', + ) + assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}] + + def test_profile_checksum_change_invalidates_approved_quality_credential(app): """关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。""" with app.app_context(): diff --git a/backend/tests/test_shipping_notice_inventory_rpa_archive.py b/backend/tests/test_shipping_notice_inventory_rpa_archive.py index 93ab9f2f..ca02bcfc 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_archive.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_archive.py @@ -10,8 +10,10 @@ from __future__ import annotations import json import zipfile +from datetime import datetime from io import BytesIO from pathlib import Path +from urllib.parse import quote import pytest @@ -27,8 +29,11 @@ from app.services.schedule.scheduler_service import ( from app.services.schedule.shipping_inventory_rpa_archive import ( inventory_raw_zip_available_from_summary, inventory_raw_zip_download_name, + inventory_rpa_attachment_stem, + inventory_rpa_result_excel_name, persist_inventory_rpa_raw_zip_archive, resolve_inventory_raw_zip_download, + _build_zip_entry_name, ) from tests.conftest import parse_api_error from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task @@ -160,10 +165,12 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p with zipfile.ZipFile(zip_path) as archive: names = archive.namelist() assert "manifest.json" in names - assert any(name.endswith(".xlsx") for name in names) + xlsx_names = [name for name in names if name.endswith(".xlsx")] + assert xlsx_names == ["001_DSV360_AWSBI_BYAWSCMH01.xlsx"] manifest = json.loads(archive.read("manifest.json").decode("utf-8")) assert manifest["run_no"] == run.run_no assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01" + assert manifest["files"][0]["file_name"] == "001_DSV360_AWSBI_BYAWSCMH01.xlsx" def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path): @@ -230,7 +237,9 @@ def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path) zip_path, file_name = resolve_inventory_raw_zip_download(run) assert zip_path.is_file() - assert file_name == inventory_raw_zip_download_name(run.run_no) + assert file_name == inventory_raw_zip_download_name(run) + assert file_name.endswith("-库存.zip") + assert file_name.startswith("库存RPA-") def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app): @@ -431,7 +440,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke task.notify_enabled = True task.notify_user_ids_json = [user.id] run.excel_file_data = b"schedule excel" - run.excel_file_name = "schedule.xlsx" + run.excel_file_name = inventory_rpa_result_excel_name(run) db.session.commit() _notify_schedule_run_wecom(task, run) @@ -442,8 +451,8 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke assert "run_id=" in captured[0] assert "raw_zip=1" in captured[0] assert "download=inventory_raw_zip" in captured[0] - assert "schedule.xlsx" in media_uploads - assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads + assert any(name.endswith("-结果.xlsx") for name in media_uploads) + assert any(name.endswith("-库存.zip") for name in media_uploads) assert file_sends == ["media-1", "media-2"] @@ -471,7 +480,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename( admin_jwt_headers, tmp_path, ): - """admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。""" + """admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。""" archive_dir = tmp_path / "inventory_archives" app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" @@ -497,7 +506,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename( run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run) db.session.commit() run_id = run.id - expected_name = inventory_raw_zip_download_name(run.run_no) + expected_name = inventory_raw_zip_download_name(run) res = client.get( f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip', @@ -505,12 +514,53 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename( ) assert res.status_code == 200 assert res.mimetype == 'application/zip' - assert expected_name in res.headers.get('Content-Disposition', '') + # Werkzeug ASCII filename 会剥掉中文;真实下载名在 filename*=UTF-8'' 段。 + disposition = res.headers.get('Content-Disposition', '') + assert quote(expected_name) in disposition with zipfile.ZipFile(BytesIO(res.data)) as archive: names = archive.namelist() assert 'manifest.json' in names - assert any(name.endswith('.xlsx') for name in names) + assert '001_DSV360_AWSBI_BYAWSCMH01.xlsx' in names + + +def test_build_zip_entry_name_prefers_source_code(): + """包内条目优先 source_code;无 source 时才回退仓码。""" + assert _build_zip_entry_name( + index=2, + source_code="DSV360_AWSBI_BYAWSCMH01", + warehouse_id="BYAWSCMH01", + original_suffix=".xlsx", + ) == "002_DSV360_AWSBI_BYAWSCMH01.xlsx" + assert _build_zip_entry_name( + index=1, + source_code="CRANE_FOOTPRINT", + warehouse_id="unknown", + original_suffix=".xlsx", + ) == "001_CRANE_FOOTPRINT.xlsx" + assert _build_zip_entry_name( + index=3, + source_code="", + warehouse_id="AWSSG", + original_suffix=".xlsx", + ) == "003_AWSSG.xlsx" + + +def test_inventory_rpa_attachment_stem_converts_utc_to_schedule_timezone(app): + """展示名 HHmm 必须用业务时区,不能直接用库内 UTC naive / run_no 内嵌时刻。""" + with app.app_context(): + run = _make_inventory_run_with_created( + schedule_no="ARCH-TZ-STEM", + username="arch_tz_stem", + created=[], + ) + # UTC 06:27 → Asia/Shanghai 14:27 + run.started_at = datetime(2026, 9, 9, 6, 27, 17) + run.task.schedule_timezone = "Asia/Shanghai" + db.session.commit() + assert inventory_rpa_attachment_stem(run) == "库存RPA-20260909-1427" + assert inventory_rpa_result_excel_name(run) == "库存RPA-20260909-1427-结果.xlsx" + assert inventory_raw_zip_download_name(run) == "库存RPA-20260909-1427-库存.zip" def test_get_inventory_raw_zip_returns_404_when_archive_unavailable( diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index f4d64b3a..45ab8b79 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -2409,7 +2409,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), ) - def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None): + def _fake_link(actual_task, inv_file, *, reason, audit_payload=None): call_order.append(f'link:{reason}') assert actual_task is task assert inv_file is snapshot @@ -2424,7 +2424,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, return {'status': 'ok', 'message': 'linked-and-loaded'} monkeypatch.setattr( - 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation', _fake_link, ) monkeypatch.setattr( @@ -2495,7 +2495,7 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app): SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), ) monkeypatch.setattr( - 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation', lambda *_a, **_k: None, ) @@ -2516,3 +2516,85 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app): assert result['status'] == 'needs_human' assert result['data']['blocking_reason']['code'] == 'inventory_file_missing' + + +def test_stp_candidate_ready_uses_preparation_link_when_warehouse_pending(monkeypatch, app): + """[断言] 动态仓未决时 preparation 软绑定仍推进,不得投影 inventory_file_missing。""" + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='OT-STP-SOFT-LINK', + id=703, + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=11, + ) + snapshot = SimpleNamespace(inventory_file_no='INV-WH-PENDING', source_code='CRANE', warehouse_id=None) + 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, 'flush', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['CRANE'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'candidate_set_id': 11, + 'lines': [{'part_number': 'P1', '__source_code': 'CRANE', '__inventory_file_no': 'INV-WH-PENDING'}], + 'missing_source_codes': [], + 'loaded_source_codes': ['CRANE'], + 'evidence': [{ + 'source_code': 'CRANE', + 'status': 'loaded', + 'inventory_file_no': 'INV-WH-PENDING', + 'line_count': 1, + 'required': True, + }], + 'required_source_codes': ['CRANE'], + }, + ) + 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_prep_link(actual_task, inv_file, *, reason, audit_payload=None): + call_order.append(f'prep:{reason}') + assert reason == 'stp_candidate_prep' + assert inv_file is snapshot + return SimpleNamespace(id=99, identity_check_status='pending_matching') + + def _fake_loaded(actual_task, lines, **kwargs): + call_order.append('loaded') + assert kwargs.get('persist_lines') is False + return {'status': 'ok', 'message': 'soft-linked'} + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation', + _fake_prep_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 == ['prep:stp_candidate_prep', 'loaded'] diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index a3ba82cb..f7bc015d 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -8,6 +8,8 @@ from app.services.shipping_notice.reservation_region import ( apply_reservation_region_candidates, extract_reservation_from_region_text, extract_reservation_from_vendor_comments_pages, + project_reservation_onto_validation_evidence, + reservation_region_candidates_from_layout, ) @@ -82,6 +84,18 @@ def test_reservation_region_maps_line_when_reservation_label_and_line_number_are }] +def test_reservation_region_maps_hyve_l_hash_abbreviation_to_line(): + """关键断言:Hyve ``Reservation L#1: 1000153133`` 必须归明细行,不得写入单头。""" + assert extract_reservation_from_region_text("Reservation L#1: 1000153133") == [{ + 'value': '1000153133', 'line_no': 1, 'scope': 'line', + 'raw_text': 'Reservation L#1: 1000153133', 'status': 'mapped', + }] + assert extract_reservation_from_region_text("Reservation LN#2: 1000153134") == [{ + 'value': '1000153134', 'line_no': 2, 'scope': 'line', + 'raw_text': 'Reservation LN#2: 1000153134', 'status': 'mapped', + }] + + def test_reservation_region_assigns_reservation_without_line_to_header(): """无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。""" assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{ @@ -106,8 +120,23 @@ def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading() assert [item['value'] for item in candidates] == ['33008', '3000098851'] +def test_terms_heading_matches_when_phrase_is_only_part_of_title(): + """结束锚点只需标题含 Terms and Conditions,不要求整行仅有该短语。""" + candidates, reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines( + 'Vendor Comments', + 'DBS Reservation Line 1: 1000143920', + '7. Terms and Conditions of Sale', + 'Reservation#99999', + )), + ]) + + assert reason is None + assert [item['value'] for item in candidates] == ['1000143920'] + + def test_vendor_comments_window_requires_start_and_end_headings(): - """缺少任一边界时不能把全文中的 Reservation 当作专区证据。""" + """缺少起始锚点时不得扫描全文;缺少结束锚点时仍返回窗内候选但必须带复核原因。""" candidates, reason = extract_reservation_from_vendor_comments_pages([ (1, _glyph_lines('Reservation#33008')), ]) @@ -115,6 +144,18 @@ def test_vendor_comments_window_requires_start_and_end_headings(): assert candidates == [] assert reason == 'vendor_comments_anchor_missing' + open_candidates, open_reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines( + 'Vendor Comments:', + 'DBS Reservation Line 1: 1000143920', + 'End Customer: D1', + )), + ]) + assert open_reason == 'terms_and_conditions_anchor_missing' + assert [item['value'] for item in open_candidates] == ['1000143920'] + assert open_candidates[0]['scope'] == 'line' + assert open_candidates[0]['line_no'] == 1 + def test_reservation_region_applies_header_and_line_override_together(): """整单值是默认值,指定行的 Reservation 仅覆盖对应明细。""" @@ -165,3 +206,71 @@ def test_reservation_gate_blocks_empty_and_malformed_order_lines(): assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines" assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line" + + +def test_reservation_region_candidates_from_layout_requires_configured_region(): + """未标注专区时不得扫描 Vendor Comments;标注后必须走锚点窗而非 page_no/region。""" + layout = { + 'coordinate_evidence': { + 'pages': {'1': {'width': 800, 'height': 600}}, + 'page_glyphs': { + '1': _glyph_lines( + 'Vendor Comments:', + 'DBS Reservation Line 1: 1000143920', + 'Terms and Conditions:', + ), + }, + }, + } + assert reservation_region_candidates_from_layout(definition={}, layout=layout) == { + 'candidates': [], 'reason': None, + } + result = reservation_region_candidates_from_layout( + definition={'reservation_id_region': {'page_no': 9, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}}}, + layout=layout, + ) + assert result['reason'] is None + assert [item['value'] for item in result['candidates']] == ['1000143920'] + assert result['candidates'][0]['scope'] == 'line' + assert result['candidates'][0]['line_no'] == 1 + + +def test_project_reservation_onto_validation_evidence_writes_line_and_review_reason(): + """验证证据必须落入与正式解析相同的 header/line 字段,并保留锚点缺失原因。""" + evidence = { + 'header_fields': [{ + 'field_id': 'f-po', 'field_code': 'customer_po_number', 'raw_value': 'PO-1', + 'normalized_value': 'PO-1', 'status': 'passed', 'issues': [], + }], + 'lines': [{'row_index': 0, 'fields': [{ + 'field_id': 'f-part', 'field_code': 'part_number', 'raw_value': 'P-1', + 'normalized_value': 'P-1', 'status': 'passed', 'issues': [], + }]}], + 'cross_checks': {}, + } + projected = project_reservation_onto_validation_evidence( + evidence, + candidates=[{ + 'value': '1000143920', 'line_no': 1, 'scope': 'line', + 'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped', + }], + reason=None, + schema_fields={ + 'header-reservation': { + 'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header', + }, + 'line-reservation': { + 'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', + }, + }, + ) + assert projected['lines'][0]['fields'][-1] == { + 'field_id': 'line-reservation', 'field_code': 'reservation_id', + 'raw_value': '1000143920', 'normalized_value': '1000143920', + 'status': 'passed', 'issues': [], + } + missing = project_reservation_onto_validation_evidence( + evidence, candidates=[], reason='vendor_comments_anchor_missing', schema_fields={}, + ) + assert missing['reservation_region_status'] == 'needs_review' + assert missing['reservation_region_review_reasons'] == ['vendor_comments_anchor_missing'] diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index 5475517b..ed8872c7 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -676,7 +676,7 @@ def test_create_run_scopes_to_selected_intakes_only(app): @pytest.mark.parametrize('layout_status', ['queued', 'running']) def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction(app, layout_status): - """发送后必须先完成版面解析;订单 Job 不得与布局 Job 并行抢跑。""" + """发送后若 PDF 版式仍在进行,Run 进入 waiting_layout;不得对未 ready 的 PDF 抽取。""" with app.app_context(): app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}') @@ -750,14 +750,14 @@ def test_create_run_accepts_a_reused_layout_from_an_identical_document(app): assert run.status == 'queued' -def test_last_layout_completion_enqueues_waiting_run_once(app): - """最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。""" +def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app): + """任一份附件布局完成即可唤醒 Run;无需等齐全部版式。""" with app.app_context(): app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True - user, agent, session, intake, first = _seed_run_input(suffix='WAIT-ALL') + user, agent, session, intake, first = _seed_run_input(suffix='WAIT-PARTIAL') second = ShippingOrderDocument( intake_id=intake.id, asset_id=first.asset_id, document_type='attachment', - attachment_key='orders-WAIT-ALL-2.pdf', filename='orders-WAIT-ALL-2.pdf', + attachment_key='orders-WAIT-PARTIAL-2.pdf', filename='orders-WAIT-PARTIAL-2.pdf', content_hash='b' * 64, classification='order_notice', parse_status='parsed', extracted_text='PO 2', ) db.session.add(second) @@ -770,12 +770,31 @@ def test_last_layout_completion_enqueues_waiting_run_once(app): ShippingDocumentLayoutVersion.document_id.in_([first.id, second.id]), ).all() assert len(layouts) == 2 + ready_payload = { + 'status': 'ready', + 'layout_candidate': {}, + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'page_glyphs': {'1': []}, + }, + } layouts[0].status = 'ready' + layouts[0].payload_json = dict(ready_payload) + first.current_layout_version_id = layouts[0].id db.session.commit() - assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 0 - assert db.session.get(Job, run.current_job_id) is not None + # 关键断言:第一份 ready 即可 resume(活跃 Job 去重仍只保留一条 extraction)。 + assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1 + db.session.refresh(run) + first_job_id = run.current_job_id + first_job = db.session.get(Job, first_job_id) + assert first_job is not None + # 关键断言:抬高 priority,避免被同队列剩余 layout FIFO 堵住。 + assert int(first_job.priority or 0) >= 10 + assert run.phase == 'waiting_layout' layouts[1].status = 'ready' + layouts[1].payload_json = dict(ready_payload) + second.current_layout_version_id = layouts[1].id db.session.commit() assert resume_runs_waiting_for_layout(document_id=layouts[1].document_id) == 1 db.session.refresh(run) @@ -783,6 +802,7 @@ def test_last_layout_completion_enqueues_waiting_run_once(app): assert run.phase == 'queued' assert job is not None assert job.job_type == 'shipping_order_extraction' + assert int(job.priority or 0) >= 10 def test_pdf_without_ready_coordinate_layout_is_a_prerequisite_failure(app): diff --git a/backend/tests/test_shipping_order_extraction_worker.py b/backend/tests/test_shipping_order_extraction_worker.py index 8fdbabde..91f7f85c 100644 --- a/backend/tests/test_shipping_order_extraction_worker.py +++ b/backend/tests/test_shipping_order_extraction_worker.py @@ -67,6 +67,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch): monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', fake_materialize) monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda _run, *, created_by_id: events.append('schedule') or False) monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {}) + monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {1}) monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or []) monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None) monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: []) @@ -113,6 +114,7 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch) lambda _run, *, created_by_id: events.append('schedule') or True, ) monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'}) + monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set()) monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting')) def fake_finish_job(*_args, **kwargs): events.append('finished') @@ -134,6 +136,116 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch) assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务' +def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(monkeypatch): + """部分 PDF 版式就绪时只抽 ready Unit,Job 以 partial_units_done 收口且不终态 Run。""" + import app.jobs.handlers.shipping_order_extraction as handler + + events: list[str] = [] + finished: dict = {} + run = SimpleNamespace( + id=4, user_id=9, run_no='SNER-WORKER-PARTIAL', status='queued', phase='queued', + current_job_id=None, attempt_count=0, cancellation_requested_at=None, + input_snapshot_json={'attachment_selection': {}, 'intakes': []}, + execution_result_json=None, extraction_completed_at=None, + ) + job = SimpleNamespace(id=4, attempts=1, business_ref=run.run_no, max_attempts=3) + ready_unit = SimpleNamespace( + id=41, document_id=101, intake_id=1, status='pending', result_json=None, position=1, + cancellation_requested_at=None, + ) + pending_unit = SimpleNamespace( + id=42, document_id=102, intake_id=1, status='pending', result_json=None, position=2, + cancellation_requested_at=None, + ) + plan = SimpleNamespace(id=4, unit_count=2, units=[ready_unit, pending_unit]) + + monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit) + monkeypatch.setattr( + handler, 'ShippingOrderProcessingRun', + SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace( + with_for_update=lambda: SimpleNamespace(first=lambda: run), + ))), + ) + monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace( + position=SimpleNamespace(asc=lambda: None), + status=SimpleNamespace(in_=lambda *_a, **_k: True), + query=SimpleNamespace( + filter_by=lambda **_kwargs: SimpleNamespace( + order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, pending_unit]), + ), + ), + )) + monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace())) + monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: events.append('freeze_begin')) + monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: events.append('freeze_complete')) + monkeypatch.setattr( + handler, 'materialize_order_extraction_run_inputs', + lambda _run, *, finalize_plan=True: events.append('finalize' if finalize_plan else 'materialize') or (plan if finalize_plan else None), + ) + monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: []) + monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: events.append('schedule') or False) + monkeypatch.setattr( + handler, 'order_extraction_layout_prerequisite_issues', + lambda _run: {102: 'layout_pending'}, + ) + monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101}) + monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True) + monkeypatch.setattr( + handler, 'transition_order_extraction_run', + lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)), + ) + monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None) + monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None) + monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, pending_unit]) + monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None) + monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: []) + monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {}) + + def _fake_transition(unit, *, target_status, **_kwargs): + unit.status = target_status + events.append(f'transition:{target_status}') + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit', + _fake_transition, + ) + + def _process(**_kwargs): + events.append('processed') + ready_unit.status = 'merging_supplement' + return [{'po_number': 'PO-1', '_hxops_intake_id': 1}] + + monkeypatch.setattr(handler, '_process_unit_with_retries', _process) + monkeypatch.setattr( + handler, 'merge_unit_orders', + lambda *, orders, schema_definition, keep_primary_documents_separate: orders, + ) + monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {}) + monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {}) + monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started')) + + def fake_finish(*_args, **kwargs): + events.append('finished') + finished.update(kwargs) + + monkeypatch.setattr(handler, 'finish_job', fake_finish) + monkeypatch.setattr(handler.db.session, 'commit', lambda: None) + monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None) + monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None) + monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'}) + + handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 4}) + + assert 'processed' in events + assert 'progressed' in events + assert 'terminalized' not in events + assert 'persist_started' not in events + assert run.phase == 'waiting_layout' + assert run.status == 'processing' + assert finished['result']['handoff_status'] == 'partial_units_done' + assert finished['result']['waiting_layout'] is True + + def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch): """版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。""" import app.jobs.handlers.shipping_order_extraction as handler diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index e01c9d20..20c1acbc 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -690,6 +690,124 @@ def test_profile_matcher_selects_signature_main_table_when_metadata_table_preced assert result.candidates[0].dimension_scores.column_topology >= 0.75 +def _header_glyphs_at(*, text: str, y0: float, y1: float, x0: float = 10.0, step: float = 4.0) -> list[dict]: + """在指定纵坐标生成带空格边界的表头字符证据。""" + return [ + { + 'text': char, + 'bbox': {'x0': x0 + index * step, 'y0': y0, 'x1': x0 + index * step + 3, 'y1': y1}, + 'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none', + } + for index, char in enumerate(text) + if char != ' ' + ] + + +def _foxconn_dual_table_layout() -> dict: + """模拟 4210012210:右上角 ORDER DATE KV 小表 + 下方明细表,全页均有 glyphs。""" + layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO QTY') + meta_header = 'ORDER DATE ORDER NO BU CODE CURRENCY' + main_header = 'ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE' + meta_glyphs = _header_glyphs_at(text=meta_header, y0=70, y1=82, x0=120.0) + main_glyphs = _header_glyphs_at(text=main_header, y0=150, y1=162, x0=10.0) + layout['tables'] = [ + { + 'table_id': 'order-meta', + 'page_no': 1, + # 绝对点坐标:与 pages width/height=200/280 一致,贴近真实 MinerU 右上角 KV 表。 + 'bbox': {'x0': 120.0, 'y0': 55.0, 'x1': 195.0, 'y1': 100.0}, + }, + { + 'table_id': 'line-items', + 'page_no': 1, + 'bbox': {'x0': 10.0, 'y0': 140.0, 'x1': 190.0, 'y1': 250.0}, + }, + ] + layout['coordinate_evidence']['tables'] = { + 'order-meta': meta_glyphs, + 'line-items': main_glyphs, + } + # 锚点 glyphs + 两表表头均写入页级证据,再现「全页 glyphs 非空」场景。 + layout['coordinate_evidence']['page_glyphs']['1'] = [ + *layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')], + *meta_glyphs, + *main_glyphs, + ] + return layout + + +def test_profile_matcher_prefers_line_table_when_order_meta_table_precedes_it(): + """全页 glyphs 下须按签名表头亲和度选明细表,不能被前置 ORDER DATE KV 小表抢走。""" + layout = _foxconn_dual_table_layout() + profile = _profile('FOX_MX') + profile['definition']['document_match']['required_anchors'] = [] + main_region = {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.90} + profile['definition']['table_regions'][0]['region'] = main_region + profile['definition']['table_regions'][0]['line_layouts'][0]['region'] = main_region + # 签名只在明细表布局上冻结,模拟已发布 FOX MX。 + sign_layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE') + sign_layout['tables'] = [layout['tables'][1]] + sign_layout['coordinate_evidence']['tables'] = {'line-items': layout['coordinate_evidence']['tables']['line-items']} + sign_layout['coordinate_evidence']['page_glyphs']['1'] = [ + *sign_layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')], + *layout['coordinate_evidence']['tables']['line-items'], + ] + profile = _with_signature(profile, sign_layout) + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + + # 关键断言:双表全页 glyphs 仍唯一命中明细模板,不得因 KV 小表落到 evidence_insufficient。 + assert result.status == 'unique_match' + assert result.profile_code == 'FOX_MX' + assert result.candidates[0].hard_match is True + assert 'profile_header_discriminator_conflict' not in result.candidates[0].reason_codes + assert 'profile_coordinate_evidence_unavailable' not in result.candidates[0].reason_codes + + +def test_profile_matcher_does_not_escalate_unrelated_coordinate_unavailable(monkeypatch): + """近亲 header 冲突时,远亲候选的坐标不可用不得把整单抬成 evidence_insufficient。""" + from app.services.shipping_notice.document_layout import order_profile_matcher as matcher + + line_layout = _layout( + 'PLANT NAME: FACTORY A', + header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY', + ) + near = _profile_without_required_anchors('NEAR_TWIN', _layout( + header_text='PART NUMBER AMOUNT CURRENCY INVOICE CODE', + )) + far = _profile_without_required_anchors('FAR_EMPTY', _layout( + header_text='VENDOR INVOICE TOTAL AMOUNT', + )) + + real_observe = matcher._observe_layout_features + + def fake_observe(*, signature, **kwargs): + """远亲强制空表头观测,稳定触发 profile_coordinate_evidence_unavailable。""" + observed = real_observe(signature=signature, **kwargs) + tokens = matcher._signature_identity_header_tokens(signature) + atoms = matcher._header_token_atoms([str(item) for item in tokens]) + if 'vendor' in atoms: + return { + **observed, + 'header_tokens': [], + 'column_centers': [], + 'column_width_ratios': [], + 'column_count': 0, + } + return observed + + monkeypatch.setattr(matcher, '_observe_layout_features', fake_observe) + + result = match_frozen_coordinate_profiles(profiles=[near, far], layout=line_layout) + + # 关键断言:不得因远亲坐标码把整单抬成 evidence_insufficient。 + assert result.status != 'evidence_insufficient' + near_cand = next(item for item in result.candidates if item.profile_code == 'NEAR_TWIN') + far_cand = next(item for item in result.candidates if item.profile_code == 'FAR_EMPTY') + assert 'profile_header_discriminator_conflict' in near_cand.reason_codes + assert 'profile_coordinate_evidence_unavailable' in far_cand.reason_codes + + def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness(): """硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。""" layout = _layout('PLANT NAME: FACTORY A') @@ -812,6 +930,207 @@ def _profile_without_required_anchors(code: str, layout: dict) -> dict: return profile +def test_header_token_atoms_ignore_parenthetical_gloss(): + """括号印刷注记经统一归一化后不得改变表头原子(不依赖 vat 特判停用词)。""" + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _header_discriminator_atoms_conflict, + _header_token_atoms, + ) + + expected = [ + 'Item', 'Parts No.& Description', 'REV.', 'UNIT', "Q'TY", + 'Delivery Date', 'Unit', 'Total', 'Price', + ] + observed = [ + 'item 项次', 'parts no.& description 料号', 'rev.', 'unit', "q'ty", + 'delivery date', 'unit', 'price (vat excluded)', 'total', 'price', + ] + assert _header_token_atoms(expected) == _header_token_atoms(observed) + assert 'vat' not in _header_token_atoms(observed) + assert _header_discriminator_atoms_conflict( + signature={'table_patterns': [{'header_tokens': expected}]}, + observed={'header_tokens': observed}, + ) is False + # 近亲多出的 ECCN 仍须硬杀。 + assert _header_discriminator_atoms_conflict( + signature={'table_patterns': [{'header_tokens': expected + ['ECCN']}]}, + observed={'header_tokens': observed}, + ) is True + + +def _profile_with_header_band( + code: str, + layout: dict, + *, + header_region: dict, + required_anchors: bool = True, +) -> dict: + """构造带 header_layouts 的 Profile,使签名冻结合法 header_bbox。""" + profile = _profile(code) + if not required_anchors: + profile['definition']['document_match']['required_anchors'] = [] + bbox = layout['tables'][0]['bbox'] + table = profile['definition']['table_regions'][0] + table['region'] = { + 'x0': float(bbox['x0']), 'y0': float(bbox['y0']), + 'x1': float(bbox['x1']), 'y1': float(bbox['y1']), + } + table['header_layouts'] = [{ + 'layout_id': 'hdr', + 'region': header_region, + 'field_regions': [_field_region(region=header_region)], + }] + # 明细行区必须与表头带不重叠,否则 OrderCoordinateProfile 校验失败。 + line_region = { + 'x0': float(bbox['x0']), + 'y0': float(header_region['y1']), + 'x1': float(bbox['x1']), + 'y1': float(bbox['y1']), + } + table['line_layouts'][0]['region'] = line_region + table['line_layouts'][0]['field_regions'] = [_field_region(region=line_region)] + return _with_signature(profile, layout) + + +def test_observe_header_ignores_vat_row_outside_aligned_header_band(): + """身份观测不得用表顶宽带读入签名表头框外的 Unit Price (VAT Excluded) 行。""" + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _extract_matching_signature, + _header_token_atoms, + _observe_layout_features, + ) + + header_text = 'ITEM NO QTY' + layout = _layout(header_text=header_text, bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}) + # 表顶 18% 内、但低于紧表头带:放入 VAT 注记行。 + vat_text = 'Unit Price (VAT Excluded)' + vat_glyphs = [ + { + 'text': char, + 'bbox': {'x0': 10 + index * 5, 'y0': 100, 'x1': 14 + index * 5, 'y1': 112}, + 'boundary_before': 'space' if index and vat_text[index - 1] == ' ' else 'none', + } + for index, char in enumerate(vat_text) + if char != ' ' + ] + layout['coordinate_evidence']['page_glyphs']['1'].extend(vat_glyphs) + header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32} + profile = _profile_with_header_band('PO_BAND', layout, header_region=header_region) + signature_body, _ = _extract_matching_signature(profile) + evidence = layout['coordinate_evidence'] + observed = _observe_layout_features( + layout=layout, + tables=layout['tables'], + pages=evidence['pages'], + glyph_tables=evidence['tables'], + page_glyphs=evidence['page_glyphs'], + signature=signature_body, + ) + atoms = _header_token_atoms([str(item) for item in (observed.get('header_tokens') or [])]) + # 关键断言:框外 VAT 行不得进入身份原子。 + assert 'vat' not in atoms + assert 'excluded' not in atoms + assert 'item' in atoms or 'qty' in atoms + + +def test_aligned_header_band_unique_match_after_table_delta_y(): + """主表相对签名整体下移时,表头框 deltaY 对齐后仍应 unique_match。""" + baseline = _layout( + header_text='ITEM NO MATERIAL QTY', + bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}, + ) + header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32} + profile = _profile_with_header_band( + 'PO_SHIFT', baseline, header_region=header_region, required_anchors=False, + ) + + shifted = _layout( + header_text='ITEM NO MATERIAL QTY', + bbox={'x0': 0.05, 'y0': 0.40, 'x1': 0.95, 'y1': 0.95}, + ) + # 默认表头 glyphs 按 y≈0.27 生成;整体下移与主表顶边一致。 + # table-1 与 page_glyphs 共享同一 glyph 对象,只平移一次。 + delta = (0.40 - 0.25) * 280 + for glyph in shifted['coordinate_evidence']['page_glyphs']['1']: + if glyph['bbox']['y0'] >= 50: + glyph['bbox']['y0'] += delta + glyph['bbox']['y1'] += delta + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=shifted) + assert result.status == 'unique_match' + assert result.profile_code == 'PO_SHIFT' + + +def test_in_band_parenthetical_vat_aligns_without_stopwords(): + """框内印刷括号注记时仅靠括号归一化与无括号签名对齐(无 vat 停用词)。""" + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _extract_matching_signature, + _header_discriminator_atoms_conflict, + _header_token_atoms, + _observe_layout_features, + _signature_identity_header_tokens, + ) + + clean = _layout( + header_text='ITEM Unit Price Total', + bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}, + ) + header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.34} + profile = _profile_with_header_band( + 'PO_PAREN', clean, header_region=header_region, required_anchors=False, + ) + # 紧凑字形间距,避免长括号注记超出表头带 x 范围被截断。 + with_gloss = _layout( + header_text='ITEM Unit Price (VAT Excluded) Total', + bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}, + ) + gloss_text = 'ITEM Unit Price (VAT Excluded) Total' + header_glyphs = [ + { + 'text': char, + 'bbox': {'x0': 10 + index * 5, 'y0': 76, 'x1': 13 + index * 5, 'y1': 88}, + 'boundary_before': 'space' if index and gloss_text[index - 1] == ' ' else 'none', + } + for index, char in enumerate(gloss_text) + if char != ' ' + ] + with_gloss['coordinate_evidence']['tables']['table-1'] = header_glyphs + anchor_glyphs = [ + glyph for glyph in clean['coordinate_evidence']['page_glyphs']['1'] + if float(glyph['bbox']['y0']) < 50 + ] + with_gloss['coordinate_evidence']['page_glyphs']['1'] = [*anchor_glyphs, *header_glyphs] + + signature_body, _ = _extract_matching_signature(profile) + evidence = with_gloss['coordinate_evidence'] + observed = _observe_layout_features( + layout=with_gloss, + tables=with_gloss['tables'], + pages=evidence['pages'], + glyph_tables=evidence['tables'], + page_glyphs=evidence['page_glyphs'], + signature=signature_body, + ) + expected_tokens = _signature_identity_header_tokens(signature_body) + observed_tokens = [str(item) for item in (observed.get('header_tokens') or [])] + assert _header_token_atoms(expected_tokens) == _header_token_atoms(observed_tokens) + assert 'vat' not in _header_token_atoms(observed_tokens) + assert _header_discriminator_atoms_conflict( + signature=signature_body, observed=observed, + ) is False + + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _score_header_semantic_position, + ) + header_score = _score_header_semantic_position( + signature=signature_body, + observed=observed, + required_hits=[], + enforce_atom_discriminator=True, + ) + assert header_score.state == 'matched' + + 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' @@ -836,6 +1155,89 @@ def test_near_twin_header_discriminator_makes_unique_match(): assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes +def test_single_logical_header_wrap_pollution_sanitized_for_identity(): + """单逻辑表头旧签名含折行副标签时,须并入所属列后再比身份(文案保留)。""" + from app.services.shipping_notice.document_layout.coordinate_region_text import ( + merge_header_identity_wrap_tokens, + ) + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _header_discriminator_atoms_conflict, + _signature_identity_header_tokens, + ) + + # Hyve 旧签名:主行 + 折行副标签 Vendor Item# / Date(centers 回退)。 + signature = { + 'table_patterns': [{ + 'header_row_count': 1, + 'header_tokens': [ + 'LN', 'Quantity', 'Part', 'Number', 'Description', + 'Requested Arrival', 'Unit', 'Price', 'Extension', 'Vendor Item#', 'Date', + ], + 'column_centers': [ + 0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801, + 0.2418, 0.5217, + ], + }], + } + identity = _signature_identity_header_tokens(signature) + joined = ' '.join(identity) + # 关键断言:副标签文案仍在;不再作为独立尾列。 + assert 'Vendor Item#' in joined + assert 'Date' in joined + assert identity[-1] != 'Date' + assert identity[-1] != 'Vendor Item#' + assert len(identity) == 9 + + observed_tokens, observed_centers, _ = merge_header_identity_wrap_tokens( + [ + 'ln', 'quantity', 'part', 'number', 'description', + 'requested arrival', 'unit', 'price', 'extension', 'vendor item#', 'date', + ], + [ + 0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801, + 0.2418, 0.5217, + ], + ) + assert _header_discriminator_atoms_conflict( + signature=signature, + observed={'header_tokens': observed_tokens}, + ) is False + + # 近亲缺 ECCN 仍须硬杀。 + twin_signature = { + 'table_patterns': [{ + 'header_row_count': 1, + 'header_tokens': [ + 'Item', 'Parts', 'No', 'ECCN', 'Description', 'REV', 'UNIT', 'QTY', + ], + 'column_centers': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8], + }], + } + twin_observed = { + 'header_tokens': ['Item', 'Parts', 'No', 'Description', 'REV', 'UNIT', 'QTY'], + } + assert _header_discriminator_atoms_conflict(signature=twin_signature, observed=twin_observed) is True + + +def test_multi_row_header_signature_keeps_secondary_row_identity(): + """真多行表头(header_row_count>1)不得做折行合并。""" + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _signature_identity_header_tokens, + ) + + signature = { + 'table_patterns': [{ + 'header_row_count': 3, + 'header_tokens': ['Item', 'Qty', 'Price', 'Amount', 'PR_Number'], + # 故意造 x 回退:多行正式表头不得合并掉 PR_Number。 + 'column_centers': [0.1, 0.3, 0.5, 0.7, 0.2], + }], + } + assert _signature_identity_header_tokens(signature) == [ + 'Item', 'Qty', 'Price', 'Amount', 'PR_Number', + ] + + def test_required_anchors_skip_header_atom_hard_mutex(): """已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。""" mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price' diff --git a/backend/tests/test_shipping_order_profile_matcher_replay.py b/backend/tests/test_shipping_order_profile_matcher_replay.py new file mode 100644 index 00000000..d8299be9 --- /dev/null +++ b/backend/tests/test_shipping_order_profile_matcher_replay.py @@ -0,0 +1,251 @@ +""" +tests/test_shipping_order_profile_matcher_replay.py + +用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。 +依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。 +逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。 +""" + +from __future__ import annotations + +import json +import os +from collections import defaultdict +from typing import Any + +import pytest +from sqlalchemy import create_engine, text +from sqlalchemy.engine import Engine + +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + match_frozen_coordinate_profiles, +) + +_REPLAY_DB_URL = os.environ.get( + 'HXOPS_PROFILE_REPLAY_DATABASE_URL', + os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'), +) +_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20')) +_EXTRA_DOC_IDS = { + int(item.strip()) + for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',') + if item.strip().isdigit() +} + + +def _can_connect(url: str) -> bool: + """探测回放库是否可连;连不上则整条集成测试 skip。""" + try: + engine = create_engine(url) + with engine.connect() as conn: + conn.execute(text('SELECT 1')) + return True + except Exception: + return False + + +@pytest.fixture(scope='module') +def replay_engine() -> Engine: + """模块级只读引擎;本地无 hxops_db 时跳过。""" + if not _can_connect(_REPLAY_DB_URL): + pytest.skip(f'Replay database unavailable: {_REPLAY_DB_URL}') + return create_engine(_REPLAY_DB_URL) + + +def _document_from_snapshot( + snapshot: dict[str, Any], + *, + document_id: int, + intake_id: int, +) -> dict[str, Any] | None: + """在冻结 intake 列表中定位 document 及其 layout_snapshot。""" + for intake in snapshot.get('intakes') or []: + if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(intake_id): + continue + for document in intake.get('documents') or []: + if not isinstance(document, dict): + continue + if int(document.get('document_id') or 0) == int(document_id): + return document + return None + + +def _layout_ready(layout: dict[str, Any] | None) -> bool: + """layout 须 ready 且具备 matcher 所需坐标证据。""" + if not isinstance(layout, dict) or layout.get('status') != 'ready': + return False + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] + return bool(pages and (page_glyphs or glyph_tables or tables)) + + +def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> list[dict[str, Any]]: + """与 Worker 一致:仅取与 Run schema_version_id 对齐的冻结模板。""" + profiles = snapshot.get('order_document_profiles') + if not isinstance(profiles, list): + profiles = snapshot.get('profiles') if isinstance(snapshot.get('profiles'), list) else [] + return [ + item for item in profiles + if isinstance(item, dict) + and int(item.get('schema_version_id') or 0) == int(schema_version_id) + ] + + +def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]: + """ + 拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。 + + Returns: + 含 route/run/unit/document/profile 期望字段的字典列表。 + """ + query = text(""" + SELECT + r.id AS route_id, + r.run_id, + r.unit_id, + r.selected_profile_code, + r.selected_profile_version, + r.selected_profile_checksum, + run.input_snapshot_json, + run.schema_version_id, + u.document_id, + u.intake_id + FROM shipping_order_route_decisions r + JOIN shipping_order_processing_runs run ON run.id = r.run_id + JOIN shipping_order_processing_units u ON u.id = r.unit_id + WHERE r.match_status = 'unique_match' + AND r.selected_profile_code IS NOT NULL + AND run.input_snapshot_json IS NOT NULL + ORDER BY r.selected_profile_code ASC, r.id DESC + """) + rows: list[dict[str, Any]] = [] + per_profile: dict[str, int] = defaultdict(int) + with engine.connect() as conn: + for row in conn.execute(query).mappings(): + code = str(row['selected_profile_code'] or '') + if per_profile[code] >= _MAX_PER_PROFILE: + continue + snapshot = row['input_snapshot_json'] + if isinstance(snapshot, str): + snapshot = json.loads(snapshot) + if not isinstance(snapshot, dict): + continue + document = _document_from_snapshot( + snapshot, + document_id=int(row['document_id'] or 0), + intake_id=int(row['intake_id'] or 0), + ) + layout = document.get('layout_snapshot') if isinstance(document, dict) else None + if not _layout_ready(layout if isinstance(layout, dict) else None): + continue + profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0)) + if not profiles: + continue + per_profile[code] += 1 + rows.append({ + 'route_id': int(row['route_id']), + 'run_id': int(row['run_id']), + 'unit_id': int(row['unit_id']), + 'document_id': int(row['document_id']), + 'expected_profile_code': code, + 'expected_profile_version': int(row['selected_profile_version'] or 0), + 'expected_profile_checksum': str(row['selected_profile_checksum'] or ''), + 'profiles': profiles, + 'layout': layout, + }) + return rows + + +def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None: + """历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。""" + samples = _load_replay_samples(replay_engine) + if not samples: + pytest.skip('No replayable unique_match snapshots in database') + + failures: list[str] = [] + summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0}) + + for sample in samples: + code = sample['expected_profile_code'] + result = match_frozen_coordinate_profiles( + profiles=sample['profiles'], + layout=sample['layout'], + ) + ok = ( + result.status == 'unique_match' + and result.profile_code == sample['expected_profile_code'] + and ( + not sample['expected_profile_version'] + or int(result.version or 0) == int(sample['expected_profile_version']) + ) + ) + if ok: + summary[code]['pass'] += 1 + else: + summary[code]['fail'] += 1 + failures.append( + f"{code} route={sample['route_id']} run={sample['run_id']} " + f"doc={sample['document_id']}: expected {sample['expected_profile_code']}" + f"/v{sample['expected_profile_version']}, got {result.status}" + f"/{result.profile_code}/v{result.version}" + ) + + if failures: + lines = [ + 'Published unique_match replay failures:', + *[f' - {item}' for item in failures[:50]], + 'Per-profile summary:', + ] + for profile_code, counts in sorted(summary.items()): + lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}') + pytest.fail('\n'.join(lines)) + + +@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS)) +def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None: + """ + 对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。 + + 历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。 + """ + query = text(""" + SELECT + run.id AS run_id, + run.input_snapshot_json, + run.schema_version_id, + u.document_id, + u.intake_id + FROM shipping_order_processing_units u + JOIN shipping_order_processing_plans p ON p.id = u.plan_id + JOIN shipping_order_processing_runs run ON run.id = p.run_id + WHERE u.document_id = :document_id + ORDER BY run.id DESC + LIMIT 1 + """) + with replay_engine.connect() as conn: + row = conn.execute(query, {'document_id': document_id}).mappings().first() + if row is None: + pytest.skip(f'No processing run for document_id={document_id}') + + snapshot = row['input_snapshot_json'] + if isinstance(snapshot, str): + snapshot = json.loads(snapshot) + document = _document_from_snapshot( + snapshot, + document_id=int(row['document_id']), + intake_id=int(row['intake_id']), + ) + layout = document.get('layout_snapshot') if isinstance(document, dict) else None + if not _layout_ready(layout if isinstance(layout, dict) else None): + pytest.skip(f'Layout not replayable for document_id={document_id}') + + profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0)) + result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout) + assert result.status == 'unique_match' + if document_id == 194: + assert result.profile_code == 'ODP-20260824-2C542346805B' + else: + assert result.profile_code diff --git a/backend/tests/test_shipping_order_profile_parse_validation.py b/backend/tests/test_shipping_order_profile_parse_validation.py index 2e27a6b0..5bcec765 100644 --- a/backend/tests/test_shipping_order_profile_parse_validation.py +++ b/backend/tests/test_shipping_order_profile_parse_validation.py @@ -166,6 +166,39 @@ def test_parse_validation_accepts_month_day_year_date_format(): assert result['metrics']['type_issue_count'] == 0 +def test_parse_validation_accepts_two_digit_year_dates(): + """关键断言:MM/DD/YY 通过类型 sanity,不得误杀 Hyve 等 PO 日期。""" + profile = _minimal_profile_snapshot(line_regions=[ + { + 'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.09, 'y1': 0.5}, + 'allowed_sources': ['pdf_coordinate'], + 'target_fields': [{ + 'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id', + }], + }, + { + 'field_id': 'date-id', 'field_code': 'requested_receipt_date', 'scope': 'line', + 'region': {'x0': 0.10, 'y0': 0.4, 'x1': 0.6, 'y1': 0.5}, + 'allowed_sources': ['pdf_coordinate'], + 'target_fields': [{ + 'scope': 'line', 'field_code': 'requested_receipt_date', 'field_id': 'date-id', + }], + }, + ]) + + result = validate_profile_parse_candidate( + profile_snapshot=profile, + layout=_layout_with_line_text('06/16/26'), + definition={'fields': [{ + 'field_code': 'requested_receipt_date', 'enabled': True, 'value_type': 'date', + }]}, + ) + + assert 'profile_parse_type_sanity_failed' not in result['reason_codes'] + assert result['metrics'].get('type_issue_count', 0) == 0 + + def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict: """构造明细区文字被纵向位移到冻结字段带之下的 layout。 diff --git a/backend/tests/test_shipping_order_profile_signature.py b/backend/tests/test_shipping_order_profile_signature.py index 3e116ac6..51eb3b66 100644 --- a/backend/tests/test_shipping_order_profile_signature.py +++ b/backend/tests/test_shipping_order_profile_signature.py @@ -74,6 +74,67 @@ def test_same_input_produces_same_checksum(): assert signature_checksum(first['signature']) == first['signature_checksum'] +def test_layout_signature_excludes_line_field_supplement_table_patterns(): + """ + 补充表不得进入匹配签名 table_patterns。 + + 关键断言:即便补充区样本含料号行文案,签名 identity 也只保留 business_lines, + 避免 line_field_supplement 污染表头原子硬互斥。 + """ + definition = _minimal_definition() + definition['table_regions'][0]['region_role'] = 'business_lines' + definition['table_regions'][0]['region'] = {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 0.55} + definition['table_regions'][0]['line_layouts'][0]['region'] = { + 'x0': 0, 'y0': 0.35, 'x1': 1, 'y1': 0.55, + } + definition['table_regions'].append({ + 'region_id': 'line_supplement', + 'region_role': 'line_field_supplement', + 'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9}, + 'line_layouts': [{ + 'layout_id': 'supp_main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [ + { + 'field_id': 'supp-ln', + 'field_code': 'customer_po_line_no', + 'scope': 'line', + 'region': {'x0': 0.05, 'y0': 0.1, 'x1': 0.2, 'y1': 0.4}, + 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'supp-pn', + 'field_code': 'part_number', + 'scope': 'line', + 'region': {'x0': 0.25, 'y0': 0.1, 'x1': 0.8, 'y1': 0.4}, + 'allowed_sources': ['pdf_coordinate'], + }, + ], + }], + }) + layout = _sample_layout(header_text='ITEM NO QTY') + # 补充表区高度内放入料号正文,模拟 HYVE 脏表头污染场景。 + dirty = 'WTP-B3-A08AR11000001 CN,TH,JP' + for index, char in enumerate(dirty): + layout['coordinate_evidence']['page_glyphs']['1'].append({ + 'text': char, + 'bbox': {'x0': 10 + index * 3, 'y0': 190, 'x1': 12 + index * 3, 'y1': 202}, + }) + + snapshot = build_layout_signature(definition=definition, sample_layouts=[layout]) + patterns = snapshot['signature']['table_patterns'] + region_ids = [item.get('region_id') for item in patterns] + assert region_ids == ['lines'] + joined = ' '.join( + str(token) + for pattern in patterns + for token in (pattern.get('header_tokens') or []) + ).upper() + assert 'WTP-B3-A08AR11000001' not in joined + assert 'CN,TH,JP' not in joined + + + def test_different_samples_produce_different_checksum(): """不同表头样本应产生不同 checksum。""" definition = _minimal_definition() @@ -182,3 +243,98 @@ def test_signature_relation_graph_uses_anchor_text_contract(): snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()]) assert isinstance(snapshot['signature']['field_relation_graph'], list) + + +def test_single_logical_header_wrap_excludes_secondary_visual_line_from_identity(): + """逻辑一行表头框住折行时,副标签并入所属列,不得拆成新身份列。""" + definition = _minimal_definition() + # 表头框盖住主行 + 折行副标签(与 Hyve 标注同构)。 + definition['table_regions'][0]['header_layouts'][0]['region'] = { + 'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.32, + } + page_h = 280.0 + main_y0, main_y1 = 60.0, 72.0 + wrap_y0, wrap_y1 = 76.0, 88.0 + glyphs = [] + # 主行:LN Quantity Part + x = 10.0 + for word in ('LN', 'Quantity', 'Part'): + for char in word: + glyphs.append({ + 'text': char, + 'bbox': {'x0': x, 'y0': main_y0, 'x1': x + 3, 'y1': main_y1}, + 'boundary_before': 'none', + }) + x += 3.5 + x += 8 + # 折行副标签:Vendor(落在 Part 列下方) + x = 40.0 + for char in 'Vendor': + glyphs.append({ + 'text': char, + 'bbox': {'x0': x, 'y0': wrap_y0, 'x1': x + 3, 'y1': wrap_y1}, + 'boundary_before': 'none', + }) + x += 3.5 + layout = { + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': page_h}}, + 'page_glyphs': {'1': glyphs}, + 'tables': {'table-1': glyphs}, + }, + } + pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0] + tokens = [str(item) for item in pattern['header_tokens']] + assert pattern['header_row_count'] == 1 + joined = ' '.join(tokens).casefold() + # 关键断言:Vendor 文案保留并入所属列,不得作为独立尾列。 + assert 'ln' in joined + assert 'quantity' in joined + assert 'part' in joined + assert 'vendor' in joined + assert tokens[-1].casefold() != 'vendor' + assert len(tokens) == len(pattern['column_centers']) + assert len(tokens) <= 3 + + +def test_multi_header_layouts_keep_both_visual_rows_in_identity(): + """多个 header_layout(真多行表头)须保留各行身份 token,不做折行合并。""" + definition = _minimal_definition() + definition['table_regions'][0]['header_layouts'] = [ + { + 'layout_id': 'header_r1', 'region': {'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.26}, + 'field_regions': [{ + 'field_id': 'hdr-item', 'field_code': 'item_no', 'scope': 'header', + 'region': {'x0': 0.05, 'y0': 0.21, 'x1': 0.2, 'y1': 0.25}, + 'allowed_sources': ['pdf_coordinate'], + }], + }, + { + 'layout_id': 'header_r2', 'region': {'x0': 0, 'y0': 0.27, 'x1': 1, 'y1': 0.33}, + 'field_regions': [{ + 'field_id': 'hdr-pr', 'field_code': 'pr_number', 'scope': 'header', + 'region': {'x0': 0.05, 'y0': 0.28, 'x1': 0.3, 'y1': 0.32}, + 'allowed_sources': ['pdf_coordinate'], + }], + }, + ] + glyphs = [] + for index, char in enumerate('ITEM'): + glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 60, 'x1': 13 + index * 4, 'y1': 72}}) + for index, char in enumerate('PRNO'): + glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 80, 'x1': 13 + index * 4, 'y1': 92}}) + layout = { + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 280}}, + 'page_glyphs': {'1': glyphs}, + 'tables': {'table-1': glyphs}, + }, + } + pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0] + joined = ' '.join(str(item) for item in pattern['header_tokens']).upper() + assert pattern['header_row_count'] == 2 + # 关键断言:两行正式表头都进入身份,不被折行合并误伤。 + assert 'ITEM' in joined + assert 'PRNO' in joined \ No newline at end of file diff --git a/backend/tests/test_shipping_runtime_parse_strategy.py b/backend/tests/test_shipping_runtime_parse_strategy.py index c573bf60..5e76e5d2 100644 --- a/backend/tests/test_shipping_runtime_parse_strategy.py +++ b/backend/tests/test_shipping_runtime_parse_strategy.py @@ -97,6 +97,74 @@ def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_busin assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) +def test_runtime_strategy_uses_dynamic_to_confirm_fixed_when_adaptive_conflicts(): + """关键断言:固定/自适应料号冲突时,动态列单侧覆盖固定则可落选;加长字段时升级动态列。""" + fixed = _row(line_no='1', part_no='B3-A08AR11000001') + fixed['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'}) + adaptive = _row(line_no='1', part_no='WTP-B3-') + adaptive['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'}) + dynamic = _row(line_no='1', part_no='B3-A08AR11000001') + dynamic['fields'].append({ + 'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR11000001', + }) + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[fixed], + adaptive_rows=[adaptive], + dynamic_rows=[dynamic], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_uses_dynamic_to_confirm_adaptive_when_fixed_conflicts(): + """动态只与自适应一致时,应落选自适应而非继续 Review。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='1', part_no='PART-WRONG')], + adaptive_rows=[_row(line_no='1', part_no='PART-RIGHT')], + dynamic_rows=[_row(line_no='1', part_no='PART-RIGHT')], + ) + + assert result.status == 'selected' + assert result.row_mode == 'adaptive_record_columns' + assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',) + + +def test_runtime_strategy_prefers_dynamic_when_it_extends_baseline_field_values(): + """动态无额外行但字段值严格加长时,也应升级动态列,避免截断料号。""" + fixed = _row(line_no='1', part_no='B3-A08') + dynamic = _row(line_no='1', part_no='B3-A08AR11000001') + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[fixed], adaptive_rows=[], dynamic_rows=[dynamic], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_prefers_dynamic_when_it_confirms_fixed_and_recovers_extra_row(): + """动态确认固定侧且额外恢复记录时,应升级为动态列。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='20', part_no='PART-B')], + adaptive_rows=[_row(line_no='20', part_no='PART-X')], + dynamic_rows=[ + _row(line_no='10', part_no='PART-A'), + _row(line_no='20', part_no='PART-B'), + ], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value(): """同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。""" fixed = _row(line_no='10', part_no='PART-A') diff --git a/docs/demand.md b/docs/demand.md index 45387816..ae38fa2e 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -5,7 +5,7 @@ - 覆盖预付款、出货款、验收款、质保款四阶段:预付款为合同申请单归档后第 7/14/21 天;出货款为交货期限前 7 天、当天、后 14 天;验收款为验收归档后第 30/40/60 天;质保款为质保到期前 7 天、当天、后 14 天。 - 三轮收件人依次为采购负责人、采购部负责人、采购分管领导。预付款及出货款以 ERP `apa_file` 付款事实判定;匹配付款后仅关闭尚未发送的轮次,保留已发送审计。 - 每日定时扫描仅生成待发送预警;每周五 18:00 按收件人归并发送一条企业微信汇总。消息仅展示总笔数及阶段数量;每位收件人附件一份 Excel,列明需付款合同及付款明细。 - - 工作台左侧“合同付款预警”提供二级入口:“合同台账”仅展示采购单号非空、合同号/金额/交期等关键事实和四阶段付款比例完整且合计 100% 的合同;不再以设备采购合同(项目型 V4)或其他固定模板作为准入条件。“待确认合同”集中展示采购单号缺失、付款比例缺失/重复/合计不为 100%,或合同金额、交货期限等关键事实缺失/与 OA 字段冲突的合同,这些合同不得进入自动付款预警;“周汇总批次”独立查看按收件人生成的批次、Excel 附件和发送审计。点击合同可查看详情、解析原因和原文附件。 + - 工作台左侧“合同付款预警”提供二级入口:“合同台账”仅展示采购单号非空、合同号/金额/交期等关键事实和四阶段付款比例完整且合计 100% 的合同;不再以设备采购合同(项目型 V4)或其他固定模板作为准入条件。“待确认合同”集中展示采购单号缺失、付款比例缺失/重复/合计不为 100%,或合同金额、交货期限等关键事实缺失/与 OA 字段冲突的合同,这些合同不得进入自动付款预警;“周汇总批次”独立查看按收件人生成的批次、Excel 附件和发送审计。台账与待确认列表均支持按合同编号、流程编号、采购单号或供应商名称模糊检索。台账顶部四张汇总卡按合同统计即将到期(7日内)、逾期未付、待补充、本月应付(全量台账),点击过滤列表。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅管理员可见。点击合同可查看详情、解析原因和原文附件。 - OA 合同申请单同时存在“合同附件”和“盖章完成合同上传”时,必须优先下载并解析后者;普通合同附件仅在盖章完成合同缺失或下载失败时作为备用。 - OA 下载的扫描版 PDF 先通过 MinerU 转为保留标题、表格和阅读顺序的 Markdown,再运行合同付款条款规则;MinerU 失败或无结果时回退原 PDF 文字层/OCR,仍无法确认的合同保留在“待确认合同”。 @@ -205,7 +205,7 @@ - **RPA 旁路**:RPA Profile 只用于定时库存导出、用户手动刷新和配置测试;排程以 `source_codes` 为目标,按 Profile 分组复用登录,但每个文件必须独立记录 Source。 - **配置归属**:连接配置只保存登录地址、加密凭据和连接级登录配置;库存源只持久化 `report_path_json` 与 `query_parameters_json`。DBS 路径为业务组/业务项目/报表分组/报表名;参数支持单选、文本多值、列表多选。订单到库存站点的选择只由版本化路由规则决定。 - **解析方案直接绑定(一期)**:停用库存站点在编辑表单直接选择已发布的库存文件解析方案,随“保存更改”一次提交;批量绑定仍执行全量预检并写追加式前后快照审计。管理员无需填写绑定原因;已启用站点、草稿/退役方案及发货模板库存字段不兼容时必须拒绝。绑定递增站点配置版本,使旧测试证据失效。 -- **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。前端不提供“确认绑定”或“启用站点”二次操作,只显示当前唯一阻塞项及其操作。Dify 无需配置变更。 +- **自动启用(二期)**:当前绑定的已发布解析方案通过本次配置测试(或已绑定解析的查询成功但无库存)后,后端复用同一正式门禁自动启用站点;必要条件缺失时绝不启用。首次启用不提供“确认绑定”二次操作,只显示当前唯一阻塞项及其操作。站点停用后若正式门禁仍满足,管理端提供“启用库存站点”按钮(调用既有 activate API);也可再次测试导出以触发自动启用。Dify 无需配置变更。 - **空库存语义(二期)**:RPA 查询成功但无库存是有效业务结果,不得显示为连接或导出失败。站点验证区分“连接/查询已验证”与“数据行待首次非空文件验证”;已绑定 published 方案及发货模板的站点可继续启用。行级解析验证与外部仓库映射均不阻断启用:前者在首次非空文件到达时验证,后者只在实际调拨前要求维护。调度空结果写入不可匹配的 `empty` 快照审计,绝不链接任务、参与库存匹配或生成发货 Excel。 - **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;`connector_type` 仅允许 `dbs` / `crane` 并用于 Driver 分发,不得复用 `ShippingTask.source_type`;不再使用 `site_id`。 - **Warehouse**:固定 Source 直接使用配置 Warehouse;动态 Source(Crane)以 `reservation_id + part_number` 从库存行取得 Warehouse,不维护 Crane Warehouse 清单。Warehouse 未解析或冲突时不得生成 Excel。 diff --git a/docs/features/contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html b/docs/features/contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html index 5bf04c14..1624c3a9 100644 --- a/docs/features/contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html +++ b/docs/features/contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html @@ -339,8 +339,8 @@

附件预览:合同付款预警明细.xlsx

-

仅展示当前收件岗位本周需跟进的事项,按逾期优先、计划预警日升序排列。

-
序号合同编号采购单号供应商付款阶段金额 / 比例日期锚点计划预警日待处理天数预警轮次收件岗位状态
+

仅展示当前收件人本周需跟进的事项,按逾期优先、计划预警日升序排列。

+
序号合同编号采购单号供应商付款阶段金额 / 比例日期锚点计划预警日待处理天数预警轮次收件人状态
@@ -422,9 +422,10 @@ dates = baseDate ? [baseDate] : []; } return dates.map((plannedDate, index) => { - const recipientRole = WARNING_ROLE[index + 1] || "采购负责人"; - const recipientName = recipientRole === "采购负责人" ? plan.owner : `${recipientRole}(岗位映射)`; - return { key: `${milestone.id}:${index + 1}`, round: index + 1, plannedDate, recipientRole, recipientName }; + const round = index + 1; + const recipientRole = WARNING_ROLE[round] || "采购负责人"; + const recipientName = round === 1 ? (plan.owner || "—") : (round === 2 ? "王主管" : "赵分管"); + return { key: `${milestone.id}:${round}`, round, plannedDate, recipientRole, recipientName }; }); } function warningRuleText(milestone) { @@ -531,7 +532,7 @@ ], claimFacts: {}, sentWarningKeys: ["o1:1"], reminderLogs: [ - { id: "or1", at: "2026-07-17 18:00", text: "周五付款预警汇总已发送 · 预付款第 1 次 · 收件岗位:采购负责人 · 详见 Excel 附件" }, + { id: "or1", at: "2026-07-17 18:00", text: "周五付款预警汇总已发送 · 预付款第 1 次 · 收件人:李采购 · 详见 Excel 附件" }, ], }, ], @@ -738,7 +739,7 @@ const plan = getPlan(state.wecomPlanId) || getPlan(state.currentPlanId) || state.plans[0]; const queue = weeklyQueue(); const preferred = queue.find((item) => item.plan.id === plan.id) || queue[0]; - const recipientName = state.wecomRecipientName || (preferred && preferred.recipientName) || "采购负责人(岗位映射)"; + const recipientName = state.wecomRecipientName || (preferred && preferred.recipientName) || (plan && plan.owner) || "—"; const items = queue.filter((item) => item.recipientName === recipientName); const byType = items.reduce((result, item) => ({ ...result, [item.milestone.type]: (result[item.milestone.type] || 0) + 1 }), {}); const summary = Object.entries(byType).map(([type, count]) => `${TYPE_LABEL[type]} ${count} 笔`).join(";") || "暂无待跟进事项"; @@ -752,7 +753,7 @@ "详细合同、金额、预警日期请查看附件《合同付款预警明细.xlsx》。", ].join("\n"); document.getElementById("excelPreviewRows").innerHTML = items.length - ? items.map(({ plan: item, milestone, plannedDate, round, recipientRole }, index) => `${index + 1}${item.contractNo}${item.purchaseOrderNo || "—"}${item.supplier}${TYPE_LABEL[milestone.type]}${money(milestone.amount)} / ${milestone.percent}%${milestone.type === "prepayment" ? (item.events.contract_archive || "待合同归档") : milestone.type === "acceptance" ? (item.events.acceptance_archive || "待验收归档") : milestone.dueDate}${plannedDate}${Math.max(0, -daysUntil(plannedDate))} 天第 ${round} 次${recipientRole}${statusPill(planBucket(item))}`).join("") + ? items.map(({ plan: item, milestone, plannedDate, round, recipientName }, index) => `${index + 1}${item.contractNo}${item.purchaseOrderNo || "—"}${item.supplier}${TYPE_LABEL[milestone.type]}${money(milestone.amount)} / ${milestone.percent}%${milestone.type === "prepayment" ? (item.events.contract_archive || "待合同归档") : milestone.type === "acceptance" ? (item.events.acceptance_archive || "待验收归档") : milestone.dueDate}${plannedDate}${Math.max(0, -daysUntil(plannedDate))} 天第 ${round} 次${recipientName}${statusPill(planBucket(item))}`).join("") : '本周无待发送事项'; state.currentPlanId = plan.id; } diff --git a/docs/features/contract-payment-plan/contract-payment-warning-proposal-v3.md b/docs/features/contract-payment-plan/contract-payment-warning-proposal-v3.md index 6db55ee9..7f09ce22 100644 --- a/docs/features/contract-payment-plan/contract-payment-warning-proposal-v3.md +++ b/docs/features/contract-payment-plan/contract-payment-warning-proposal-v3.md @@ -10,7 +10,7 @@ ## 1. 目标 -从 OA 归档合同中自动生成付款节点。系统每日扫描到期轮次,仅在每周五 18:00 按收件岗位发送企业微信汇总及 Excel 明细。预付款、出货款是否已经付款,以 ERP `apa_file` 为准。 +从 OA 归档合同中自动生成付款节点。系统每日扫描到期轮次,仅在每周五 18:00 按收件人发送企业微信汇总及 Excel 明细。预付款、出货款是否已经付款,以 ERP `apa_file` 为准。 ## 2. 总体流程 @@ -115,7 +115,7 @@ erDiagram - 每日扫描:仅生成到期的待发送记录,不发送企业微信。 - 每周五 18:00:以收件人为单位汇总待发送记录;无待处理事项时不发送空消息。 - 企业微信正文仅展示总笔数、按阶段汇总、Excel 附件和工作台入口,不逐笔展示详细信息。 -- Excel 一行对应一笔待跟进的付款节点,至少列合同编号、采购单号、供应商、付款阶段、金额、日期锚点、计划预警日、待处理天数、预警轮次和当前状态;按逾期优先、计划预警日升序排列。 +- Excel 一行对应一笔待跟进的付款节点,至少列合同编号、采购单号、供应商、付款阶段、金额、日期锚点、计划预警日、待处理天数、预警轮次、收件人(实际姓名)和当前状态;按逾期优先、计划预警日升序排列。 ## 7. 边界与待确认项 diff --git a/docs/features/contract-payment-plan/demand.md b/docs/features/contract-payment-plan/demand.md index e9e77baf..d51e6177 100644 --- a/docs/features/contract-payment-plan/demand.md +++ b/docs/features/contract-payment-plan/demand.md @@ -1,7 +1,7 @@ # 合同付款预警 Agent 需求说明 -> **版本**:V1.6(第二、三轮上级改查 OA 矩阵) -> **更新日期**:2026-09-02 +> **版本**:V1.10(企微 Excel 收件人列写实际姓名) +> **更新日期**:2026-09-10 > **状态**:待业务确认后进入开发/联调 > **适用范围**:采购合同付款预警工作台、OA 同步、企业微信通知 @@ -154,7 +154,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据; - 企业微信正文应包含:本周需跟进付款总笔数、按预付款/出货款/验收款/质保款的笔数汇总、Excel 附件说明及工作台入口。 - Excel 一行对应一笔需要付款/请款跟进的付款节点,不应输出无关合同或已停止预警的节点。 -- Excel 至少包含:序号、合同编号、采购单号、供应商、付款阶段、付款金额、付款比例、日期锚点、计划预警日、逾期/待处理天数、预警轮次、对应收件岗位、当前状态。 +- Excel 至少包含:合同编号、采购单号、供应商、付款阶段、付款金额、付款比例、日期锚点、计划预警日、逾期/待处理天数、预警轮次、收件人、当前状态。 +- Excel「收件人」列须写该批次实际收件人姓名(系统用户 `real_name`,为空时回退用户名),不得再写「采购负责人」等岗位名称。 +- Excel「状态」列须写中文(待发送 / 已发送 / 发送失败 / 已关闭),不得输出 `pending` 等内部英文码。 - Excel 按紧急程度排序:逾期在前,其次按计划预警日升序;同一收件人只收到其应处理的明细。 - Excel 文件应作为本次汇总发送的审计附件保存,可在工作台下载查看。 @@ -163,6 +165,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据; - 工作台应展示各付款阶段的规则说明、合同付款节点、日期依据和当前状态。 - 合同详情应展示每条预警的付款阶段、轮次、计划日期、实际汇总发送时间、收件人、汇总批次和发送状态。 - 工作台应展示下一次汇总发送时间(每周五 18:00)及本周待发送笔数。 +- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号或供应商名称模糊检索。 +- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、待补充、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。 +- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。 - 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。 ### FR-06 权限与数据安全 @@ -190,7 +195,7 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据; ### 8.3 企业微信汇总消息与附件 - 本周需要跟进的付款总笔数及阶段汇总; -- 当前收件岗位和汇总周期; +- 当前收件人和汇总周期; - Excel 明细附件及工作台入口; - 不在企业微信正文逐笔列出合同、供应商、金额等详细信息。 @@ -226,6 +231,10 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据; | 日期 | 版本 | 变更内容 | | --- | --- | --- | +| 2026-09-10 | V1.10 | 企微周汇总 Excel「收件岗位」列改为「收件人」,单元格写系统用户真实姓名(为空回退用户名);「状态」列改写中文(待发送/已发送/发送失败/已关闭),不再输出 pending 等英文码;三轮升级规则表仍按岗位定义。 | +| 2026-09-10 | V1.9 | 合同台账增加四张汇总卡:即将到期(7日内)、逾期未付、待补充、本月应付;均按合同计数、统计全量台账,点击过滤列表。 | +| 2026-09-10 | V1.8 | 同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 | +| 2026-09-10 | V1.7 | 合同台账与待确认列表的 keyword 增加供应商名称模糊匹配。 | | 2026-09-02 | V1.6 | 第二、三轮上级改查 OA:`HrmResource.lastname` 取部门,`Matrixtable_3.zz`/`jfl` 作为企微收件人;不再使用全局岗位用户 ID。 | | 2026-09-01 | V1.4 | 第一次预警收件人明确为台账申请人,按系统用户真实姓名唯一匹配;第二、三次为其上级主管,组织关系来源待 Q-04。 | | 2026-08-26 | V1.3 | 改为以 ERP apa_file 的合格付款记录判断预付款、出货款已付款;不再使用 OA 请款状态停止预警。 | diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index e64ec82f..74557b8f 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -72,7 +72,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,禁止自动猜测;未定义该专区的模板不扫描全文,原解析行为不变。 +- **Reservation ID 专区动态锚点(2026-08-25)**:仅当已选中模板定义了 `reservation_id_region` 时启用。该配置不再以保存时的 `page_no/region` 作为正式取值位置,而是补齐全文页面坐标证据后,按阅读顺序从首次 `Vendor Comments` 标题之后累计到首次 `Terms and Condition` / `Terms and Conditions` / `Terms & Conditions` 标题之前;区块可跨页。只在此封闭区块内解析带 `Reservation` 标签的合法 5/10 位数字,并复用既有行号归属和冲突规则。缺失起始锚点不扫描;缺失结束锚点时仍返回已累计窗内候选供展示与归属,但固定 `needs_review`,禁止当成可自动建单封闭证据;值冲突同样进入 Review。未定义该专区的模板不扫描全文,原解析行为不变。**画布预览候选、验证 current_sample、盲测候选与正式解析共用同一锚点扫描与归属契约**(2026-09-08);验证证据写入 `validation_evidence` 的 header/line `reservation_id` 字段,并在需复核时附带 `reservation_region_status/review_reasons`。 - `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`。 @@ -86,6 +86,8 @@ - 自动标注只生成 Draft 的 `layout_schema_candidates`/建议,不能直接作为生产规则、不能自动接受、更不能自动发布。生产通用解析必须有冻结 `generic_parse_plan`,绑定 Schema、Layout、候选 checksum、映射决定及字段 `cell_id/evidence_ref`;Plan 缺失、漂移或证据缺失即 Review。 - **模板样本就绪门禁(2026-08-21)**:上传成功只表示 PDF/EML 已物化为 `ShippingOrderDocument`,不表示可自动标注。Draft annotation sample 必须由同一 `refresh_profile_sample_readiness()` 在当前 ready Layout 上验证视觉主表、内容 hash、canonical payload checksum、parser provenance,并冻结 `layout_version_id + layout_payload_checksum` 后,才返回 `automark_ready=true`。保存草稿、样本状态轮询和 `/pdf-automark` 入队共用此服务;一旦主表缺失/歧义、Layout 尚未完成或身份不一致,返回稳定原因码并禁止入队,绝不降级成“配置无效”或猜测。Worker 执行期仍复验 Job 的冻结身份。状态按 `profile_id + annotation sample` 隔离,同一文档被其他 Draft 引用不会影响当前模板。该回填仅更新现有 Draft sample 字段和追加式审计,不新建 Profile 版本、不修改已发布版本。 - Profile 仅允许 `draft -> published`;发布前必须满足 Schema/字段绑定校验、训练样本、独立盲测、双人批准、冻结样本证据及发布检查。已发布/退役版本只读;演进只能克隆为新 Draft,旧发布版本退役。管理端不提供自动接受、自动批准或自动发布路径。 +- **盲测预览明细展示(2026-09-09)**:`reconstruct_coordinate_profile_rows_with_strategy` 在运行时策略为 `needs_review` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/验证人工核对;正式自动建单路径仍要求 `strategy.status == 'selected'`,不得把 fallback 当成可自动建单结果。盲测候选重建前还会确保表所在页的整页坐标证据已补齐。 +- **明细字段补充表 / COO(2026-09-09)**:`table_regions[].region_role` 区分 `business_lines`(默认,主明细命中源)与 `line_field_supplement`(同文档按 LN 补 `customer_part_number`/`part_number`,如 Hyve COO)。补充表不进入 `matches`/`multiple_business_tables`;合并策略为空值直补、主表为补充值前缀则补全、完整冲突则 Review 不覆盖;正式解析、盲测候选与验证 `current_sample` 共用 `line_field_supplement_merge`。重建时若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox **纵向扩展** glyph 范围,避免样本仅 1 行 COO、盲测多行时相对框偏矮读不到数据行。版面签名 `table_patterns` **排除** `line_field_supplement`,且仅取顶部连续表头带,避免副表/误挂表头污染 `header_tokens` 导致训练样本自命中 0%。 ### Dify 手工配置说明 @@ -1197,6 +1199,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 | `cancelled` / `unit_cancelled` / `cancellation_completed` | `cancelled` | 已取消 | | Run/Unit 成功终态 | `completed` | 处理完成 | +> **版式→抽取放行(Unit 级,2026-09-08)**:`waiting_layout` 表示 Run 内仍有 PDF 版式未完成,不再要求全部 layout 就绪才开始订单抽取。任一 PDF layout ready 即可抽取对应 Unit 并 `progress_ready_extraction_unit`;兄弟文件继续等待。Run 终态仍须等全部 Unit 收敛。layout 与 extraction 共 shipping 队列时,resume 入队的 extraction 使用抬高的 `priority`,避免被剩余 layout FIFO 堵住。 + - 投影字段冻结:`user_visible_stage`、`queue_position`(仅排队 Unit)、`elapsed_seconds`、`last_activity_at`、`health_tips[]`、`cancellation`、`available_actions`、`handling_items[]`(Run 级待补/冲突/冻结/复核/失败/预算停扩)、`primary_notice`、`progress_version`(Run)/`activity_version`(Unit)。 - Run 收口 `result_json` 保留受控处理事实:`pending_orders`(候选号/原因/缺失字段)、`auto_freeze.blocked_tasks`、`budget_stopped`;聊天卡与右侧「本次处理」按 `handling_items.category` 展示原因码、`affected_refs`(任务号/候选号/受限附件)与 `primary_action` 跳转,禁止仅用 `partially_completed`/`review_required` 笼统提示。聊天消息持久化去重签名包含 `handling_items`/`primary_notice`,保证历史会话恢复最新处理说明。 - 健康提示阈值(后端统一计算,前端禁止本地臆造):连续 60 秒无新活动 → `processing_slow`;排队超过 5 分钟 → `queue_backlog`;处理超过 30 分钟 → `processing_attention`。 @@ -1751,7 +1755,7 @@ GET /api/admin/shipping-order-schema/published-contract - 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。 - 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`shipping_inventory_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingInventoryParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。 - 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 -- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。 +- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。**身份契约**:`configuration_test` / `configuration_test_batch` 与 `scheduled` 同属按 run 计价模式,不携带订单 `task_no` / Attempt / Gate 等生产身份;Worker 不得对其做逐源 v2 身份 fail-closed(否则会误报 `trigger_identity_invalid` 并错误回调生产 `inventory-batch-ready`)。 - **一期直接绑定**:停用站点可通过 `POST /api/admin/shipping-notice/sources/{id}/bind-parsing-profile` 直接绑定一个 `published` Profile;多站点使用 `POST /api/admin/shipping-notice/sources/bulk-bind-parsing-profile`。`reason` 是可选补充说明;未填写时,服务端自动记录直接或批量绑定动作。服务端先全量检查站点停用、方案已发布及当前 published 发货模板引用的全部库存字段均由方案提供,任一失败则整批不写入。成功后增加 `source.config_version`、写入 `shipping_inventory_source_parsing_binding_audits` 前后快照,但不触发 RPA、不产生快照、不启用站点。管理员可通过 `GET /sources/{id}/parsing-binding-audits` 追溯绑定。**Dify 手动配置说明**:一期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;上述管理 API 不供 Dify 调用。 - **二期空库存验证**:Worker 将 `NoInventoryDataError` 作为 `status=empty` 回调,站点验证运行保存为 `completed_empty / empty_data_pending_validation`,而不是 `failed`。只有站点已绑定 `published` Profile 时,空结果才作为当前配置版本的连接/业务查询成功证据;否则仍失败,避免无解析定义时误放行。固定仓的空结果使 `configuration_test` 通过,`parsing_validation` 标为“待首次非空文件验证”但不阻断;动态仓仍阻断 `warehouse_identification`,因为空结果无法证明仓库识别和映射覆盖。定时 RPA 批量回调对 `skip_reason=no_inventory_data` 写入 `shipping_inventory_files.snapshot_status=empty`、`line_count=0` 的幂等审计快照;`find_latest_ready_snapshot`、任务链接与匹配链路只读取 `ready`,因此空快照绝不参与订单匹配或发货。**Dify 手动配置说明**:二期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;Dify 不读取站点验证或空快照状态。 - 库存站点详情的 `activation` 是 HXOPS 后端唯一的上线检查真相,返回 `ready` 与按配置顺序排列的 `checks[]`。每项包含稳定业务编号 `code`、`passed / pending / failed / stale` 状态、`blocking`、推荐 `action` 和非敏感 `evidence`;管理端只负责翻译与引导,不得根据表单值重算启用资格。`missing_requirements` 仅是由阻断 checks 派生的紧凑摘要。 @@ -2032,7 +2036,9 @@ python -m pip install playwright openpyxl pyyaml python -m playwright install chromium ``` -若使用本机 Edge 浏览器,worker 可配置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`。 +**默认使用 Playwright 捆绑 Chromium**(上一步已 `playwright install chromium`)。 +勿设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile +在 Excel 下载时会原生崩溃(`Download.save_as: TargetClosed` / 残留 `.crdownload`)。 #### 1.5.5 Windows RPA 主机:临时环境变量与登录测试 @@ -2053,7 +2059,7 @@ $env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOO $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" -$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" +# 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" @@ -2459,7 +2465,7 @@ $env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>" $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" -$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" +# 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 $env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers" $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop" @@ -3167,6 +3173,7 @@ API 层 - RPA 配置测试回调只在当前绑定方案为本次文件的 `exact`/`compatible` 候选时,写入 `current_profile_verified` 证据;候选为其他方案时只提示管理员在表单选择、保存并重新测试,绝不自动替换绑定。 - 对于当前绑定 published 方案,非空测试验证成功或空库存查询成功后,`inventory_configuration_test.report_test_export` 在同一事务调用 `shipping_inventory_service.activate_source_if_ready`。该函数复用 `get_source_activation_status`,仅当连接、解析方案、发货模板、模板字段契约及当前版本测试证据全部通过时设置 `source.enabled=True`。 - 自动启用不放宽任何门禁:缺少发货模板、模板字段不兼容、配置/连接版本已变更时均保持停用;外部仓库映射和首次非空文件的数据行验证仍属于后续流程,不阻断站点启用。Dify 无需修改配置。 +- **停用后再启用**:停用后若 `activation.ready` 仍为真,管理端显示“启用库存站点”并调用既有 `POST /sources/{id}/activate`(与自动启用同一门禁);表单有未保存修改时禁用该按钮。也可再次测试导出以触发 `activate_source_if_ready`。 ### 6.3 快照复用规则 @@ -3185,12 +3192,14 @@ API 层 - **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/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` +- **DOM 假空兜底**(2026-09-09):`result_ready` 后 DOM 明细行探测仅作加速;无行时重试一次 View Report,仍无行则继续 Excel 导出。真空只在落盘 Excel「有 Supplier ID/AWS Sku 表头但无明细」时记 `NoInventoryDataError`/`no_inventory_data`,避免 Salt Lake 等慢报表假 skip。 - 回调:`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`,不得等待库存轮询超时。 - 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai) - 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key - **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.` 的合并结果核对 ②③(DB 优先于 env 文件)。 +- **库存 RPA 企微/下载文件名**(2026-09-09):展示名统一为 `库存RPA-{yyyyMMdd}-{HHmm}-结果.xlsx` 与 `库存RPA-{yyyyMMdd}-{HHmm}-库存.zip`(`HHmm` 按任务 `schedule_timezone`,缺省 Asia/Shanghai,勿直接用 UTC/`run_no` 内嵌时刻);完整 `run_no` 只留在 textcard 与磁盘归档键 `{run_no}.zip`。ZIP 包内条目为 `{序号}_{source_code}.xlsx`(无 source_code 时回退仓码);`warehouse_id` / `inventory_file_no` 仅写入 `manifest.json`。 - **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。 ### 6.5 审计字段 @@ -3310,7 +3319,7 @@ API 层 邮件正文保持 `email_context`,但其受控 HTML 表会被确定性解析为 PO 级补充事实,而不是订单 Candidate 或订单抽取 Unit。每个补充值冻结 EML Intake、正文 Document、表格/行/列、DOM `cell_id`、原始值与规范化值;Run 仅冻结这项事实,Worker 不会对正文单独执行订单解析。 -合并优先使用 `PO + MPN`;只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。 +合并优先使用 `PO + MPN`;其次同 PO 且双方均有合法 `reservation_id` 时以 `po_reservation` 按行对齐(解决 allocation 表 APN 对不上 PDF 料号时仍可补库存源线索);只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。 #### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27,迁移前历史) diff --git a/docs/funclist.md b/docs/funclist.md index 3bb1e1bf..dad7f5af 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -6,12 +6,12 @@ | ------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 | | 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 | -| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件,并在“周汇总批次”独立入口保留批次审计。 | -| 合同付款台账与详情 | 已实现 | “合同付款预警 > 合同台账”服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;点击合同查看概览、原文附件、付款计划和预警记录。 | +| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;并在“周汇总批次”独立入口保留批次审计。 | +| 合同付款台账与详情 | 已实现 | “合同付款预警 > 合同台账”服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;关键词同时匹配合同号、流程号、采购单号和供应商;四张汇总卡按合同统计即将到期(7日内)、逾期未付、待补充、本月应付(全量台账),点击过滤列表;点击合同查看概览、原文附件、付款计划和预警记录。 | | 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入“待确认合同”,不得触发自动预警。 | | 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 | | 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不拉取 OA、不覆盖 OA 字段,用于规则升级后的待确认合同恢复。 | -| 合同付款专项权限 | 已实现 | 功能权限 `contract_payment.access`:admin 默认开启,普通用户需在用户管理勾选;无权限不展示侧栏,直链会提示并回应用管理,API 返回 403。 | +| 合同付款专项权限 | 已实现 | 功能权限 `contract_payment.access`:admin 默认开启,普通用户需在用户管理勾选;无权限不展示侧栏,直链会提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 | | OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 | ## 知识库同步状态校验 @@ -28,6 +28,7 @@ - Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。 - 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。 - Excel/CSV 分段使用独立配置 `KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL`(默认 1200)和表格行组段上限 `table_segment_max_chars`(默认 1000);普通文档仍使用 `KB_DIFY_SEGMENT_MAX_TOKENS`(默认 600)。 +- 工作台知识库源文件下载保存名为上传时的原始文件名;一次点击只触发一次下载。 ## 设备维保助手 @@ -120,6 +121,7 @@ | **旧 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 无需配置变更。 | +| **明细字段补充表(COO 按 LN 补料号)** | 已实现(2026-09-09) | `table_regions.region_role=line_field_supplement`;仅补 `customer_part_number`/`part_number`;正式解析/盲测/验证共用合并契约;冲突进 Review。见 `technical.md`。 | | 订单人工复核工作台(阶段 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)。 | @@ -701,9 +703,9 @@ | 四阶段付款节点 | 已实现 | 解析预付款、出货款、验收款、质保款;不完整合同进入待复核,不伪造节点。 | | 三轮分级预警 | 已实现 | 首次为台账申请人(系统用户真实姓名唯一匹配);第二、三次按申请人部门查 OA 矩阵 `zz`/`jfl`,该 ID 同时用于企业微信。 | | OA 厂商请款判定 | 已实现 | 同步「厂商预付款请款作业」,预付款/出货款存在对应请款事实即停止后续升级。 | -| 每日扫描与周五汇总 | 已实现 | 每日生成到期轮次待发送记录;仅周五 18:00 按收件人发送一条企业微信汇总及 Excel 明细附件。 | +| 每日扫描与周五汇总 | 已实现 | 每日生成到期轮次待发送记录;仅周五 18:00 按收件人发送一条企业微信汇总及 Excel 明细附件(「收件人」列为实际姓名)。 | | OA 增量同步 | 已实现 | 合同 HTTP 列表以 `oa-contract-archive` 为游标;验收 SQL 以 `oa-acceptance-archive` 独立游标。首次全量,增量按时间窗口 + 采购单号回补;触顶不推进合同断点;重复运行不重复入库。 | -| 工作台与审计 | 已实现 | “合同付款预警”左侧二级菜单分为合同台账与周汇总批次;台账展示本周待发送笔数和下一次周五 18:00;周汇总页可查看批次并下载 Excel 附件。具备 `contract_payment.access` 的用户可见菜单并调用 API,不要求平台 admin 角色。 | +| 工作台与审计 | 已实现 | “合同付款预警”左侧二级菜单分为合同台账与周汇总批次;台账/待确认支持按合同号、流程号、采购单号或供应商模糊检索;台账展示本周待发送笔数和下一次周五 18:00;周汇总页可查看批次并下载 Excel 附件。具备 `contract_payment.access` 的用户可见菜单并查询,不要求平台 admin 角色;同步/扫描/发送仅管理员。 | - [X] Admin 模板比对区域配置、V4 默认恢复与识别预览 - [X] 默认启用模板区域规则自动应用于 Chat 双文件比对 diff --git a/docs/superpowers/specs/2026-09-10-inventory-rpa-source-coalesce-design.md b/docs/superpowers/specs/2026-09-10-inventory-rpa-source-coalesce-design.md new file mode 100644 index 00000000..285bf27d --- /dev/null +++ b/docs/superpowers/specs/2026-09-10-inventory-rpa-source-coalesce-design.md @@ -0,0 +1,199 @@ +# 库存 RPA 跨订单按源合并(Source Coalesce)设计 + +> 日期:2026-09-10 +> 状态:已确认(brainstorming) +> 范围:货代发货通知 · 库存准备 / 按需 RPA trigger 去重 +> 相关实现:`per_source_rpa_service.py`、`inventory_workflow.py`、`inventory_rpa_workflow.py`、`rpa.py`、`ShippingTaskInventoryRpaAttempt` + +--- + +## 1. 问题 + +订单解析后自动推进库存准备时,若无可复用库存快照,会按单触发 RPA 并写入 trigger 文件。 + +当**尚未跑过定时批次 RPA**,且**一次提交解析大量订单**时: + +- 多单常依赖同一 `source_code`(同仓/同站点) +- 每单各自写一份(或单源 batch 包装的)trigger +- Worker 对同一源重复登录、导出,吞吐差、外部站点压力大 + +单票内「多源合并为一个 batch trigger」已存在(`ensure_all_required_sources_prepared`);缺口是 **跨订单、按源去重**。 + +--- + +## 2. 目标与非目标 + +### 目标 + +1. **快照优先**:未过期 ready 源级快照直接复用,零 RPA。 +2. **跨单按源合并**:同一 `source_code` 同时最多一次活动导出(一个 Leader + 一个 trigger)。 +3. **挂等**:其它订单以 Follower 挂到同一 `source_run_no`,不写 trigger。 +4. **成功唤醒**:回调落源级快照后,唤醒挂等单走「复用快照」路径续跑(避免海量空转轮询)。 +5. **失败同败**:Leader 失败/超时 → 同组 Follower 一并失败;不自动连环重试。 +6. **人工强制重抓**:`retry_rpa` 跳过复用与挂等,强制新开 Leader。 + +### 非目标 + +- 不新建「全局 Fetch」大表(在现有 Attempt 上扩展角色即可)。 +- 不改 Worker 导出协议 / 一次登录导全世界的新能力。 +- 不以长防抖窗口作为主路径。 +- 不禁止按需自动 RPA(仍自动推进;只去重)。 + +--- + +## 3. 已定决策 + +| # | 决策 | 选择 | +| --- | --- | --- | +| D1 | 优先级 | 未过期快照 → 再跨单按源合并 | +| D2 | 已有 in-flight | `auto` 挂等;`retry_rpa` 强制新开 | +| D3 | 同时缺快照如何合成一次 | **源级租约**:抢到锁的写 trigger,其余立刻挂等 | +| D4 | 成功后如何推进挂等单 | **混合**:源级落快照 + 唤醒 `auto_progress`/`ensure_inventory`,内部仍走复用路径 | +| D5 | Leader 失败 | **同败**:挂等单一并失败,各自提供 retry/上传入口 | +| D6 | 实现路线 | 方案一:源级租约 + Leader/Follower Attempt | + +--- + +## 4. 架构与数据模型 + +### 4.1 角色 + +| 角色 | 含义 | +| --- | --- | +| **Leader Attempt** | 抢到源级租约的订单:写 trigger,持有 Worker 身份键(`source_run_no` / `lease_token` 等) | +| **Follower Attempt** | 挂等订单:同 `source_code` + 同 `source_run_no`,**不写** trigger,不进 trigger 文件的 `inventory_sources[]` | + +### 4.2 Attempt 扩展(建议字段) + +在 `ShippingTaskInventoryRpaAttempt` 上增加(名称可在实现计划中微调,语义固定): + +- `role`:`leader` | `follower`(历史行默认视为 `leader`) +- `leader_task_no`:Follower 指向 Leader 的 `task_no`(Leader 自身可空或自指) +- `coalesce_group_id`:与共享的 `source_run_no` 对齐(或直接约定 `coalesce_group_id == source_run_no`,避免双键漂移) + +保留现有逐单 Attempt 审计、Gate/UI 对 `(task_no, source_code)` 状态的消费方式。 + +### 4.3 并发约束 + +1. **源级**:同一 `source_code` 同时最多 1 个 Leader(`status IN ('queued','running')`)——部分唯一索引或等价行锁。 +2. **单级**:保留现有 `(task_no, source_code)` 活动唯一,防止同单双点。 +3. **抢锁失败**:立即转 Follower,禁止自旋写盘。 +4. **定时批次**:若 scheduled 已是同源活动 Leader,按需 `auto` 只当 Follower。 + +### 4.4 多源订单 + +按源独立决策:源 X 可挂等、源 Y 可本单当 Leader;全部 required 源 `prepared` 后才进入匹配。 + +--- + +## 5. 数据流 + +### 5.1 `ensure_all_required_sources_prepared`(按源) + +```text +[1] mode != retry_rpa 且存在未过期 ready 快照 + → prepared + +[2] 查同源是否已有活动 Leader(任意 task,queued|running) + → 本单建 Follower Attempt(同 source_run_no) + → pending,不写 trigger + +[3] 否则抢源级租约 + → 成功:建 Leader Attempt,加入本轮待写 trigger 列表 + → 失败:回到 [2] 挂成 Follower + +[4] 循环结束 + → 仅本轮 Leader 源合并写入一个 batch trigger(延续单票内合并) + → Follower 不出现在 trigger 文件中 +``` + +`retry_rpa`:跳过 [1][2],对本单该源强制新 Leader;可按现语义将旧活动 Attempt 标 `superseded`。 +若其它单的 Follower 挂在被 supersede 的 `source_run_no` 上,跟随失败/被取代(见 §6)。 + +### 5.2 成功回调 + +```text +Worker 回调 → 以 Leader 身份键命中 + → ingest 源级快照 + → Leader → succeeded + → 同 coalesce_group 的 Follower → succeeded(共享 inventory_file_no) + → 对受影响 task_no 去重后入队 auto_progress / ensure_inventory + └─ 内部走复用快照,禁止二次写 trigger +``` + +### 5.3 失败回调 / 超时 + +```text +Leader failed | timeout + → 同组 Follower 一并 failed(同 error_code / message) + → 各单走现有失败收口(retry_rpa / 上传) + → 不自动连环重试 +``` + +### 5.4 与轮询关系 + +- 推进主路径:回调唤醒(D4)。 +- `poll` / `allow_auto_retry=False`:只读 Attempt 与快照事实,禁止新建 Attempt、禁止写 trigger。 +- UI 挂等期间可继续展示 `running`(有 Follower Attempt 事实)。 + +--- + +## 6. 错误处理与边界 + +| 场景 | 行为 | +| --- | --- | +| Leader 回调失败 / 超时 | 同组 Follower 同败;现有 timeout/exhausted 恢复动作 | +| 迟到回调(旧 `source_run_no`) | `superseded`;不覆盖已消费状态;不二次唤醒 | +| Leader 写 trigger 失败 | Leader + 本轮拟挂 Follower → `failed/trigger_not_written` | +| Worker 离线 | 现有心跳门禁;不抢租约、不写 trigger | +| `retry_rpa` | 仅该单该源新 Leader;不踢掉无关单的活动 Attempt;挂在被取代 `source_run_no` 上的 Follower 随组失败/取代 | +| 唤醒后快照已过期 | 重新走 [2][3],不假定一次成功永续 | +| 唤醒入队 | 同一回调对同一 `task_no` 只入队一次(job dedupe) | + +--- + +## 7. 组件落点(实现指引,非本 spec 任务拆解) + +| 区域 | 变更要点 | +| --- | --- | +| `ShippingTaskInventoryRpaAttempt` + 迁移 | `role` / `leader_task_no`(及源级 Leader 唯一约束) | +| `per_source_rpa_service.ensure_all_required_sources_prepared` | 快照 → 查跨单 Leader → 租约 → Leader/Follower 分流;trigger 仅含 Leader | +| 库存 RPA 回调路径 | 成功/失败扇出同组 Attempt;成功后唤醒受影响任务 | +| `queue_service` / auto_progress 入队 | 回调唤醒去重 | +| 测试 | 见 §8 | + +Worker 与 batch v2 trigger 契约保持不变;Follower 身份不进入 Worker 输入。 + +--- + +## 8. 测试要点 + +1. **快照优先**:同源未过期快照 → 0 trigger,多单 prepared。 +2. **跨单挂等**:A 为 Leader,B/C `auto` → 仅 1 个 trigger;B/C 为 Follower。 +3. **成功扇出**:回调后 A/B/C 均可复用快照且被唤醒(断言入队次数)。 +4. **失败同败**:Leader fail → Followers 同 `error_code`。 +5. **并发抢租约**:双请求同时缺快照 → 1 Leader + 1 Follower,1 个 trigger。 +6. **retry_rpa**:强制新 Leader/新 trigger,不复用旧快照。 +7. **多源混合**:X 挂等、Y 本单 Leader → trigger 仅含 Y。 +8. **poll 只读**:`allow_auto_retry=False` 不新建 Attempt、不写 trigger。 + +--- + +## 9. 验收标准 + +- 大批量解析且多单同仓、无预热快照时:同源活动导出次数 ≈ 1(而非 ≈ 订单数)。 +- 有未过期快照时:不因解析批量而写 trigger。 +- 挂等单在 Leader 成功后能自动续跑,无需依赖高频空转 poll。 +- Leader 失败时挂等单可解释地进入现有人工恢复,且无自动重试打爆。 +- `retry_rpa` 仍可绕过挂等强制重抓。 + +--- + +## 10. 开放实现细节(计划阶段拍板即可) + +以下不影响本设计语义,留给 implementation plan: + +- `coalesce_group_id` 是否物理列,或直接等于 `source_run_no`。 +- 源级 Leader 唯一用 PostgreSQL 部分唯一索引 vs 独立租约行。 +- 唤醒调用 `submit_auto_progress` 还是直接 `ensure_inventory` 的精确入口。 +- 历史 Attempt 回填:`role` 默认 `leader` 的迁移策略。 diff --git a/docs/tec.md b/docs/tec.md index 4e359bc3..36850952 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -3,14 +3,14 @@ ## 合同付款预警(2026-08) - 使用 Flask + SQLAlchemy 合同付款域模型,OA 同步、每日预警扫描与周汇总均注册为平台排程任务;默认时区 `Asia/Shanghai`,周汇总 Cron 为 `0 18 * * 5`。合同付款 Job 运行超时由 `CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS`(默认 1800 秒)回收:未超过最大重试次数的任务重新排队,耗尽后标记失败,避免 Worker 异常退出导致任务永久停在 `running`。 -- `contract_payment_alerts` 保存逐笔、逐轮、逐收件人的幂等记录;`contract_payment_alert_batches` 对 `(week_key, recipient_user_id)` 唯一,保存汇总统计、Excel 二进制附件及企微发送审计。 +- `contract_payment_alerts` 保存逐笔、逐轮、逐收件人的幂等记录;`contract_payment_alert_batches` 对 `(week_key, recipient_user_id)` 唯一,保存汇总统计、Excel 二进制附件及企微发送审计。Excel「收件人」列写入系统用户真实姓名(为空回退用户名),不再写岗位名称。 - 企业微信正文只发送汇总数字,附件通过现有临时媒体上传能力发送;OA、DMS 地址和凭据仅通过环境变量配置。 - - 合同台账接口采用 offset 服务端分页,最大每页 100 条;前端复用 `PaginationBar`,避免同步量增长后一次查询加载全部合同。付款解析不依赖设备采购合同(项目型 V4)或其他固定模板,只根据可识别的合同号、金额、交期及预付款、出货款、验收款、质保款四阶段比例生成计划;比例须完整、无重复且合计为 100%,并要求采购单号非空,作为 ERP `apa_file` 回查预付款/出货款完成事实的业务键。比例校验失败、采购单号缺失、关键事实缺失或合同正文与 OA 字段冲突时写入 `needs_review`,从正常台账排除并由“待确认合同”二级路由通过 `review_only=1` 集中查询。合同详情复用 `/contracts/{id}` 返回合同、附件、节点与解析问题,附件下载必须校验附件归属该合同,批次页面独立调用审计批次接口。 + - 合同台账接口采用 offset 服务端分页,最大每页 100 条;`keyword` 同时模糊匹配合同编号、流程编号、采购单号和供应商名称。`GET /contracts/summary` 按合同统计即将到期(7 日内)、逾期未付、待补充、本月应付,始终看全部已解析台账;列表 `focus` 与 keyword 叠加过滤。前端复用 `PaginationBar`,避免同步量增长后一次查询加载全部合同。付款解析不依赖设备采购合同(项目型 V4)或其他固定模板,只根据可识别的合同号、金额、交期及预付款、出货款、验收款、质保款四阶段比例生成计划;比例须完整、无重复且合计为 100%,并要求采购单号非空,作为 ERP `apa_file` 回查预付款/出货款完成事实的业务键。比例校验失败、采购单号缺失、关键事实缺失或合同正文与 OA 字段冲突时写入 `needs_review`,从正常台账排除并由“待确认合同”二级路由通过 `review_only=1` 集中查询。合同详情复用 `/contracts/{id}` 返回合同、附件、节点与解析问题,附件下载必须校验附件归属该合同,批次页面独立调用审计批次接口。 - OA 附件排序以字段语义为第一优先级:`盖章完成合同上传` 固定优先于 `合同附件`,不得被文件名中的“合同”等关键词逆转;同一字段内部再按文件名对正文和辅助文件排序。 - 普通 OA 同步仅补充本地空字段;管理员显式提交 `POST /api/contract-payment/sync` 的 `{ "force": true }` 时,才以 OA 本次非空字段覆盖合同主表。覆盖操作人、时间和 `before/after` 字段差异保存在既有 JSON 列 `source_payload_json.force_sync_audit`(最近 20 次),不新增数据库结构;附件下载及付款计划解析链路保持不变。 - 同一同步 Job 支持 `{ "reparse_existing": true }` 存量恢复模式:不依赖 OA 增量通知,遍历已有合同的已归档附件并按盖章完成合同上传优先级重跑解析,刷新 `parse_result_json`、解析状态和节点;单次最多 1000 份,没有附件或文件资产的记录安全跳过。 - OA 通知同步采用增量断点:`contract_payment_sync_states` 以 `state_key='oa-contract-archive'` 单行游标记录上次成功同步时间,下次用 `last_successful_sync_at - CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS` 作为归档时间下限(overlap 兜住迟到/越序记录)。翻页使用 `CONTRACT_PAYMENT_OA_SYNC_PAGE_SIZE` / `..._PAGE_PARAM`;`CONTRACT_PAYMENT_OA_SYNC_MAX_PAGES` 默认 `0`(翻到短页为止),仅约束增量窗口,首次全量忽略此上限。触顶且末页仍满页时标记截断,已入库记录保留但**不推进断点**。重复项由 `(event_type, source_event_id)` 幂等去重;仅当 OA 配置、列表接口可用且本轮未截断时才推进断点。增量窗口只拉"归档时间在窗口内"的合同,窗口外旧合同的字段修正由管理员显式触发:`{ force: true }` 同步绕过时间窗口全量重扫,`{ reparse_existing: true }` 存量重解析遍历全部已归档附件,都会覆盖窗口外记录。 - - 工作台与 `/api/contract-payment/*` 统一校验功能权限 `contract_payment.access`:`admin` 角色默认开启,其他角色默认关闭,可在用户管理中显式授予或关闭。前端侧栏与路由守卫只负责展示,后端仍做 403 强校验(`CONTRACT_PAYMENT.FORBIDDEN`)。企业微信收件人与该访问权解耦。 + - 工作台与 `/api/contract-payment/*` 统一校验功能权限 `contract_payment.access`:`admin` 角色默认开启,其他角色默认关闭,可在用户管理中显式授予或关闭。前端侧栏与路由守卫只负责展示,后端仍做 403 强校验(`CONTRACT_PAYMENT.FORBIDDEN`)。`POST /sync`、`POST /alerts/run`、`POST /alerts/weekly-run` 额外要求 `role=admin`(`CONTRACT_PAYMENT.ADMIN_REQUIRED`),企业微信收件人与该访问权解耦。 - 验收单归档不走合同申请单 HTTP 列表,而查 OA SQL Server(凭据复用 `OA_SQLSERVER_*`):`formtable_main_324.cgdh` 为采购单号,`requestId` 关联 `workflow_requestbase`,`currentnodetype='3'` 为已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。归档日取 `lastoperatedate`/`lastoperatetime`。事件幂等键 `oa-acceptance:{requestId}:c{contractId}`,按采购单号匹配台账;独立断点 `oa-acceptance-archive`。查询失败 fail-safe 跳过且不推进该断点。节点后于事件生成时,`_persist_payment_plan` 回放已有验收事件计算验收款/质保款日期。表名/字段可由 `CONTRACT_PAYMENT_OA_ACCEPTANCE_*` 覆盖。 - 第二、三轮收件人查同一 OA SQL:`HrmResource.lastname` 唯一匹配台账申请人,取其 `departmentid`;`Matrixtable_3.bm` 关联部门,`zz` 为第二轮、`jfl` 为第三轮。该 ID 即 `HrmResource.id` 与企业微信 userid。优先按 `users.wecom_userid` 映射系统用户,未绑定再用主管 `lastname` 唯一匹配 `real_name`;查不到不向第一轮兜底。表名/字段可由 `CONTRACT_PAYMENT_OA_HRM_*`、`CONTRACT_PAYMENT_OA_MATRIX_*` 覆盖。 @@ -1479,7 +1479,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t - 付款计划统一生成 `prepayment`、`shipment`、`acceptance`、`warranty` 节点;预付款以合同申请单归档日、出货款以交货期限、验收款以验收单归档日、质保款以质保到期日作为提醒锚点。 - 合同付款预警通过 ERP Oracle `apa_file` 查询付款完成事实:以 `apaud03` 关联采购单号,筛选 `apa41='Y'` 且 `apa63=1`,按 `apa34f` 汇总付款金额;累计金额覆盖节点金额时停止预付款/出货款后续提醒。ERP 未配置或查询失败时 fail-safe 按未付款处理。历史 `contract_payment_vendor_requests` 表保留兼容性,但不再作为付款完成停止条件。 - `contract_payment_alerts` 以 `(node_id, trigger_key, recipient_user_id)` 幂等,并保存 `alert_round`。第一轮收件人按台账申请人 `users.real_name` 唯一匹配,匹配失败或重名则不发送、不回退默认管理员。第二、三轮查 OA `HrmResource.lastname` → `departmentid` → `Matrixtable_3.bm`,分别取 `zz`/`jfl` 作为企微 userid;未命中不向第一轮兜底。历史环境变量 `CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS` / `CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS` 已不再参与解析。 -- 预警任务拆分为“每日扫描”和“周五 18:00 汇总发送”:每日仅产生待发送预警,周汇总按收件人聚合并生成 Excel 明细附件,再发送一条企业微信消息;无待发送事项不得发送空消息。汇总批次、Excel 文件和单笔预警的关联须可审计,且同一节点轮次在同一收件人下保持幂等。 +- 预警任务拆分为“每日扫描”和“周五 18:00 汇总发送”:每日仅产生待发送预警,周汇总按收件人聚合并生成 Excel 明细附件(「收件人」列为系统用户真实姓名,为空回退用户名),再发送一条企业微信消息;无待发送事项不得发送空消息。汇总批次、Excel 文件和单笔预警的关联须可审计,且同一节点轮次在同一收件人下保持幂等。 - 合同付款 OA 附件中的 PDF 与采购合同审核固定共用 `PROCUREMENT_CONTRACT_MINERU_*` 配置,并优先调用 MinerU 同步 `/file_parse`:请求携带 `lang_list=ch`、`backend`、`parse_method` 和 `formula_enable=false`,仅接受 `status=completed` 且结果含 `md_content` 的响应。付款条款规则直接消费 Markdown,以保留扫描版合同的表格与阅读顺序;MinerU 故障或空结果则回退附件文字层及历史 OCR,保证同步任务可继续完成。 - 验收归档读取 OA SQL Server(`OA_SQLSERVER_*`):`formtable_main_324.cgdh` 匹配采购单号,`workflow_requestbase.currentnodetype='3'`(归档);归档日取 `lastoperatedate`。事件先于付款节点时,解析落库后回放已有 `acceptance_archive` 计算验收款与质保款日期。 - `contract_templates.comparison_region_config` 使用 JSON 保存唯一默认启用模板的区域规则,由 Admin API 统一校验。 diff --git a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts index 7494953e..b4384b2d 100644 --- a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts +++ b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts @@ -589,7 +589,15 @@ export const readOrderProfilePreviewPageRegionText = ( signal?: AbortSignal, purpose?: 'reservation_id_region', renderedImageBase64?: string | null, -) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review'; reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }> }>( +) => requestJson<{ + document_id: number; + page_no: number; + text: string; + source: string | null; + status: 'needs_review'; + reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }>; + reservation_region_reason?: string | null; +}>( `/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, { method: 'POST', body: JSON.stringify({ document_id: documentId, region, ...(purpose ? { purpose } : {}), ...(renderedImageBase64 ? { rendered_image_base64: renderedImageBase64 } : {}) }), signal, ...jsonAuth(), }, diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts index 70475340..74b53486 100644 --- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts +++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts @@ -294,7 +294,7 @@ export function useScheduleAdminRuns( const a = document.createElement('a'); a.href = url; const disposition = res.headers.get('content-disposition'); - a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'inventory-rpa-raw.zip'; + a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || '库存RPA-库存.zip'; document.body.appendChild(a); a.click(); document.body.removeChild(a); diff --git a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue index 204c6228..99e69e45 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -171,8 +171,16 @@

{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}

-