diff --git a/backend/app/api/chat/sessions.py b/backend/app/api/chat/sessions.py index a46ab083..4e359b22 100644 --- a/backend/app/api/chat/sessions.py +++ b/backend/app/api/chat/sessions.py @@ -2,8 +2,8 @@ api/chat/sessions.py 用途:处理聊天会话、历史消息与本地结构化消息路由。 -依赖:chat.shared、chat.core、ChatSession、ChatLog。 -逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。 +依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。 +逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。 """ from __future__ import annotations @@ -246,7 +246,8 @@ def save_local_message(): 保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。 核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡; - 结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。 + 结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题; + user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。 """ user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) @@ -286,6 +287,13 @@ def save_local_message(): if user_query and _looks_like_review_auto_title(session.title or ''): session.title = _session_title_from_text(user_query) + # [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截 + if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload: + payload = { + **payload, + 'user_attachments': _normalize_user_attachments(payload.get('user_attachments')), + } + # 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录 # 这样能保证前端表单状态(例如已确认)被持久化 local_id = payload.get('formId') if payload and isinstance(payload, dict) else None diff --git a/backend/app/api/chat/shared.py b/backend/app/api/chat/shared.py index faf3c128..f3baf80a 100644 --- a/backend/app/api/chat/shared.py +++ b/backend/app/api/chat/shared.py @@ -43,7 +43,7 @@ from app.core.errors import ( SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' # 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。 -CHAT_USER_ATTACHMENT_LIMIT = 20 +CHAT_USER_ATTACHMENT_LIMIT = 200 CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} @@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]: """ 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 - 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。 + 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举; + 列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。 Args: - value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。 + value: 前端 user_attachments 原始值;必须为列表。 Returns: 可安全写入 JSON 的附件快照列表;非法项目被忽略。 + + Raises: + ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。 """ if not isinstance(value, list): return [] + if len(value) > CHAT_USER_ATTACHMENT_LIMIT: + raise ValidationError( + f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})', + code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED', + details={ + 'limit': CHAT_USER_ATTACHMENT_LIMIT, + 'count': len(value), + }, + ) normalized: list[dict] = [] - for item in value[:CHAT_USER_ATTACHMENT_LIMIT]: + for item in value: if not isinstance(item, dict): continue raw_name = str(item.get('name') or '') diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 328af407..640457dd 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -4,10 +4,13 @@ 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)、order_extraction_ready_document_ids(Unit 级放行)。 + order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)、 + order_extraction_has_extractable_ready_work(收口自交接判断)。 逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进, - 兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout; + 收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接; + 仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout; 运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed; + 两处续抽均 continue_from_running,避免复用即将结束的 running Job; 每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记; 不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*; 合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。 @@ -46,6 +49,7 @@ from app.services.shipping_notice.order_extraction_run_service import ( begin_input_freeze, complete_input_freeze, mark_order_extraction_persistence_started, + order_extraction_has_extractable_ready_work, order_extraction_layout_prerequisite_issues, order_extraction_layouts_pending, order_extraction_ready_document_ids, @@ -1158,8 +1162,36 @@ 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): + # [STEP] 收口前用 DB 实况判断版面就绪:有可抽 ready work 则自交接续抽, + # 覆盖「Job 中途 layout 变 ready」与「开工快照过期跳过」;勿仅信 layout_blocked_in_wave。 + has_ready_work = order_extraction_has_extractable_ready_work(run) + layouts_pending = order_extraction_layouts_pending(run) + if has_ready_work: + continue_job_id = _enqueue_ready_order_extraction_job( + run, + message='附件版面已就绪,继续识别剩余附件', + continue_from_running=True, + ) + run.current_job_id = continue_job_id + run.phase = 'waiting_layout' if layouts_pending else 'queued' + db.session.commit() + finish_job( + job.id, + result={ + 'run_no': run.run_no, + 'waiting_layout': bool(layouts_pending), + 'waiting_continue': True, + 'handoff_status': 'layout_ready_continue', + 'merged_unit_count': len(pending_merge_unit_ids), + 'ready_document_ids': sorted(ready_document_ids), + 'continue_job_id': int(continue_job_id), + }, + message='附件版面已就绪,已排队继续识别剩余附件', + owned_attempt=owned_attempt, + ) + return + if layouts_pending: + # 仅仍有 layout pending、无可抽 ready work:回到 waiting_layout,靠 layout 完成回调唤醒。 run.phase = 'waiting_layout' db.session.commit() finish_job( @@ -1197,7 +1229,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: commit=False, ) continue_job_id = _enqueue_ready_order_extraction_job( - run, message='运行时预算已用尽,继续识别剩余附件', + run, + message='运行时预算已用尽,继续识别剩余附件', + continue_from_running=True, ) run.current_job_id = continue_job_id run.phase = 'waiting_layout' diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index c1ff5278..2f8a1b8a 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -3,10 +3,11 @@ services/shipping_notice/auto_progress_controller.py 用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。 依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务; - process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。 + process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。 逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job - 在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll, - 强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 + 在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时 + 覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。 + 库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 """ from __future__ import annotations @@ -413,9 +414,15 @@ def submit_auto_progress( from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job from app.services.shipping_notice.process_gate_service import queue_gate_attempt + # 显式回到库存准备:用户点「重新获取」(retry_rpa) 或人工改源 + # (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照), + # 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。 explicit_inventory_retry = ( - str(inventory_mode or '').strip() == 'retry_rpa' - and str(resume_gate_code or '').strip() == 'inventory_preparation' + str(resume_gate_code or '').strip() == 'inventory_preparation' + and ( + str(inventory_mode or '').strip() == 'retry_rpa' + or str(trigger or '').strip() == 'manual_override_source' + ) ) if not explicit_inventory_retry: sync_fulfillment_gates_from_task( diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index b6cebb0d..3597cc5a 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -5,8 +5,8 @@ services/shipping_notice/lifecycle_projection.py 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因; [B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时 - 兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作; - 阶段入口与实际动作权限必须分开。 + 兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。 + 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 """ from __future__ import annotations @@ -75,6 +75,11 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'freight_uploading': 'freight_upload', 'manual_upload_handoff': 'freight_upload', 'completed': 'upload_complete', + # 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。 + 'step5_match_inventory': 'fulfillment_prep', + 'step6_generate_file': 'fulfillment_prep', + 'step3_inventory_prepare': 'fulfillment_prep', + 'step7_upload_freight': 'freight_upload', } def lifecycle_entries( 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 a44c0973..a252c96d 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -1263,13 +1263,27 @@ def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) -> def _enqueue_ready_order_extraction_job( - run: ShippingOrderProcessingRun, *, message: str, + run: ShippingOrderProcessingRun, + *, + message: str, + continue_from_running: bool = False, ) -> int: """ 为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。 核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到 _ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。 + 自交接续抽(预算耗尽 / layout ready)须 continue_from_running=True,仅对 queued + 去重,避免复用即将结束的 running Job。 + + Args: + run: 订单抽取 Run。 + message: Job 初始状态说明。 + continue_from_running: True 时 dedupe_statuses=('queued',),供当前 running + Job 出口自交接;False(默认)可复用 queued/running,供 layout 完成回调唤醒。 + + Returns: + 入队或复用的 Job.id。 """ from app.jobs.queue import enqueue from app.jobs.types import JobType @@ -1283,6 +1297,7 @@ def _enqueue_ready_order_extraction_job( priority=_ORDER_EXTRACTION_READY_PRIORITY, max_attempts=3, message=message, + dedupe_statuses=('queued',) if continue_from_running else None, commit=False, ) job = db.session.get(Job, int(job_id)) diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 4da9c9a9..55a1f473 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -971,11 +971,15 @@ def _handle_retry_inventory_preparation( inventory_payload['source_codes'] = list(line_scope['source_codes']) inventory_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id']) # [STEP] 按已有动作码映射 ensure_inventory mode(零新动作码)。 - # 禁止「人工入口一律 retry_rpa」:仅显式强制 RPA 码写 retry_rpa;poll 只读轮询; - # 首次 gate_attempt_passed 自动投递保持默认 auto(先复用快照)。 + # 禁止「人工入口一律 retry_rpa」:poll 只读;gate_attempt_passed 首投保持 auto; + # 人工改源显式 inventory_mode=auto 按指定源复用快照;其余强制 RPA 码才跳过复用。 action_code = str(payload.get('action_code') or '').strip() if action_code in _FORCE_INVENTORY_RPA_ACTION_CODES and not is_initial_auto_dispatch: - inventory_payload['mode'] = 'retry_rpa' + requested_mode = str(payload.get('inventory_mode') or '').strip() + if requested_mode == 'auto' and str(payload.get('trigger') or '') == 'manual_override_source': + inventory_payload['mode'] = 'auto' + else: + inventory_payload['mode'] = 'retry_rpa' if action_code == 'poll_inventory_preparation': # [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试, # 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。 @@ -1015,8 +1019,9 @@ def _handle_override_line_inventory_source( 覆写为任一**已启用**库存源,而不仅限于规则候选。先放开、后续再收紧到仅候选源。 校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写; - 覆写后把该行候选钉为所选源并重跑该行匹配(snapshot 复用/触发 RPA 由既有 - auto-progress / ensure_inventory 处理:有未过期快照直接匹配,否则重新 RPA)。 + 覆写后把该行候选钉为所选源。人工指定即定论:不再重跑路由规则。 + - 当前在 routing:passed 后由 complete → enqueue 首投库存准备(按冻结源取数)。 + - 当前在准备/匹配:定向回 inventory_preparation,mode=auto(有快照复用,无则 RPA)。 Args: execution: 门禁执行上下文。 @@ -1104,9 +1109,9 @@ def _handle_override_line_inventory_source( }, } - # 首次人工选源完成的是 routing Gate 本身;让 Attempt 以 passed 收口后, - # process_gate_service 会统一入队下一道 inventory_preparation,避免在当前 - # routing Attempt 内递归触发 RPA 而把 Gate 状态写错。 + # 人工指定源即定论:冻结候选后不再重跑路由规则。routing Gate 以 passed 收口, + # complete_gate_attempt → _enqueue_auto_progress_after_gate_pass 首投 inventory_preparation + #(按已冻结源取数:有 ready 快照复用,否则再 RPA)。禁止在本 Attempt 内递归推进。 if gate.gate_code == 'inventory_source_routing': return { 'outcome': 'passed', @@ -1123,18 +1128,16 @@ def _handle_override_line_inventory_source( from app.services.shipping_notice.progress_workflow import run_task_auto_progress - # [ROOT CAUSE FIX · RPA 不触发] 行级库存源覆写冻结新候选后,必须把 inventory_preparation Gate - # 作为「定向人工恢复」重新推进:显式传 resume_gate_code='inventory_preparation' 与 - # inventory_mode='retry_rpa'。否则 AutoProgress 会读取该 Gate 残留的 next_action_code - # (waiting_external → poll_inventory_preparation),只排队一个只读 poll,既不创建 - # InventoryPreparationAttempt 也不触发 RPA,最终永远停在 inventory_file_empty。 - # 与 execute_stage_capability 的「重新获取库存」路径保持同一语义(见 process_gate_service)。 + # [ROOT CAUSE FIX] 已在准备/匹配阶段改源:必须定向回到 inventory_preparation, + # 并取消残留 poll(见 submit_auto_progress 对 manual_override_source)。 + # inventory_mode=auto:按新冻结源执行——有未过期快照直接复用,无文件才 RPA; + # 禁止无差别 retry_rpa 把「已有指定源文件」误判成必须重导。 run_task_auto_progress( task.task_no, trigger='manual_override_source', operator_id=actor_id, resume_gate_code='inventory_preparation', - inventory_mode='retry_rpa', + inventory_mode='auto', ) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id) # 覆写库存源只改变后续取数/匹配的输入,不能把“库存准备”本身伪造成成功。 diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index d0689a19..933e53f7 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -7,6 +7,7 @@ services/shipping_notice/process_gate_projection.py 逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影; 用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断; pending/queued/running 不冒充人工待办,但保留 execution_status 供观测; + 无 Gate 行时 current_gate_code 回退 Execution.current_gate_code(对齐待办 SQL); explainability.details 仅白名单业务事实;request_id 仅真实 HTTP 请求号, execution_no 写入 details;blocking_message 为中文兜底,前端优先 i18n。 """ @@ -676,7 +677,11 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if not blocking and str(next_action or '').strip() == 'confirm_customer': next_action = None - current_gate_code = str((current or {}).get('gate_code') or '').strip() or None + current_gate_code = ( + str((current or {}).get('gate_code') or '').strip() + or str(getattr(execution, 'current_gate_code', None) or '').strip() + or None + ) allowed_actions: list[str] = [] action_items: list[dict[str, str]] = [] is_formal_inventory_matching = bool( diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index bd6f5701..181e52ea 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -236,6 +236,8 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: 根据 Gate 列表重算 Execution 当前门禁与主恢复动作。 核心逻辑:取第一个非 passed/skipped 门禁为 current;全部通过则 completed。 + 若上游 Gate 已是 invalidated,但下游仍停在真实阻断/执行态,则跳过该 + invalidated(陈旧失效残留),避免把已建单成功的 task_creation 误标为当前门禁。 """ gates = ( ShippingProcessGate.query @@ -245,12 +247,21 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: ) last_passed = None current = None - for gate in gates: + # 下游仍“在办事/已阻断”时,上游 invalidated 只是过期残留,不能抢 current。 + _ACTIVE_DOWNSTREAM = frozenset({ + 'blocked_manual', 'blocked_retryable', 'waiting_external', + 'failed_terminal', 'running', 'queued', + }) + for index, gate in enumerate(gates): if gate.status == 'passed': last_passed = gate.gate_code continue if gate.status == 'skipped': continue + if gate.status == 'invalidated' and any( + later.status in _ACTIVE_DOWNSTREAM for later in gates[index + 1:] + ): + continue current = gate break execution.last_passed_gate_code = last_passed @@ -957,8 +968,10 @@ def _enqueue_auto_progress_after_gate_pass( ) -> None: """门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。 - 核心逻辑:不再写 legacy shipping_notice_run;统一由 submit_auto_progress 创建 - ProcessGate Attempt/Job。已完成或仍需人工的任务会安全早停。 + 核心逻辑:刷新指针后对「当前未通过 Gate」入队唯一 Attempt/Job。典型场景: + 人工指定库存源使 ``inventory_source_routing`` passed 后,下一道仍是 + ``pending`` 且 ``next_action_code`` 为空的 ``inventory_preparation``——必须在此 + 补种首投动作并入队,按已冻结源取数,禁止静默 return 导致永久「库存文件未准备」。 """ try: # 直接为下一 Gate 创建 Attempt/ProcessGate Job,避免重新进入 @@ -970,8 +983,21 @@ def _enqueue_auto_progress_after_gate_pass( .with_for_update() .first() ) - if next_gate is None or not next_gate.next_action_code: + if next_gate is None: return + # [STEP] pending 门禁创建时 next_action 为空;契约 default_next_actions 也没有 + # pending/queued。若不补种,人工选源 passed 后会永远卡在库存准备未跑。 + if not next_gate.next_action_code: + if str(next_gate.status or '').strip() != 'pending': + return + seeded = primary_next_action_for_gate( + gate_code=str(next_gate.gate_code), + status='blocked_retryable', + ) + if not seeded: + return + next_gate.next_action_code = seeded + execution.primary_next_action_code = seeded if not action_belongs_to_gate( gate_code=next_gate.gate_code, action_code=str(next_gate.next_action_code), diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 17b115cc..4bd1e701 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -679,8 +679,13 @@ _USER_STAGE_TO_CODE: dict[str, str] = { 'waiting_review': 'waiting_human_review', 'inventory_fetching': 'inventory_fetch', 'inventory_matching': 'inventory_match', + # step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。 + 'step5_match_inventory': 'inventory_match', + 'step3_inventory_prepare': 'inventory_fetch', + 'step6_generate_file': 'excel_generate', 'excel_generating': 'excel_generate', 'freight_uploading': 'freight_upload', + 'step7_upload_freight': 'freight_upload', 'completed': 'completed', 'failed': 'failed_terminal', 'cancelled': 'cancelled', diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 843410e0..3bb53c84 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -15,8 +15,10 @@ services/shipping_notice/query_service.py list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办; serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create; 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与确认客户/来源文档; - 待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);无 Execution 回退 position/user_mode; - SQL CASE 仍为粗筛近似(双读过渡,与 Gate 可能短暂漂移); + 待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级); + 无 Execution fail-closed 进 pending(复核位 review,有 Excel 则 manual_upload,否则 exception),禁止默认 in_progress; + SQL CASE 与 derive_todo_category / F2 running 同序,处理中桶只对应系统在跑; + list 与 count 都以 CASE 为权威,禁止再用「有原因/有产物」粗筛漏掉 fail-closed 项; list 用 UNION ALL + COUNT/OFFSET/LIMIT,仅水合当前页(禁止 500 截断冒充总数); fetch_gate_positions 批量读 Execution.current_gate_code,供 Gate 推导待办避免 N+1; DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact); @@ -110,6 +112,19 @@ _REVIEW_TODO_POSITIONS = frozenset({ 'notice_text_extraction_failed', 'quality_issue', }) +_REVIEW_TODO_GATE_CODES = frozenset({ + 'order_field_extraction', + 'customer_resolution', + 'reservation_validation', +}) +_EXCEPTION_TODO_GATE_CODES = frozenset({ + 'inventory_sufficiency', + 'freight_upload_rpa', + 'inventory_source_routing', + 'excel_readiness', +}) +_RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'}) +_BLOCKED_OR_FAILED_EXECUTION_STATUSES = frozenset({'blocked', 'failed'}) _PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload", "intake_parse"}) _TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = { "pending": _PENDING_TODO_CATEGORIES, @@ -1051,7 +1066,8 @@ def _todo_category_from_gate( """ 从 Gate 位置推导 todo_category(替代 user_mode 路径)。 - 核心逻辑:derive_user_mode + derive_position → derive_todo_category。 + 核心逻辑:derive_user_mode + derive_position → derive_todo_category; + 无 Gate 时不得经本函数默认 in_progress。 Args: gate_pos: ``{'current_gate_code', 'status'}``;可为 None(仅靠 review_status)。 @@ -1112,12 +1128,11 @@ def _todo_category_from_process_gate( def task_todo_category(task: ShippingNotice) -> str: """ - 推导待办分类(服务端唯一口径):优先 Gate,无 Execution 回退 position/user_mode。 + 推导待办分类(服务端唯一口径):优先 Gate;无 Execution 时 fail-closed。 核心逻辑:wait_manual_upload→manual_upload;complete→done; must_human 且属复核入口→review,其余 must_human→exception; - auto_continue→in_progress。 - SQL CASE 仍为粗筛近似。 + auto_continue 且有 Gate 推进中→in_progress;无 Gate 禁止默认 in_progress。 Returns: review | exception | manual_upload | in_progress | done @@ -1128,14 +1143,19 @@ def task_todo_category(task: ShippingNotice) -> str: _process_gate_user_summary_for_task(task), getattr(task, 'review_status', None), ) + if gated is not None: + return gated + # Gate 投影无 current_gate_code(常见于仅有 Execution 指针、尚无 Gate 行)时, + # 与 SQL CASE 同源读最新 Execution,避免列表 hydrate 与 COUNT 分叉。 + gated = _todo_category_from_latest_execution(task) if gated is not None: return gated ui = resolve_task_ui_state(task) - return _todo_category_from_ui(ui.position, ui.user_mode) + return _todo_category_after_missing_gate(task, position=ui.position, user_mode=ui.user_mode) def _todo_category_from_ui(position: str | None, kind: UserMode) -> str: - """将 user_mode(及复核入口位置集合)映射为 todo_category(无 Gate 时回退)。""" + """将 user_mode(及复核入口位置集合)映射为 todo_category。""" if kind == UserMode.WAIT_MANUAL_UPLOAD: return "manual_upload" if kind == UserMode.COMPLETE: @@ -1147,6 +1167,98 @@ def _todo_category_from_ui(position: str | None, kind: UserMode) -> str: return "in_progress" +def _todo_category_without_gate(*, position: str | None, user_mode: Any) -> str: + """ + 无 Gate 时的待办分类:保留人工/完成细类,禁止把未知态当成系统处理中。 + + 核心逻辑:先走 ``_todo_category_from_ui``;若得到 in_progress 则按复核位 + 降为 review,否则 exception。 + """ + kind = user_mode if isinstance(user_mode, UserMode) else UserMode( + str(user_mode or UserMode.AUTO_CONTINUE), + ) + category = _todo_category_from_ui(position, kind) + if category != "in_progress": + return category + if str(position or "") in _REVIEW_TODO_POSITIONS: + return "review" + return "exception" + + +def _notice_current_export_artifact(task: Any): + """ + 取 Notice 当前可上传链路上的最新 Excel Artifact。 + + 核心逻辑:``ShippingExportArtifact.task_id`` 是 Notice.id;OT 根实体返回 None。 + """ + if isinstance(task, ShippingOrderTask): + return None + notice_id = getattr(task, 'id', None) + if notice_id is None: + return None + return ( + ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id == int(notice_id), + ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')), + ) + .order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()) + .first() + ) + + +def _todo_category_after_missing_gate(task: Any, *, position: str | None, user_mode: Any) -> str: + """ + 无 Gate 摘要时的待办分类。 + + 核心逻辑:与 SQL 同序——当前 Artifact 已 uploaded→done;否则先走 + ``_todo_category_without_gate``;仍为 exception 且有 ready/uploading Excel→manual_upload。 + """ + artifact = _notice_current_export_artifact(task) + if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() == 'uploaded': + return 'done' + category = _todo_category_without_gate(position=position, user_mode=user_mode) + if category != "exception": + return category + if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() in { + 'ready', 'uploading', + }: + return "manual_upload" + return category + + +def _todo_category_from_latest_execution(task: Any) -> str | None: + """ + Gate 行缺失时按最新 Execution 指针推导 todo_category,与 SQL CASE 对齐。 + + 核心逻辑:Execution.task_id 只认 OT.id;有 ``current_gate_code`` 则走 + ``_todo_category_from_gate``;否则返回 None 供无 Gate fail-closed。 + """ + if isinstance(task, ShippingOrderTask): + order_task_id = getattr(task, 'id', None) + else: + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is None: + return None + execution = ( + ShippingProcessExecution.query + .filter( + ShippingProcessExecution.task_id == int(order_task_id), + ShippingProcessExecution.status != 'superseded', + ) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None or not str(getattr(execution, 'current_gate_code', '') or '').strip(): + return None + return _todo_category_from_gate( + { + 'current_gate_code': execution.current_gate_code, + 'status': getattr(execution, 'status', None), + }, + getattr(task, 'review_status', None), + ) + + def _todo_category_from_task_row( row: Any, *, @@ -1156,7 +1268,8 @@ def _todo_category_from_task_row( """ 用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。 - 核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退。 + 核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退, + 且 fail-closed 不得默认 in_progress。 """ del extractions_with_lines # 领域行事实不再参与位置裁决 if gate_pos is not None and gate_pos.get('current_gate_code'): @@ -1166,7 +1279,6 @@ def _todo_category_from_task_row( ) from app.services.shipping_notice.process_gate_contract import ( derive_position, - derive_todo_category, derive_user_mode, ) review_status = getattr(row, 'review_status', None) @@ -1177,7 +1289,7 @@ def _todo_category_from_task_row( review_status=review_status, lifecycle_stage=None, ) - return derive_todo_category(user_mode=user_mode, position=position) + return _todo_category_after_missing_gate(row, position=position, user_mode=user_mode) def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]: @@ -1435,12 +1547,15 @@ def _enrich_task_center_fields( ui_state.get("process_gate") if isinstance(ui_state, dict) else None, ui_state.get("review_status") if isinstance(ui_state, dict) else getattr(task, 'review_status', None), ) + if gated is None: + gated = _todo_category_from_latest_execution(task) if gated is not None: data["todo_category"] = gated else: - data["todo_category"] = _todo_category_from_ui( - ui_state.get("position") if isinstance(ui_state, dict) else None, - UserMode(str((ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE)), + data["todo_category"] = _todo_category_after_missing_gate( + task, + position=ui_state.get("position") if isinstance(ui_state, dict) else None, + user_mode=(ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE, ) _inject_unified_processing_fields(task, data) # [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。 @@ -1922,14 +2037,31 @@ def _gate_todo_category_sql_whens(task_id_column): """ Gate 优先的 todo_category CASE when 列表(对齐 derive_todo_category)。 - 核心逻辑:复核 gate→review;人工上传 handoff→manual_upload; - 短缺/失败类 gate→exception;准备/匹配运行中→in_progress。 + 核心逻辑:Execution.status 区分系统在跑与阻断;复核 gate 仅在 blocked/failed + 时进 review;人工上传 handoff→manual_upload;短缺/失败类 gate→exception; + active/waiting_external→in_progress。禁止无状态默认 in_progress。 """ gate_code = _latest_process_execution_field_sql(task_id_column, 'current_gate_code') gate_exec_status = _latest_process_execution_field_sql(task_id_column, 'status') + blocked_or_failed = gate_exec_status.in_(tuple(sorted(_BLOCKED_OR_FAILED_EXECUTION_STATUSES))) + running_exec = gate_exec_status.in_(tuple(sorted(_RUNNING_EXECUTION_STATUSES))) return [ ( - gate_code.in_(('order_field_extraction', 'customer_resolution', 'reservation_validation')), + db.and_( + gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))), + blocked_or_failed, + ), + literal('review'), + ), + ( + db.and_( + gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))), + running_exec, + ), + literal('in_progress'), + ), + ( + gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))), literal('review'), ), ( @@ -1945,35 +2077,28 @@ def _gate_todo_category_sql_whens(task_id_column): ), ( db.and_( - gate_code.in_( - ( - 'inventory_sufficiency', - 'freight_upload_rpa', - 'inventory_source_routing', - 'excel_readiness', - ) - ), - gate_exec_status.in_(('blocked', 'failed')), + gate_code.in_(tuple(sorted(_EXCEPTION_TODO_GATE_CODES))), + blocked_or_failed, ), literal('exception'), ), ( - gate_code.in_( - ( - 'inventory_preparation', - 'inventory_matching', - 'inventory_field_mapping', - 'order_freeze_readiness', - 'artifact_generation', - ) - ), + gate_exec_status.in_(('failed',)), + literal('exception'), + ), + ( + gate_exec_status.in_(('blocked',)), + literal('exception'), + ), + ( + running_exec, literal('in_progress'), ), ] def _order_task_todo_category_sql_expr(): - """按 Gate 优先、再领域事实投影 OT 待办,禁止读取库存 JSON 投影。""" + """按 Gate 优先、再领域事实投影 OT 待办;无判定时 fail-closed 为 exception。""" stage = db.func.lower(db.func.coalesce(ShippingOrderTask.stage, "")) reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, "")) ready_file = exists( @@ -2046,7 +2171,7 @@ def _order_task_todo_category_sql_expr(): literal("in_progress"), ), (stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")), - else_=literal("in_progress"), + else_=literal("exception"), ) def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False): @@ -2484,7 +2609,8 @@ def _task_todo_category_sql_expr(): 待办 todo_category 的 SQL CASE:Gate 优先,再 review_status / 领域标量回退。 核心逻辑:不再与 resolve_task_ui_state「同序」;与 ORM - ``task_todo_category`` / ``derive_todo_category`` 对齐,供 UNION 分页与徽标 COUNT。 + ``task_todo_category`` / ``derive_todo_category`` 对齐。无 Gate 且无法判定时 + fail-closed 为 exception,禁止 else in_progress。 """ has_lines = _task_has_dynamic_order_lines_sql() reason = select(ShippingOrderTask.pending_human_reason).where( @@ -2538,33 +2664,15 @@ def _task_todo_category_sql_expr(): literal("exception"), ), ( - db.and_(snapshot_id.is_(None), has_lines), + db.and_( + snapshot_id.is_(None), + has_lines, + ), literal("in_progress"), ), (reason == PH_RPA_EXHAUSTED, literal("exception")), # Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。 (artifact_exists, literal("manual_upload")), - ( - db.and_( - _sql_str_blank(review_status), - _sql_str_blank(reason), - ~exists().where( - ShippingTaskInventoryLink.task_id == ShippingNotice.order_task_id, - ShippingTaskInventoryLink.is_active.is_(True), - ShippingTaskInventoryLink.invalidated_at.is_(None), - ), - ), - literal("in_progress"), - ), - ( - db.and_( - _sql_str_blank(review_status), - _sql_str_blank(reason), - ~match_exists, - has_lines, - ), - literal("in_progress"), - ), ( db.and_( match_exists, @@ -2572,7 +2680,6 @@ def _task_todo_category_sql_expr(): ), literal("manual_upload"), ), - (match_exists, literal("in_progress")), (reason == PH_INV_UNAVAIL, literal("exception")), (reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")), ( @@ -2591,7 +2698,7 @@ def _task_todo_category_sql_expr(): (reason == PH_UPLOAD_RPA_PENDING, literal("exception")), # Excel 后待人工上传登记。 (upload_pending, literal("manual_upload")), - else_=literal("in_progress"), + else_=literal("exception"), ) def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]: @@ -2657,23 +2764,15 @@ def _todo_tasks_base_query( task_no: str | None, ): """ - 构造带粗筛 + 精确 category CASE 过滤的 Task 待办查询。 + 构造带精确 category CASE 过滤的 Task 待办查询。 - 核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。 + 核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed); + done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。 """ q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin) workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() - workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() - workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() - workflow_customer_pending = exists( - select(1).select_from(ShippingCustomerShadowResolution) - .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) - .where(ShippingOrderTask.id == ShippingNotice.order_task_id, - ShippingCustomerShadowResolution.status != 'confirmed') - ) artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) upload_success = _verified_upload_success_sql_expr() - upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown')))) match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) @@ -2703,25 +2802,9 @@ def _todo_tasks_base_query( ) ) - category_clause = _todo_category_sql_filter(allowed) - if category_clause is not None: - q = q.filter(category_clause) - if normalized_bucket in {"pending", "processing"}: - q = q.filter( - db.or_( - workflow_pending_reason.isnot(None), - workflow_review_status.isnot(None), - artifact_exists, - workflow_current_step.isnot(None), - exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), - )), - upload_pending, - ) - ) - elif normalized_bucket == "done": + # [STEP] 精确分类由 CASE 下推。pending 含无 Gate fail-closed,禁止再用 + # 「有原因/有产物/有 Execution」粗筛把裸 Notice 漏掉,否则 list 与 count 分叉。 + if normalized_bucket == "done": # Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。 q = q.filter( db.or_( @@ -2842,8 +2925,11 @@ def list_my_todos( ) ) - # 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败任务会从任务中心消失。 - ot_allowed = frozenset(cat for cat in task_allowed if cat in {"exception", "in_progress"}) + # 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败/复核任务会从任务中心消失。 + ot_allowed = frozenset( + cat for cat in task_allowed + if cat in {"exception", "in_progress", "review", "manual_upload"} + ) if ot_allowed: ot_q = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) if task_no: @@ -2988,7 +3074,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: pending += active.filter(category_expr.in_(task_pending_cats)).count() ot_active = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) ot_category = _order_task_todo_category_sql_expr() - pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse", "manual_upload"})))).count() + pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count() processing = active.filter(category_expr == "in_progress").count() processing += ot_active.filter(ot_category == "in_progress").count() done = ( diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 706bf052..1001f1c2 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -3523,7 +3523,9 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A # 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面, # 也不得作为「通知完成」的分子或分母。 item_group = _batch_user_group(item) - if item_group in {'cancelled', 'archived'}: + if item_group in {'cancelled', 'archived', 'unclassified'}: + continue + if item_group not in {'failed', 'waiting_human', 'processing', 'completed'}: continue summary = stage_summaries[lifecycle_stage] summary['total'] += 1 @@ -3537,8 +3539,10 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A summary['needs_action'] += 1 elif item_group == 'waiting_human': summary['needs_action'] += 1 - else: + elif item_group == 'processing': summary['processing'] += 1 + else: + continue if summary['blocking_reason'] is None and isinstance(item.get('blocking_reason'), dict): reason = item['blocking_reason'] summary['blocking_reason'] = { @@ -3604,8 +3608,8 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, Any]: """裁决会话批次的用户状态与唯一主动作。 - 优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造 - 人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。 + 优先级与文件 ``user_group`` 一致:失败优先,其次待人工,再次系统处理中。 + 有需处理时主状态不得标成 completed。 """ # 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。 # 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成 @@ -3614,16 +3618,28 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An _current_file_representatives(work_items), key=lambda item: { 'failed': 0, - 'retryable': 0, 'waiting_human': 1, - 'running': 2, + 'processing': 2, 'completed': 3, 'cancelled': 4, - }.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5), + 'archived': 4, + }.get(_batch_user_group(item), 5), ) selected = ranked[0] if ranked else {} + selected_group = _batch_user_group(selected) if selected else '' + status_by_group = { + 'failed': 'failed', + 'waiting_human': 'waiting_human', + 'processing': 'running', + 'completed': 'completed', + 'cancelled': 'cancelled', + 'archived': 'archived', + } return { - 'status': str(selected.get('user_status') or selected.get('status') or 'running'), + 'status': status_by_group.get( + selected_group, + str(selected.get('user_status') or selected.get('status') or 'running'), + ), 'stage': str(selected.get('user_stage') or selected.get('stage') or ''), # 5 业务阶段:与右侧批次中心轨道、工作台导航同源(前端只读做 i18n,禁止再映射)。 'lifecycle_stage': _lifecycle_stage_from_item(selected), diff --git a/backend/tests/test_chat_user_attachments.py b/backend/tests/test_chat_user_attachments.py index 90bbda70..3f00834e 100644 --- a/backend/tests/test_chat_user_attachments.py +++ b/backend/tests/test_chat_user_attachments.py @@ -1,16 +1,19 @@ """ backend/tests/test_chat_user_attachments.py -用途:验证聊天附件快照的后端白名单清洗与归属安全合并。 -依赖:chat API 附件辅助函数、pytest monkeypatch。 -逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。 +用途:验证聊天附件快照的后端白名单清洗、超限显式失败与归属安全合并。 +依赖:chat API 附件辅助函数、pytest、ValidationError。 +逻辑:覆盖敏感字段过滤、数量上限显式失败、无效项丢弃、无 ChatLog ID 不写入和有效终态合并。 """ +import pytest + from app.api.chat import ( CHAT_USER_ATTACHMENT_LIMIT, _merge_user_attachments_from_terminal_event, _normalize_user_attachments, ) +from app.core.errors import ValidationError def test_normalize_user_attachments_keeps_only_display_whitelist(): @@ -34,7 +37,7 @@ def test_normalize_user_attachments_keeps_only_display_whitelist(): }] -def test_normalize_user_attachments_limits_items_and_drops_invalid_values(): +def test_normalize_user_attachments_keeps_all_items_at_limit(): valid = { 'name': 'file.pdf', 'size': 1, @@ -42,16 +45,66 @@ def test_normalize_user_attachments_limits_items_and_drops_invalid_values(): 'type': 'document', 'source': 'local', } - items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)] - items[0] = {**valid, 'type': 'executable'} - items[1] = {**valid, 'source': 'unknown'} - items[2] = {**valid, 'size': -1, 'extension': '../pdf'} - + items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(CHAT_USER_ATTACHMENT_LIMIT)] normalized = _normalize_user_attachments(items) + assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT + assert normalized[0]['name'] == 'file-0.pdf' + assert normalized[-1]['name'] == f'file-{CHAT_USER_ATTACHMENT_LIMIT - 1}.pdf' - assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2 - assert 'size' not in normalized[0] - assert 'extension' not in normalized[0] + +def test_normalize_user_attachments_keeps_more_than_legacy_twenty(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(21)] + normalized = _normalize_user_attachments(items) + assert len(normalized) == 21 + + +def test_normalize_user_attachments_raises_when_over_limit(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 1)] + with pytest.raises(ValidationError) as exc_info: + _normalize_user_attachments(items) + err = exc_info.value + assert err.code == 'CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED' + assert err.details.get('limit') == CHAT_USER_ATTACHMENT_LIMIT + assert err.details.get('count') == CHAT_USER_ATTACHMENT_LIMIT + 1 + + +def test_normalize_user_attachments_drops_invalid_values_without_truncating_valid_tail(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [ + {**valid, 'type': 'executable'}, + {**valid, 'source': 'unknown'}, + ] + # 旧 [:20] 会在处理完前 20 项后丢弃尾部合法项;无 slice 后应保留 tail。 + items.extend({**valid, 'type': 'executable'} for _ in range(18)) + items.append({**valid, 'name': 'kept-tail.pdf'}) + normalized = _normalize_user_attachments(items) + assert normalized == [{ + 'name': 'kept-tail.pdf', + 'type': 'document', + 'source': 'local', + 'extension': 'pdf', + 'size': 1, + }] def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch): diff --git a/backend/tests/test_gate_derivation.py b/backend/tests/test_gate_derivation.py index e5c9a034..3184d0ef 100644 --- a/backend/tests/test_gate_derivation.py +++ b/backend/tests/test_gate_derivation.py @@ -412,3 +412,102 @@ def test_user_mode_review_status_must_human(): review_status=rs, lifecycle_stage=None, ) == 'must_human' + + +def test_sql_todo_category_review_gate_blocked_is_review(app): + """订单复核 Gate 阻断必须进 review,不得落入 in_progress。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-REVIEW-BLOCK') + ot = ShippingOrderTask( + task_no='OT-SQL-REVIEW-BLOCK', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='order_review', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-REVIEW-BLOCK', + task_id=int(ot.id), + status='blocked', + current_gate_code='order_field_extraction', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'review' + + +def test_sql_todo_category_running_inventory_prep_is_in_progress(app): + """库存准备 Execution=active 才是系统处理中。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-RUNNING') + ot = ShippingOrderTask( + task_no='OT-SQL-RUNNING-PREP', + user_id=user.id, + conversation_id=session.session_id, + status='processing', + stage='notification_preparation', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-RUNNING-PREP', + task_id=int(ot.id), + status='active', + current_gate_code='inventory_preparation', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'in_progress' + + +def test_sql_todo_category_without_gate_is_not_in_progress(app): + """无 Gate 的 OT 不得进入处理中桶。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-NO-GATE') + ot = ShippingOrderTask( + task_no='OT-SQL-NO-GATE', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='order_review', + progress_version=1, + ) + db.session.add(ot) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'exception' diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 8436d5bd..9ebf9f87 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -337,7 +337,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): db.session.commit() data = serialize_task_summary(task, viewer_user_id=11) - assert data["todo_category"] == "in_progress" + assert data["todo_category"] == "exception" assert data["created_by"] == 11 assert data["can_handle"] is True # 无 Gate 且无 review_status:薄回退不投影 order_freeze @@ -1161,12 +1161,74 @@ def test_todo_category_sql_matches_formal_notice_facts(app): assert sql_category == expected pending = list_my_todos(owner, bucket="pending", page=1, page_size=50) - assert pending["total"] == 1 + assert pending["total"] == 2 counts = count_my_todos(owner) - assert counts["pending"] == 1 + assert counts["pending"] == 2 assert counts["done"] == 1 + assert counts["processing"] == 0 + assert counts["total_pending_badge"] == 2 + + +def test_count_my_todos_running_gate_is_processing_and_not_double_counted(app): + """有 Notice 的 OT 只计 Notice 分支;active 库存准备进处理中。""" + with app.app_context(): + from app import db + from app.models import ShippingProcessExecution + from app.services.shipping_notice.query_service import count_my_todos, list_my_todos + + owner = 91 + order_task = ShippingOrderTask( + task_no="OT-RUN-ONCE", source_type="direct_pdf", user_id=owner, + status="processing", stage="notification_preparation", + ) + notice = ShippingNotice(task_no="SN-RUN-ONCE", source_type="manual", user_id=owner) + db.session.add_all([order_task, notice]) + db.session.flush() + notice.order_task_id = order_task.id + db.session.add(ShippingProcessExecution( + execution_no="SPE-RUN-ONCE", + task_id=int(order_task.id), + status="active", + current_gate_code="inventory_preparation", + )) + db.session.commit() + + counts = count_my_todos(owner) assert counts["processing"] == 1 - assert counts["total_pending_badge"] == 1 + processing = list_my_todos(owner, bucket="processing", page=1, page_size=50) + assert processing["total"] == 1 + assert processing["items"][0]["task_no"] in {"SN-RUN-ONCE", "OT-RUN-ONCE"} + + +def test_list_my_todos_order_review_gate_stays_in_pending(app): + """订单复核 blocked Gate 进入待处理,不进处理中。""" + with app.app_context(): + from app import db + from app.models import ShippingProcessExecution + from app.services.shipping_notice.query_service import count_my_todos, list_my_todos + + owner = 92 + order_task = ShippingOrderTask( + task_no="OT-REVIEW-PENDING", source_type="direct_pdf", user_id=owner, + status="waiting_review", stage="order_review", + ) + db.session.add(order_task) + db.session.flush() + db.session.add(ShippingProcessExecution( + execution_no="SPE-REVIEW-PENDING", + task_id=int(order_task.id), + status="blocked", + current_gate_code="order_field_extraction", + )) + db.session.commit() + + counts = count_my_todos(owner) + assert counts["processing"] == 0 + pending = list_my_todos(owner, bucket="pending", page=1, page_size=50) + assert pending["total"] == 1 + assert pending["items"][0]["todo_category"] == "review" + processing = list_my_todos(owner, bucket="processing", page=1, page_size=50) + assert processing["total"] == 0 def test_serialize_task_detail_workbench_view_drops_editor_fields(app): diff --git a/backend/tests/test_shipping_order_extraction_worker.py b/backend/tests/test_shipping_order_extraction_worker.py index 0bff7ccf..814fcd5c 100644 --- a/backend/tests/test_shipping_order_extraction_worker.py +++ b/backend/tests/test_shipping_order_extraction_worker.py @@ -1,4 +1,9 @@ -"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。""" +""" +订单抽取 Worker 单元测试。 + +覆盖:物化顺序、partial waiting_layout、layout_ready_continue 自交接、 +runtime_budget_continue、layout 调度失败收口、以及 continue_from_running 去重。 +""" from types import SimpleNamespace @@ -190,6 +195,7 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo ) monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101}) monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True) + monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False) monkeypatch.setattr( handler, 'transition_order_extraction_run', lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)), @@ -300,6 +306,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {}) monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202}) monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False) + monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False) monkeypatch.setattr( handler, 'transition_order_extraction_run', lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)), @@ -339,7 +346,9 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started')) monkeypatch.setattr( handler, '_enqueue_ready_order_extraction_job', - lambda _run, *, message: events.append(f'enqueue:{message}') or 999, + lambda _run, *, message, continue_from_running=False: ( + events.append(f'enqueue:{message}:continue={continue_from_running}') or 999 + ), ) def fake_finish(*_args, **kwargs): @@ -356,7 +365,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp assert 'processed:51' in events assert 'processed:52' not in events - assert any(item.startswith('enqueue:') for item in events) + assert any(item.startswith('enqueue:') and item.endswith(':continue=True') for item in events) assert 'terminalized' not in events assert 'persist_started' not in events assert run.status == 'processing' @@ -368,6 +377,267 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp assert pending_unit.status == 'pending' +def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(monkeypatch): + """ + 开工快照仍 layout_pending,收口时 DB 已有 extractable ready work:须 layout_ready_continue 自交接。 + + 断言:入队续抽且 continue_from_running=True;Run 不终态;handoff_status=layout_ready_continue。 + """ + import app.jobs.handlers.shipping_order_extraction as handler + + events: list[str] = [] + finished: dict = {} + enqueue_calls: list[dict] = [] + run = SimpleNamespace( + id=6, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE', 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=6, attempts=1, business_ref=run.run_no, max_attempts=3) + ready_unit = SimpleNamespace( + id=61, document_id=301, intake_id=1, status='pending', result_json=None, position=1, + cancellation_requested_at=None, + ) + stale_pending_unit = SimpleNamespace( + id=62, document_id=302, intake_id=1, status='pending', result_json=None, position=2, + cancellation_requested_at=None, + ) + plan = SimpleNamespace(id=6, unit_count=2, units=[ready_unit, stale_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, stale_pending_unit]), + ), + ), + )) + monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace())) + monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None) + monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None) + monkeypatch.setattr( + handler, 'materialize_order_extraction_run_inputs', + lambda _run, *, finalize_plan=True: 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: False) + # 开工快照:302 仍 pending;收口时 mock 为已有 ready work、layout 已全部就绪。 + monkeypatch.setattr( + handler, 'order_extraction_layout_prerequisite_issues', + lambda _run: {302: 'layout_pending'}, + ) + monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {301}) + monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False) + monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', 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, stale_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: {}) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit', + lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status), + ) + + def _process(**_kwargs): + events.append('processed') + ready_unit.status = 'merging_supplement' + return [{'po_number': 'PO-LAYOUT-CONTINUE', '_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_enqueue(_run, *, message, continue_from_running=False): + enqueue_calls.append({'message': message, 'continue_from_running': continue_from_running}) + events.append(f'enqueue:continue={continue_from_running}') + return 1006 + + monkeypatch.setattr(handler, '_enqueue_ready_order_extraction_job', _fake_enqueue) + + 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': 6}) + + assert 'processed' in events + assert 'progressed' in events + assert 'terminalized' not in events + assert 'persist_started' not in events + assert enqueue_calls == [{ + 'message': '附件版面已就绪,继续识别剩余附件', + 'continue_from_running': True, + }] + assert run.status == 'processing' + assert run.phase == 'queued' + assert run.current_job_id == 1006 + assert finished['result']['handoff_status'] == 'layout_ready_continue' + assert finished['result']['waiting_continue'] is True + assert finished['result']['waiting_layout'] is False + assert finished['result']['continue_job_id'] == 1006 + assert stale_pending_unit.status == 'pending' + + +def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_pending(monkeypatch): + """ + 收口时已有 ready work,但仍有兄弟 layout pending:自交接且 phase 保持 waiting_layout。 + + 断言:handoff_status=layout_ready_continue;waiting_layout=True;不终态 Run。 + """ + import app.jobs.handlers.shipping_order_extraction as handler + + finished: dict = {} + run = SimpleNamespace( + id=7, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE-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=7, attempts=1, business_ref=run.run_no, max_attempts=3) + ready_unit = SimpleNamespace( + id=71, document_id=401, intake_id=1, status='pending', result_json=None, position=1, + cancellation_requested_at=None, + ) + stale_pending_unit = SimpleNamespace( + id=72, document_id=402, intake_id=1, status='pending', result_json=None, position=2, + cancellation_requested_at=None, + ) + plan = SimpleNamespace(id=7, unit_count=2, units=[ready_unit, stale_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, stale_pending_unit]), + ), + ), + )) + monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace())) + monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None) + monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None) + monkeypatch.setattr( + handler, 'materialize_order_extraction_run_inputs', + lambda _run, *, finalize_plan=True: 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: False) + monkeypatch.setattr( + handler, 'order_extraction_layout_prerequisite_issues', + lambda _run: {402: 'layout_pending'}, + ) + monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {401}) + monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True) + monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', 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, stale_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: {}) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit', + lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status), + ) + monkeypatch.setattr( + handler, '_process_unit_with_retries', + lambda **_kwargs: (setattr(ready_unit, 'status', 'merging_supplement') or [ + {'po_number': 'PO-PARTIAL-CONTINUE', '_hxops_intake_id': 1}, + ]), + ) + monkeypatch.setattr( + handler, 'merge_unit_orders', + lambda *, orders, schema_definition, keep_primary_documents_separate: orders, + ) + monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: {}) + monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: (_ for _ in ()).throw( + AssertionError('must not terminalize'), + )) + monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None) + monkeypatch.setattr( + handler, '_enqueue_ready_order_extraction_job', + lambda _run, *, message, continue_from_running=False: 1007, + ) + monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs)) + 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': 7}) + + assert run.status == 'processing' + assert run.phase == 'waiting_layout' + assert run.current_job_id == 1007 + assert finished['result']['handoff_status'] == 'layout_ready_continue' + assert finished['result']['waiting_layout'] is True + assert finished['result']['waiting_continue'] is True + + +def test_enqueue_ready_order_extraction_job_continue_from_running_dedupes_queued_only(monkeypatch): + """ + continue_from_running=True 时 enqueue 必须只对 queued 去重,避免复用当前 running Job。 + + 断言:传入 dedupe_statuses=('queued',)。 + """ + from app.services.shipping_notice import order_extraction_run_service as svc + + captured: dict = {} + + def _fake_enqueue(*_args, **kwargs): + captured.update(kwargs) + return 42 + + monkeypatch.setattr('app.jobs.queue.enqueue', _fake_enqueue) + monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: None) + + run = SimpleNamespace(run_no='SNER-DEDUP', user_id=9) + job_id = svc._enqueue_ready_order_extraction_job( + run, message='续抽', continue_from_running=True, + ) + + assert job_id == 42 + assert captured.get('dedupe_statuses') == ('queued',) + assert captured.get('business_ref') == 'SNER-DEDUP' + + 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_override_inventory_source.py b/backend/tests/test_shipping_override_inventory_source.py index c68e698b..29ec2c7e 100644 --- a/backend/tests/test_shipping_override_inventory_source.py +++ b/backend/tests/test_shipping_override_inventory_source.py @@ -94,10 +94,10 @@ def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app): assert pinned['audit']['action'] == 'override_line_inventory_source' assert pinned['audit']['after']['selected_source_code'] == 'SRC_X' assert retrigger_calls and retrigger_calls[0] == task.task_no - # [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa), - # 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。 + # [回归] 改源后必须定向回 inventory_preparation;mode=auto 按指定源复用快照(无文件才 RPA)。 assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation' - assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa' + assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'auto' + assert retrigger_kwargs and retrigger_kwargs[0].get('trigger') == 'manual_override_source' assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'} diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py index 4d17260a..a23721d4 100644 --- a/backend/tests/test_shipping_process_gate_service.py +++ b/backend/tests/test_shipping_process_gate_service.py @@ -266,6 +266,60 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp assert queued[0]['gate_code'] == 'inventory_preparation' +def test_auto_progress_seeds_pending_inventory_preparation_after_routing_pass( + gate_execution, monkeypatch, +): + """人工指定源使 routing passed 后,必须补种并入队 pending 的库存准备。 + + [回归] pending 门禁 next_action_code 为空时旧逻辑静默 return,工作台永久显示 + 「库存文件未准备」;手动选源即定论,应按冻结源执行准备,不得再停在路由。 + """ + from app.services.shipping_notice import process_gate_service + + for prior_gate in ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id == int(gate_execution.id), + ShippingProcessGate.sequence_no < 13, + ).all(): + prior_gate.status = 'passed' + prior_gate.next_action_code = None + + prep = ShippingProcessGate.query.filter_by( + execution_id=int(gate_execution.id), gate_code='inventory_preparation', + ).one() + prep.status = 'pending' + prep.next_action_code = None + process_gate_service._refresh_execution_pointers(gate_execution) + db.session.flush() + assert gate_execution.current_gate_code == 'inventory_preparation' + assert prep.next_action_code is None + + queued: list[dict[str, object]] = [] + monkeypatch.setattr( + process_gate_service, + 'queue_gate_attempt', + lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=91))[1], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', + lambda **_kwargs: None, + ) + + routing = ShippingProcessGate.query.filter_by( + execution_id=int(gate_execution.id), gate_code='inventory_source_routing', + ).one() + process_gate_service._enqueue_auto_progress_after_gate_pass( + execution=gate_execution, + gate=routing, + ) + + assert prep.next_action_code == 'retry_inventory_preparation' + assert gate_execution.primary_next_action_code == 'retry_inventory_preparation' + assert len(queued) == 1 + assert queued[0]['gate_code'] == 'inventory_preparation' + assert queued[0]['input_snapshot']['action_code'] == 'retry_inventory_preparation' + assert queued[0]['input_snapshot']['payload']['trigger'] == 'gate_attempt_passed' + + def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch): """已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。""" from app.services.shipping_notice import process_gate_service @@ -334,6 +388,77 @@ def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution assert queued == [] +def test_refresh_pointers_skips_stale_invalidated_when_downstream_blocked(gate_execution): + """已建单成功后又被标 invalidated 的上游,不得盖住下游真实 blocked_manual。 + + 复现:task_creation 已 passed_at + invalidated,inventory_sufficiency=blocked_manual; + 刷新指针必须停在库存充足性,而不是「生成订单草稿」。 + """ + from datetime import datetime, timezone + + from app.services.shipping_notice import process_gate_service + + now = datetime.now(timezone.utc).replace(tzinfo=None) + for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all(): + if gate.gate_code == 'task_creation': + gate.status = 'invalidated' + gate.passed_at = now + gate.invalidated_at = now + gate.blocking_reason_code = 'gate_invalidated' + gate.next_action_code = 'retry_task_creation' + elif gate.gate_code in { + 'document_materialization', 'layout_parsing', 'document_profile_routing', + 'order_field_extraction', 'field_completeness', 'reservation_validation', + 'customer_resolution', 'duplicate_detection', 'field_conflict_resolution', + 'order_freeze_readiness', 'inventory_source_routing', 'inventory_preparation', + 'inventory_field_mapping', 'inventory_matching', + }: + gate.status = 'passed' + gate.passed_at = now + elif gate.gate_code == 'inventory_sufficiency': + gate.status = 'blocked_manual' + gate.blocking_reason_code = 'inventory_shortage_review_required' + gate.next_action_code = 'open_shortage_review' + elif gate.gate_code == 'excel_readiness': + gate.status = 'blocked_manual' + gate.blocking_reason_code = 'excel_not_ready' + # 其余保持 pending + db.session.flush() + + process_gate_service._refresh_execution_pointers(gate_execution) + db.session.flush() + + assert gate_execution.current_gate_code == 'inventory_sufficiency' + assert gate_execution.primary_next_action_code == 'open_shortage_review' + assert gate_execution.status == 'blocked' + + +def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_execution): + """故意失效且下游仍为 passed 时,current 必须停在 invalidated,等待重评。""" + from datetime import datetime, timezone + + from app.services.shipping_notice import process_gate_service + + now = datetime.now(timezone.utc).replace(tzinfo=None) + for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all(): + if gate.gate_code == 'task_creation': + gate.status = 'invalidated' + gate.passed_at = now + gate.invalidated_at = now + gate.blocking_reason_code = 'gate_invalidated' + gate.next_action_code = 'retry_task_creation' + else: + gate.status = 'passed' + gate.passed_at = now + db.session.flush() + + process_gate_service._refresh_execution_pointers(gate_execution) + db.session.flush() + + assert gate_execution.current_gate_code == 'task_creation' + assert gate_execution.status == 'blocked' + + diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index cea474bc..54cb3462 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -765,6 +765,67 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None: assert fulfillment['summary']['processing'] == 0 +def test_batch_waiting_human_has_zero_processing_on_card_and_stage() -> None: + """顶卡 processing_files 与阶段 processing 必须同时为 0。""" + work_items = [{ + 'work_item_type': 'order_task', + 'work_item_no': 'OT-WAIT-CARD', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', + 'user_stage': 'waiting_review', + 'source_summary': {'document_id': 601, 'filename': 'review.pdf'}, + }] + counts = _batch_file_counts(work_items) + assert counts['processing_files'] == 0 + assert counts['waiting_human_files'] == 1 + order_review = next( + node for node in _batch_lifecycle_nodes(work_items) + if node['code'] == 'order_review' + ) + assert order_review['summary']['processing'] == 0 + assert order_review['summary']['needs_action'] == 1 + assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human' + + +def test_batch_ui_state_does_not_show_completed_when_human_wait_exists() -> None: + """需处理文件存在时批次主状态不得为 completed。""" + work_items = [ + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-DONE-FILE', + 'user_group': 'completed', 'user_status': 'completed', + 'user_stage': 'upload_complete', + 'source_summary': {'document_id': 602, 'filename': 'done.pdf'}, + }, + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-WAIT-FILE', + 'user_group': 'waiting_human', 'user_status': 'running', + 'user_stage': 'waiting_review', + 'source_summary': {'document_id': 603, 'filename': 'wait.pdf'}, + }, + ] + assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human' + assert _batch_file_counts(work_items)['processing_files'] == 0 + + +def test_unclassified_file_does_not_inflate_stage_processing() -> None: + """未分类文件不得把五阶段写成「N 份处理中」。""" + work_items = [{ + 'work_item_type': 'order_task', + 'work_item_no': 'OT-UNCLASSIFIED', + 'user_group': 'unclassified', + 'user_status': 'unknown', + 'user_stage': 'freight_uploading', + 'source_summary': {'document_id': 604, 'filename': 'odd.pdf'}, + }] + assert _batch_file_counts(work_items)['processing_files'] == 0 + freight = next( + node for node in _batch_lifecycle_nodes(work_items) + if node['code'] == 'freight_upload' + ) + assert freight['summary']['processing'] == 0 + assert freight['summary']['total'] == 0 + + def test_conversation_status_groups_use_the_same_current_file_representative() -> None: """文件清单不能保留旧失败项,否则会与互斥统计和当前 CTA 相互矛盾。""" projection = _conversation_processing_from_work_items([ diff --git a/backend/tests/test_shipping_projection_cross_surface.py b/backend/tests/test_shipping_projection_cross_surface.py index 7d213f31..4f0909f6 100644 --- a/backend/tests/test_shipping_projection_cross_surface.py +++ b/backend/tests/test_shipping_projection_cross_surface.py @@ -36,6 +36,23 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage(): ) +def test_legacy_step_key_stage_maps_to_fulfillment_prep(): + """OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。""" + from app.services.shipping_notice.lifecycle_projection import project_lifecycle + + result = project_lifecycle( + current_gate={'gate_code': 'task_creation', 'status': 'invalidated'}, + blocking_reason={'code': 'gate_invalidated'}, + has_candidate_context=True, + processing_stage='step5_match_inventory', + ) + # processing_stage 权威高于错误的 task_creation 门禁。 + assert result['lifecycle_stage'] == 'fulfillment_prep' + assert result['lifecycle_authority'] == 'processing_stage' + current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current') + assert current['code'] == 'fulfillment_prep' + + def test_fifteen_stages_inventory_source_before_review(): """库存源解析必须排在人工复核与建单之前(跨面共用同一有序元组)。""" stages = list(SHIPPING_PROCESSING_STAGES) diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 74557b8f..a5fcf36b 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2577,7 +2577,12 @@ Task 工作台 = 非主界面,仅保留备用深链 - **对话工作台(`chat`)**:主上传入口、解析摘要 / Candidate / Task 进度 / Process Gate 业务卡片;会话右侧「**本次处理中**」为会话级状态投影(Run / Candidate / Task / Process Gate,支持多对象与当前 Task 聚焦)。轻量操作(客户确认、重试、人工接管、刷新)**只调用正式 Workspace API**,禁止前端本地改业务状态或推导进度百分比。纯 `open_existing` 显示「发现重复文件,已关联已有任务」。文档投影含 `duplicate_resolution` / `existing_task_no` / `opened_existing_documents`。**不**挂载顶部批次进度条与右侧批次履约抽屉作为主路径。 - **人工复核工作台(`review`)**:复杂字段/明细/证据/冲突/LLM/库存异常的深度写入口;确认建单后优先**返回原对话并聚焦 Task**,走与直通相同的后台 `auto_progress` 链。资格摘要与对话卡片数据同源 Candidate Qualification。 - **Task 备用深链(`task_deep_link`)**:路由 `/workspace/shipping-notice/tasks/:taskNo` **不进入主导航**;仅用于对话删除后恢复、外部深链、管理员排查、运维诊断。履约写操作仍以后端状态机与正式 API 为准;正式 Task 按钮只消费 `ui_state.actions.primary/secondary`,批次 / 生命周期按钮只消费同一投影的 `primary_action/secondary_actions`。 -- **我的待办**:跨会话聚合待复核 / 异常 / 待人工上传;徽标与列表同源后端 `todo_category`;打开后深链进入复核或对话聚焦,**不以 Task 工作台为默认主区**。 +- **我的待办**:跨会话聚合人工事项与系统处理中任务;徽标与列表同源后端 `todo_category`;打开后深链进入复核或对话聚焦,**不以 Task 工作台为默认主区**。 + - **待处理** = `review` / `exception` / `manual_upload` / `intake_parse`(等人确认、异常、待人工上传、孤儿解析)。 + - **处理中** = `in_progress`,且只对应 F2 `user_status=running` / 批次 `user_group=processing`(系统正在自动跑)。订单复核等人确认不得进入此桶。 + - **已完成** = `done`。 + - 无 Gate 时 fail-closed 进待处理,禁止默认 `in_progress`。 + - **轮询**:有 running 时复用 `resolveProcessingPollIntervalMs`(可见 2s→5s→10s,隐藏 30s);仅人工等待约 30s 或页面重新可见/回焦再拉;空列表停止。静默刷新不得把列表打成「正在加载…」。批次进度中心仍仅在 `summary.processing > 0` 时轮询。 - 服务端状态机(含 `checkpoint_kind`)、审计与乐观锁是唯一裁决;Chat Turn 履约写路径标记废弃,逐步拆除。 - 对话侧所有写操作必须带 `request_id` / 幂等键并写入审计;自动推进节点顺序与重试上限由后端固定,前端只展示投影。 - **阶段 5(Process Gate 对话化)**:`ProcessGateRecoveryCard` 复用于侧栏 Item、详情抽屉与复核入口;恢复动作走 Workspace API;Gate 失败不自动重试,需用户显式触发恢复;对话恢复额外写 `chat_process_gate_*`。 @@ -2642,6 +2647,8 @@ ui_state.actions -> 前端唯一可渲染的履约动作投影 6. **重试、扩批(Run 内 selection_batch)、恢复、重新识别(同谱系)不产生新的用户可见任务**;仅当用户再次发送且无法追加时,才创建新的用户可见任务。 7. 内容全集 Hash 复用(`reused=true`)仍有效;部分重叠不合并。复用结果须投影到既有用户可见任务,并写审计。 +**对话附件展示与写入契约(2026-09-14)**:用户消息气泡中的附件数量为本次发送写入 `ChatLog.payload.user_attachments` 的**顶层提交快照**条数(一次提交的 EML/PDF 等各对应一条);下方货代进度卡的文件计数可包含 EML 展开后的 Workflow Unit,二者口径 intentionally 不同。`user_attachments` 上限 **200**,前后端均禁止静默 `[:20]` 截断;超限须显式失败(后端 `CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED`,前端发送前 warning 拦截)。进度卡出现后,对应用户气泡附件区切换为 `summaryOnly`(仅摘要、不可展开),避免与进度卡重复展示。 + #### 会话级 processing 投影(阶段 1 返回) ```text diff --git a/docs/superpowers/specs/2026-09-14-shipping-processing-todo-polling-design.md b/docs/superpowers/specs/2026-09-14-shipping-processing-todo-polling-design.md new file mode 100644 index 00000000..32197df1 --- /dev/null +++ b/docs/superpowers/specs/2026-09-14-shipping-processing-todo-polling-design.md @@ -0,0 +1,227 @@ +# 2026-09-14 待办「处理中」口径对齐与轮询收敛 + +> 日期:2026-09-14 +> 状态:已确认(brainstorming) +> 范围:货代发货通知 · 我的待办桶分类 + 待办/批次轮询 +> 相关实现:`query_service.py`(`todo_category` SQL/COUNT)、`process_gate_contract.py`(F2 `user_status`)、`shipping_processing_projection.py`(`user_group` / `processing_files`)、`ShippingTaskCenterPage.vue`、`shippingTaskCenterPolling.ts`、`useShippingNoticeWorkflow.ts` +> 权威手册落地后同步:[`docs/features/shipping-notice/technical.md`](../../features/shipping-notice/technical.md) §1.6「我的待办」 + +--- + +## 1. 问题 + +测试环境同一批订单复核任务: + +- **我的待办**「处理中 (9)」,阶段卡全在订单复核,列表每 2s 闪「正在加载…」 +- **批次进度中心**「处理中 0」「需处理 49」;五阶段仍可能写「1 份处理中」;顶栏甚至显示「已完成」 + +根因不是数字延迟,是两套「处理中」加上待办轮询过猛: + +1. 待办桶 `processing` = SQL `todo_category=in_progress`。CASE 大量 `else → in_progress`,无 Gate 或订单复核等人确认也会进处理中。 +2. 批次「处理中」= `user_group=processing` / `processing_files`,只计系统正在自动跑。等人确认是 `waiting_human` → 「需处理」。 +3. 待办页 `bucket === 'processing'` **无条件 2s 轮询**;`refreshAll({ silent: true })` 未真正静默,`loadTodos` 仍置 `loading`,列表被换成加载占位。 +4. `isShippingTodoListItemInProgress` 把 `waiting_review` / `needs_action` / `blocked` 算作可继续轮询;详情甚至「有 stage 且不是 upload_complete 就算进行中」。 + +手册已写:**我的待办聚合待复核 / 异常 / 待人工上传**;批次才是会话级系统进度。实现与手册分叉。 + +--- + +## 2. 目标与非目标 + +### 目标 + +1. **一词一义**:两边「处理中」都只表示系统正在自动跑(F2 `user_status=running` / `user_group=processing`)。 +2. **等人确认进待处理**:订单复核、异常、待人工上传不得出现在待办「处理中」桶。 +3. **轮询跟系统态走**:有 running → 分层间隔(复用批次函数);仅人工等待 → 约 30s 或回焦/可见再拉;空/已完成 → 停。 +4. **静默刷新不闪加载**:自动轮询禁止把列表打成「正在加载…」。 +5. **批次顶卡与阶段条同源**:同一 `user_group`,禁止「处理中 0」与「1 份处理中」并存。 + +### 非目标 + +- 不上 SSE / WebSocket。 +- 不新建统一状态服务,不逐条 hydrate shipping-processing 做待办 COUNT。 +- 不改 Gate 写路径、STP、自动建单。 +- 不把待办数字与批次数字做成跨会话相等(范围不同:用户全部 vs 本会话文件)。 +- 不改桶名(仍「待处理 / 处理中 / 已完成」)。 + +--- + +## 3. 已定决策 + +| # | 决策 | 选择 | +| --- | --- | --- | +| D1 | 「处理中」语义 | **A**:只表示系统正在自动跑 | +| D2 | 无系统处理时怎么刷 | **B**:running 分层轮询;人工等待 30s 或 visibility/focus;silent 真静默 | +| D3 | 待办桶权威 | **B**:与批次共用已有投影主态;`todo_category=in_progress` 只翻译 `running` | +| D4 | 实现路线 | **方案 2**:收口 SQL CASE + 待办轮询纯函数;不新服务 | +| D5 | 无 Gate | fail-closed 进 pending(复核位 `review`,否则 `exception`),**禁止**默认 `in_progress` | + +--- + +## 4. 架构 + +故意双层保留(状态契约 Phase B),禁止把阶段词当成用户主态: + +```text +Gate / Execution(库内) + → user_status(F2 六值,已有 GATE_STATUS_TO_USER_STATUS) + → todo_category(待办桶翻译,不是第二套状态机) + → COUNT / 列表桶 + → 前端 running 谓词 → 是否轮询、哪一档间隔 +``` + +| 层 | 规范词 | 用途 | +| --- | --- | --- | +| Wire `user_status` | `running \| waiting_human \| retryable \| failed \| completed \| cancelled` | 唯一用户主态 | +| 批次 `user_group` | `processing` 当且仅当 running | 批次「处理中」卡 / `processing_files` | +| 待办 `todo_category` | 见下表 | 待办三桶 + pending 细类 | +| `lifecycle_stage` / processing stage | `order_review` 等 | 阶段位置,**不得**单独决定「处理中」 | + +`todo_category` 翻译(唯一出口:已有 `derive_todo_category` + SQL 必须同序): + +| `user_status` | `todo_category` | 待办桶 | +| --- | --- | --- | +| `running` | `in_progress` | 处理中 | +| `waiting_human` + 复核位 | `review` | 待处理 | +| `waiting_human` + 人工上传 handoff | `manual_upload` | 待处理 | +| `waiting_human` 其余 / `retryable` / `failed` | `exception` | 待处理 | +| `completed` / `cancelled` | `done` | 已完成 | + +建单前开放 Review Case、解析中孤儿 Intake 仍走现有 pending 分支(`review` / `intake_parse`),不进处理中桶。Intake `created/queued/parsing` 算系统在跑,只影响**轮询**,不影响进处理中桶。 + +--- + +## 5. 组件与落点 + +四个现有单元,各管一件事。 + +### 5.1 待办分类 SQL / COUNT + +文件:`backend/app/services/shipping_notice/query_service.py` + +- `_gate_todo_category_sql_whens`、`_task_todo_category_sql_expr`、`_order_task_todo_category_sql_expr` 与 `GATE_STATUS_TO_USER_STATUS` → `derive_todo_category` 同序。 +- **删除** `else_=literal("in_progress")`。无 Gate / 无法判定 → pending 细类(D5)。 +- Gate `blocked_manual`(及映射为 `waiting_human`)不得产出 `in_progress`。 +- `retryable` / `failed` → `exception`。 +- 仅 Gate 推进中(pending/queued/running/passed/waiting_external/invalidated 等映射为 `running`)→ `in_progress`。 +- `count_my_todos`:Notice 分支与「无 Notice 的 OT」分支必须互斥。`_visible_order_tasks_query_for_todos` 已排除已有 Notice 的 OT;加回归锁死同一 `task_no` 不得双计。 +- ORM `task_todo_category` 已走 Gate,作为 SQL 对照;列表/徽标 COUNT 不得与 ORM 分叉。 + +不改 `list_my_todos` 分页形态(UNION + 当前页 hydrate)。 + +### 5.2 列表项「是否系统在跑」 + +文件:`frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.ts` + +`isShippingTodoListItemInProgress` **只认系统 running**: + +- Intake:`intake_parse_status ∈ {created, queued, parsing}`(保持) +- 其余:`shipping_processing_status ∈ {queued, processing, automating}`,或 `user_status === 'running'` +- **移出** `waiting_review` / `needs_action` / `blocked` +- 等人编辑的 `review_case` / `waiting_human` → false + +详情 `isDetailInProgress` 同样只认 running,禁止「有 stage 且不是 upload_complete」当进行中。 + +### 5.3 待办页轮询调度 + +文件:`ShippingTaskCenterPage.vue` + +- 删除 `bucket === 'processing' → 永远 poll`。 +- `shouldAutoRefresh`: + - 当前页或详情至少 1 条 running → 高频分层 + - 仅人工等待 → 30s,或 `visibilitychange=visible` / window `focus` 拉一次 + - 空列表且无进行中详情 → 停 +- 间隔:**直接调用**已导出的 `resolveProcessingPollIntervalMs`(2s→5s→10s;隐藏 30s)。待办禁止自写第二套毫秒数。 + - 注意:该函数在 `hasProcessing=false` 时返回 `null`。人工等待的 30s **由页面包装**,不修改函数对批次中心的语义。 +- `refreshAll({ silent })` 必须传到 `loadTodos` / `loadDetail`:silent 时禁止置 `loading` / `detailLoading`。 +- `runs` 面:必须 silent;是否高频只看 5.2 同一 running 谓词,禁止「只要停在 runs 就 2s」。验收主路径仍是 todos 面。 + +### 5.4 批次侧 + +文件:`useShippingNoticeWorkflow.ts`(轮询谓词已存在)、`shipping_processing_projection.py`(阶段汇总) + +- `shouldContinueProcessingPolling` 保持「`summary.processing > 0` 才继续」;`summary.processing` 与 `processing_files` 必须同时为 0 当全部 `waiting_human`/`failed`。 +- `_batch_lifecycle_nodes` 已按 `user_group` 计数。补回归:`user_group=waiting_human` 时顶卡 `processing_files=0` **且**对应阶段 `summary.processing=0`。 +- 不改批次 UI 结构。顶栏「已完成」若与 `needs_action>0` 矛盾,随同一 `user_group` 投影修正,不单开 UI 项目。 + +--- + +## 6. 数据流 + +**待办读路径** + +1. `count_my_todos` → `{pending, processing, done}`;`processing` 只含 `in_progress`。 +2. `list_my_todos(bucket)` 只返回该桶。订单复核 Case / `waiting_human` OT 必须在 `pending`。 +3. 前端不根据 `lifecycle_stage` 重判桶。 +4. 静默轮询:保留旧列表直到响应返回再替换;失败不清空。 + +**批次读路径** +不变。待办总数与批次文件数可以不等(跨会话 vs 本会话)。**同一 `task_no`** 不得一边 `running`/`in_progress`、一边 `waiting_human`。 + +**写路径** +不改。用户确认/重试成功后沿用现有立刻 `refreshAll()` / `refreshTrigger`。 + +**待办轮询状态机** + +| 当前页事实 | 间隔 | +| --- | --- | +| ≥1 running | `resolveProcessingPollIntervalMs`(可见 2s→5s→10s;隐藏 30s) | +| 仅人工等待 | 30s,或可见/focus 时拉一次 | +| 空 / 全 done | 停 | + +离开页面或切到无 running 的桶:清 timer。 + +--- + +## 7. 错误处理 + +- 单次轮询失败:保留旧列表,不闪加载,不每次 toast。`failureCount` 走已有退避(10s→20s→30s 封顶)。 +- 用户点「刷新」:清零退避并立即拉(可显示 loading)。 +- 请求重叠:保持 `pollInFlight`;切桶/卸载丢弃过期响应(generation)。 +- 无 Gate:SQL fail-closed 进 pending,避免空转高频轮询。 +- 批次顶卡 vs 阶段条不一致:视为投影 bug,测试锁死,前端不对冲数字。 +- 不新增 `error.code`、不改 JSON envelope。 + +--- + +## 8. 测试 + +### 后端 + +- Gate `blocked_manual` + 复核 gate(`order_field_extraction` 等)→ SQL 与 ORM 均为 `review`;`list_my_todos(processing)` 不含;`pending` 含。 +- `waiting_human` 非复核位 → `exception` 或 `manual_upload`,不得 `in_progress`。 +- Gate 映射 `running` → `in_progress`,只出现在 processing 桶。 +- 无 Gate → pending,不进 processing。 +- 同一 OT 有 Notice 只计 Notice 分支;`count_my_todos.processing` 不双计。 +- 批次:`user_group=waiting_human` → `processing_files=0` 且对应阶段 `summary.processing=0`。 + +扩 `tests/test_shipping_notice_query_service.py`、`tests/test_shipping_processing_projection_stage4.py`(已有 `test_batch_stage_summary_uses_the_same_user_group_as_file_counts`,补「顶卡+阶段同时为 0」)。 + +### 前端 + +- `isShippingTodoListItemInProgress`:人工 review_case / `waiting_review` / `needs_action` → false;queued/processing/automating 或 `user_status=running` → true。 +- 停在 processing 桶但列表全人工 → 不调度 2s。 +- 有 running → 间隔等于 `resolveProcessingPollIntervalMs`。 +- `refreshAll({ silent: true })` 期间 `loading === false`。 +- 批次:`summary.processing=0` → `shouldContinueProcessingPolling === false`(保留现有用例)。 + +--- + +## 9. 成功标准 + +对应测试环境那两张图: + +1. 订单复核等人确认:待办在「待处理」;批次「处理中=0、需处理>0」。同一任务两边不得一个 running、一个 waiting_human。 +2. 仅当系统在跑时,待办「处理中」才有数;语义与批次「处理中」相同。 +3. 待办停在处理中桶不再无条件 2s 闪「正在加载…」;人工等待最多约 30s 或回焦再拉。 +4. 批次顶卡「处理中」与五阶段「N 份处理中」同源;有需处理时不得把批次总状态显示成「已完成」。 +5. 无 SSE、无新状态服务、无新 API envelope。 + +--- + +## 10. 文档 + +实现同一变更集更新 `docs/features/shipping-notice/technical.md`: + +- §1.6「我的待办」:三桶语义(待处理=人工事项,处理中=`running`,已完成=终态)。 +- 轮询:待办与批次共用 `resolveProcessingPollIntervalMs`;人工等待低频;silent 刷新契约。 diff --git a/frontend/nginx.conf b/frontend/nginx.conf index b0442e05..f061a803 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -15,8 +15,22 @@ server { } # Vite 构建产物(/assets/ 下带 hash 文件):内容寻址,文件名一变即换新缓存,可放心长期 immutable 缓存。 + # alpine nginx 默认 mime.types 无 .mjs;缺省会落到 default_type application/octet-stream。 + # 同级 include + types 合并映射。前端另用 Blob Worker 绕过错误 MIME 的 immutable 磁盘缓存。 location /assets/ { root /usr/share/nginx/html; + include /etc/nginx/mime.types; + types { + text/javascript mjs; + } + add_header Cache-Control "public, max-age=31536000, immutable"; + } + + # 显式兜底:任意 .mjs 都按 JS 模块输出(RFC 9239: text/javascript)。 + location ~* \.mjs$ { + root /usr/share/nginx/html; + default_type text/javascript; + types { } add_header Cache-Control "public, max-age=31536000, immutable"; } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index 55efb327..bf4faa94 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -613,6 +613,14 @@ const coordinateCanvasActions = computed(() => ({ page: (nextPageNo) => { void selectPage(nextPageNo); }, draw: (kind) => startDrawing(kind), })); +/** 页图 token 失效时自动重签;客户端渲染失败(如 worker MIME)不得超过预算。 */ +let previewReauthInFlight = false; +let previewAutoReauthCount = 0; +const PREVIEW_AUTO_REAUTH_LIMIT = 2; +const resetPreviewAutoReauthBudget = () => { + previewAutoReauthCount = 0; +}; + /** * 共享视觉画布模型:模板差异在此处一次性被 adapter 吸收,之后所有画布事件和 props * 均只消费 visualCanvas。datasets path、集合与拆分规则不属于视觉模型,继续留在 XFA @@ -659,7 +667,10 @@ const visualCanvas = computed(() => { warningVisible: adapterWarningVisible || canvasUnavailable.value, warningText: adapterWarningText || (canvasUnavailable.value ? t('admin.shippingOrderProfiles.workbench.canvasUnavailable') : null), - retryCanvas: () => { void loadPages(); }, + retryCanvas: () => { + resetPreviewAutoReauthBudget(); + void loadPages(); + }, reportCanvasLoadFailed: () => { canvasUnavailable.value = true; }, applyAutomarkCandidates: () => false, canRender: true, @@ -814,13 +825,13 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly); const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible); const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || ''); const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas(); -/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */ -let previewReauthInFlight = false; +/** 页图/原 PDF 令牌 HTTP 失效时自动重签;客户端渲染失败不得走此路径(见 DocumentCanvas)。 */ const onDeskCanvasLoadFailed = async () => { - if (previewReauthInFlight) { + if (previewReauthInFlight || previewAutoReauthCount >= PREVIEW_AUTO_REAUTH_LIMIT) { visualCanvas.value.reportCanvasLoadFailed(); return; } + previewAutoReauthCount += 1; previewReauthInFlight = true; try { await loadPages(); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts index 411d498a..becbd3fd 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts @@ -14,11 +14,12 @@ const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({ renderMock: vi.fn(), })); -vi.mock('pdfjs-dist', () => ({ - GlobalWorkerOptions: {}, - getDocument: (...args: unknown[]) => getDocumentMock(...args), +vi.mock('@/shared/utils/pdfjs', () => ({ + loadPdfJs: async () => ({ + GlobalWorkerOptions: {}, + getDocument: (...args: unknown[]) => getDocumentMock(...args), + }), })); -vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' })); vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) })); describe('OrderProfileDocumentCanvas PDF preview', () => { @@ -274,4 +275,89 @@ describe('OrderProfileDocumentCanvas PDF preview', () => { // 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。 expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240); }); + + it('keeps pdfCanvas mounted under pdfPreview error overlay and does not reauth on render failure', async () => { + getDocumentMock.mockReturnValue({ + promise: Promise.resolve({ + numPages: 1, + getPage: vi.fn(async () => { + throw new Error('PDF canvas is unavailable'); + }), + }), + }); + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'single-use-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { + plugins: [createI18n({ + legacy: false, + locale: 'zh-CN', + messages: { + 'zh-CN': { + admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } }, + }, + }, + })], + }, + }); + await flushPromises(); + await flushPromises(); + + // 关键断言:原 PDF 路径失败不得卸掉 canvas,否则重试/reauth 后 render 仍读到 null。 + expect(wrapper.find('canvas.pdf-page').exists()).toBe(true); + expect(wrapper.find('.canvas-error-overlay').exists()).toBe(true); + expect(wrapper.emitted('loadFailed')).toBeUndefined(); + }); + + it('reuses in-memory PDF bytes for the same single-use preview token', async () => { + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'single-use-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] }, + }); + await flushPromises(); + await flushPromises(); + expect(fetch).toHaveBeenCalledTimes(1); + + // 改 grant 依赖重入 watch,但 pdfPreview token 不变;必须走内存缓存,否则 getdel 二次 GET=404。 + await wrapper.setProps({ + grant: { page_no: 1, preview_token: 'png-ignored' }, + pdfPreview: { preview_token: 'single-use-token' }, + }); + await flushPromises(); + await flushPromises(); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it('emits loadFailed only for preview-token HTTP failures', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 }))); + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'dead-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { + plugins: [createI18n({ + legacy: false, + locale: 'zh-CN', + messages: { + 'zh-CN': { + admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } }, + }, + }, + })], + }, + }); + await flushPromises(); + await flushPromises(); + expect(wrapper.emitted('loadFailed')).toHaveLength(1); + expect(wrapper.find('canvas.pdf-page').exists()).toBe(true); + }); }); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue index df98dbcd..9ab029c1 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue @@ -4,6 +4,9 @@ 依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。 逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动; PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token; + 原 PDF(pdf-preview)令牌亦为 Redis getdel 单次消费:同 token 字节必须缓存,且仅 HTTP 401/403/404 + 才 emit loadFailed 触发父级 reauth;画布/渲染失败不得重签,否则会空转授权风暴; + pdfPreview 错误态用 overlay,禁止 v-if 卸掉 pdfCanvas(否则 renderPdfPage 必失败); 未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除; 选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效); 拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走; @@ -16,28 +19,11 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next'; import { getAuthHeaders } from '@/shared/utils/auth'; +import { loadPdfJs } from '@/shared/utils/pdfjs'; import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types'; import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils'; import type { PDFDocumentProxy } from 'pdfjs-dist'; -type PdfJsModule = typeof import('pdfjs-dist'); -let pdfjsLoader: Promise | null = null; - -/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */ -async function loadPdfJs(): Promise { - if (!pdfjsLoader) { - pdfjsLoader = (async () => { - const [pdfjs, workerMod] = await Promise.all([ - import('pdfjs-dist'), - import('pdfjs-dist/build/pdf.worker.min.mjs?url'), - ]); - pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default; - return pdfjs; - })(); - } - return pdfjsLoader; -} - const props = defineProps<{ profileId: number | null; grant?: OrderProfilePreviewPageGrant | null; @@ -107,6 +93,12 @@ const viewport = ref(null); const zoom = ref(1); /** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */ const pageImageCache = new Map(); +/** + * 原 PDF 字节缓存:pdf-preview 令牌是 Redis getdel 单次消费。 + * 同 token 的并发/重入 loadPage 若再次 GET 会 404,并误触发父级 reauth 风暴。 + */ +let cachedPdfBytes: Uint8Array | null = null; +let cachedPdfToken: string | null = null; let loadGeneration = 0; let cachedProfileId: number | null = null; const zoomPercent = computed(() => Math.round(zoom.value * 100)); @@ -123,17 +115,34 @@ const emptyStateText = computed(() => ( props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf') )); +/** + * 等待 pdfCanvas 进入 DOM。 + * 错误态曾用 v-if 卸掉 canvas;清错后仅一次 nextTick 仍可能读到 null, + * 进而抛 "PDF canvas is unavailable",被空 catch 吃掉且 0 console error。 + */ +const ensurePdfCanvas = async (): Promise<{ canvas: HTMLCanvasElement; context: CanvasRenderingContext2D }> => { + for (let attempt = 0; attempt < 10; attempt += 1) { + await nextTick(); + const el = pdfCanvas.value; + const context = el?.getContext('2d'); + if (el && context) return { canvas: el, context }; + await new Promise((resolve) => { + if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve()); + else window.setTimeout(() => resolve(), 16); + }); + } + throw new Error('PDF canvas is unavailable'); +}; + /** * 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。 * 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。 */ const renderPdfPage = async (pdf: PDFDocumentProxy) => { - await nextTick(); - const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages); + const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages || 1); + if (pdf.numPages < 1) throw new Error('PDF has no pages'); const page = await pdf.getPage(targetPage); - const canvas = pdfCanvas.value; - const context = canvas?.getContext('2d'); - if (!canvas || !context) throw new Error('PDF canvas is unavailable'); + const { canvas, context } = await ensurePdfCanvas(); const viewport = page.getViewport({ scale: zoom.value }); pdfPageSize.value = { width: viewport.width, height: viewport.height }; canvas.width = Math.ceil(viewport.width); @@ -142,6 +151,12 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => { pdfRendered.value = true; }; +/** 令牌失效类 HTTP 才值得父级 reauth;画布未挂载/渲染失败重签只会空转。 */ +const isPreviewTokenHttpError = (error: unknown): boolean => { + if (!(error instanceof Error)) return false; + return /^HTTP (401|403|404)\b/.test(error.message); +}; + /** * 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。 */ @@ -149,6 +164,8 @@ const clearPageImageCache = () => { for (const url of pageImageCache.values()) URL.revokeObjectURL(url); pageImageCache.clear(); inflightPageLoads.clear(); + cachedPdfBytes = null; + cachedPdfToken = null; }; /** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */ @@ -206,13 +223,21 @@ const loadPage = async () => { || `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`; if (props.pdfPreview) { imageUrl.value = ''; - const response = await fetch( - `${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`, - { headers: getAuthHeaders(), cache: 'no-store' }, - ); - if (!response.ok) throw new Error(`HTTP ${response.status}`); + const token = props.pdfPreview.preview_token; + let bytes: Uint8Array; + if (cachedPdfToken === token && cachedPdfBytes) { + bytes = cachedPdfBytes; + } else { + const response = await fetch( + `${previewPath}?preview_token=${encodeURIComponent(token)}`, + { headers: getAuthHeaders(), cache: 'no-store' }, + ); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + bytes = new Uint8Array(await response.arrayBuffer()); + cachedPdfBytes = bytes; + cachedPdfToken = token; + } const pdfjs = await loadPdfJs(); - const bytes = new Uint8Array(await response.arrayBuffer()); pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise; if (generation !== loadGeneration) return; emit('pageCount', pdfDocument.numPages); @@ -224,7 +249,7 @@ const loadPage = async () => { const blobUrl = await fetchPageImage(previewPath, grant); if (generation !== loadGeneration) return; imageUrl.value = blobUrl; - } catch { + } catch (error) { if (generation !== loadGeneration) return; const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null; if (fallback) { @@ -234,7 +259,10 @@ const loadPage = async () => { } imageUrl.value = ''; internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable'); - emit('loadFailed'); + // 仅令牌 HTTP 失效才通知父级重签;画布未挂载/PDF.js 渲染失败重签只会烧掉单次 token。 + if (isPreviewTokenHttpError(error) || (props.grant && error instanceof Error && /^HTTP \d+/.test(error.message))) { + emit('loadFailed'); + } } finally { if (generation === loadGeneration) loading.value = false; } @@ -442,10 +470,20 @@ defineExpose({ watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true }); watch(() => props.pageNo, async (value) => { pageInput.value = value; - if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument); + if (!(props.pdfPreview && pdfDocument)) return; + try { + await renderPdfPage(pdfDocument); + } catch { + /* 翻页时画布可能短暂卸载;下一次 load/retry 会恢复 */ + } }); watch(zoom, async () => { - if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument); + if (!(props.pdfPreview && pdfDocument)) return; + try { + await renderPdfPage(pdfDocument); + } catch { + /* 缩放同翻页:避免未捕获 Promise 干扰控制台 */ + } }); onBeforeUnmount(() => { endMove(); @@ -494,7 +532,8 @@ onBeforeUnmount(() => {
{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}
- + @@ -635,7 +680,20 @@ onBeforeUnmount(() => { cursor: pointer; } .canvas-retry:hover { border-color: #60a5fa; background: #26364f; } -.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; } +.canvas-work-area { position: relative; display: flex; min-height: 0; flex: 1; gap: .6rem; } +.canvas-error-overlay { + position: absolute; + inset: 0; + z-index: 8; + display: grid; + place-content: center; + gap: .75rem; + background: rgb(15 23 42 / .82); + color: #fecaca; + font-size: .875rem; + text-align: center; + padding: 1rem; +} .canvas-work-area.readonly { gap: 0; } .canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; } .canvas-viewport.panning { cursor: grab; } diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index c9f44a90..a1e4384f 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -4,6 +4,7 @@ * 依赖:lucide 图标、附件完整性判断工具。 * 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。 * 同时支持采购合同双文件输入控件:底部左区放附件/合同等工具,右区语音与发送并排;采购合同审查用专用上传按钮,不展示通用回形针附件入口。 + * 货代订单抽取提交中(isOrderExtractionSubmitting)时发送钮展示 Loader,免责声明区提示提交中。 */ diff --git a/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts index 550e3ed2..8c19f144 100644 --- a/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts +++ b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts @@ -1,11 +1,15 @@ /** * features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts * 用途:锁定任务中心自动轮询的边界,避免人工待处理任务被误判为持续处理中。 - * 依赖:isShippingTodoListItemInProgress。 - * 逻辑:只有后端明确的进行中状态继续轮询;复核草稿、失败和完成任务停止轮询。 + * 依赖:isShippingTodoListItemInProgress、resolveTodoCenterPollIntervalMs。 + * 逻辑:只有系统 running 继续高频轮询;复核草稿、失败和完成停止;人工等待 30s。 */ import { describe, expect, it } from 'vitest'; -import { isShippingTodoListItemInProgress } from './shippingTaskCenterPolling'; +import { + HUMAN_WAIT_POLL_MS, + isShippingTodoListItemInProgress, + resolveTodoCenterPollIntervalMs, +} from './shippingTaskCenterPolling'; describe('isShippingTodoListItemInProgress', () => { it('does not poll a review case that is waiting for human editing', () => { @@ -17,6 +21,32 @@ describe('isShippingTodoListItemInProgress', () => { } as never)).toBe(false); }); + it('does not poll waiting_review or needs_action as system running', () => { + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-1', + shipping_processing_status: 'waiting_review', + } as never)).toBe(false); + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-2', + shipping_processing_status: 'needs_action', + } as never)).toBe(false); + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-3', + shipping_processing_status: 'blocked', + } as never)).toBe(false); + }); + + it('does not treat a non-complete lifecycle stage as running', () => { + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-STAGE', + ui_state: { stage: { code: 'order_review', label: '订单复核', index: 1, total: 5 } }, + } as never)).toBe(false); + }); + it('continues polling a review case with an explicit processing status', () => { expect(isShippingTodoListItemInProgress({ item_kind: 'review_case', @@ -26,4 +56,47 @@ describe('isShippingTodoListItemInProgress', () => { review_run_no: 'RUN-1', } as never)).toBe(true); }); + + it('continues polling queued automating or running execution', () => { + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-Q', + shipping_processing_status: 'queued', + } as never)).toBe(true); + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-A', + shipping_processing_status: 'automating', + } as never)).toBe(true); + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-E', + ui_state: { process_gate: { status: 'active' } }, + } as never)).toBe(true); + expect(isShippingTodoListItemInProgress({ + item_kind: 'task', + task_no: 'OT-U', + user_status: 'running', + } as never)).toBe(true); + }); +}); + +describe('resolveTodoCenterPollIntervalMs', () => { + it('reuses batch intervals while system work is running', () => { + expect(resolveTodoCenterPollIntervalMs({ + hasRunning: true, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0, + })).toBe(2000); + expect(resolveTodoCenterPollIntervalMs({ + hasRunning: true, hasHumanWait: false, elapsedMs: 15000, visibility: 'visible', failureCount: 0, + })).toBe(5000); + }); + + it('uses 30s for human wait and stops when idle', () => { + expect(resolveTodoCenterPollIntervalMs({ + hasRunning: false, hasHumanWait: true, elapsedMs: 0, visibility: 'visible', failureCount: 0, + })).toBe(HUMAN_WAIT_POLL_MS); + expect(resolveTodoCenterPollIntervalMs({ + hasRunning: false, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0, + })).toBeNull(); + }); }); diff --git a/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.ts b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.ts index f15b9142..a92e1a3b 100644 --- a/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.ts +++ b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterPolling.ts @@ -1,18 +1,20 @@ /** * features/workspace/shipping-task-center/shippingTaskCenterPolling.ts - * 用途:任务中心列表项是否仍需前台轮询(纯函数,供页面与单测共用)。 - * 依赖:ShippingTaskSummary、shippingProcessingFulfillment 状态集合。 - * 逻辑:ShippingTaskCenterPage 用本函数决定 poll;Intake created/queued/parsing 必须轮询, - * parse_failed 停止;review_case 持续轮询;OT/Notice 走统一投影状态。 + * 用途:任务中心列表项是否系统在跑、以及待办页轮询间隔(纯函数)。 + * 依赖:ShippingTaskSummary、useShippingNoticeWorkflow 间隔函数。 + * 逻辑:ShippingTaskCenterPage 用本模块决定 poll;仅 queued/processing/automating/running + * 或 Execution active/waiting_external 算系统在跑;人工等待走 30s;间隔复用批次函数。 */ import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api'; import { - IN_PROGRESS_PROCESSING_STATUSES, - TERMINAL_PROCESSING_STATUSES, -} from '@/features/chat/shipping/shippingProcessingFulfillment'; + resolveProcessingPollBackoffMs, + resolveProcessingPollIntervalMs, + type ProcessingPollContext, +} from '@/features/chat/shipping/useShippingNoticeWorkflow'; +import { TERMINAL_PROCESSING_STATUSES } from '@/features/chat/shipping/shippingProcessingFulfillment'; -/** 历史轮询状态集合;正常任务中心优先消费统一 ui_state。 */ +/** 历史轮询状态集合;正常任务中心不再用它判定系统处理中。 */ export const IN_PROGRESS_PROCESS = new Set([ 'parsing', 'parsed', @@ -26,41 +28,78 @@ export const IN_PROGRESS_PROCESS = new Set([ 'pending_void', ]); -/** Intake 仍在解析、必须轮询的状态。 */ +/** Intake 仍在解析、必须高频轮询的状态。 */ export const INTAKE_POLLING_PARSE_STATUSES = new Set([ 'created', 'queued', 'parsing', ]); +/** 系统正在自动跑的统一 processing status;不含人工等待。 */ +export const SYSTEM_RUNNING_PROCESSING_STATUSES = new Set([ + 'queued', + 'processing', + 'automating', + 'running', +]); + +/** Execution.status 中表示系统仍在推进。 */ +const RUNNING_EXECUTION_STATUSES = new Set([ + 'active', + 'waiting_external', +]); + +/** 仅人工等待时的待办轮询间隔,与批次中心后台档一致。 */ +export const HUMAN_WAIT_POLL_MS = 30000; + /** - * 判断列表项是否应触发轮询刷新。 - * 核心逻辑:review_case 持续轮询;order_intake 仅 created/queued/parsing; - * 其余优先 shipping_processing_status,再按统一 ui_state.stage; - * 不复用 WorkflowItem lifecycle。 + * 判断列表项是否仍有系统在自动跑,从而需要高频轮询。 + * 核心逻辑:Intake created/queued/parsing;其余只认 running 投影 + * (shipping_processing_status / user_status / Execution active), + * 不把 waiting_review / needs_action / blocked / 阶段码当成处理中。 * @param item - 我的待办列表项 - * @returns 是否需要继续轮询 + * @returns 是否系统处理中 */ export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boolean { - if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) { - const unified = String(item.shipping_processing_status || '').trim().toLowerCase(); - if (unified) { - if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false; - return IN_PROGRESS_PROCESSING_STATUSES.has(unified); - } - return false; - } - if (item.item_kind === 'order_intake') { - const intakeStatus = String( - item.intake_parse_status || '', - ).trim().toLowerCase(); + if (item.item_kind === 'order_intake' || (item.intake_no && !item.task_no && !item.review_run_no)) { + const intakeStatus = String(item.intake_parse_status || '').trim().toLowerCase(); return INTAKE_POLLING_PARSE_STATUSES.has(intakeStatus); } const unified = String(item.shipping_processing_status || '').trim().toLowerCase(); if (unified) { if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false; - return IN_PROGRESS_PROCESSING_STATUSES.has(unified); + return SYSTEM_RUNNING_PROCESSING_STATUSES.has(unified); } - const stage = String(item.ui_state?.stage?.code || '').trim(); - return Boolean(stage) && stage !== 'upload_complete'; + const userStatus = String( + (item as { user_status?: string | null }).user_status + || (item.ui_state as { user_status?: string; status?: string } | undefined)?.user_status + || (item.ui_state as { status?: string } | undefined)?.status + || '', + ).trim().toLowerCase(); + if (userStatus === 'running') return true; + const executionStatus = String(item.ui_state?.process_gate?.status || '').trim().toLowerCase(); + return RUNNING_EXECUTION_STATUSES.has(executionStatus); +} + +/** + * 待办页轮询间隔:系统在跑复用批次函数;仅人工等待 30s;否则停。 + */ +export function resolveTodoCenterPollIntervalMs(context: { + hasRunning: boolean; + hasHumanWait: boolean; + elapsedMs: number; + visibility: ProcessingPollContext['visibility']; + failureCount: number; +}): number | null { + if (context.hasRunning) { + return resolveProcessingPollIntervalMs({ + elapsedMs: context.elapsedMs, + visibility: context.visibility, + hasProcessing: true, + failureCount: context.failureCount, + }); + } + if (!context.hasHumanWait) return null; + if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount); + return HUMAN_WAIT_POLL_MS; } diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index f051e61c..423c83cf 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -53,6 +53,7 @@ "shippingNoticeUploadOk": "Upload succeeded.", "shippingNoticeUploadFailed": "Shipping notice upload failed.", "shippingNoticeBatchSubmitting": "Shipping notice submission is in progress. Please do not repeat the action.", + "shippingNoticeSubmitting": "Submitting order files…", "shippingNoticeWaitingForParse": "Shipping notices are still uploading or parsing. Please wait before confirming batch creation.", "shippingNoticeParseFailedHint": "Some shipping notices failed to parse or have incomplete attachments. Retry or remove them before sending.", "shippingNoticeUploading": "Uploading", diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index eb3e0485..c43776c0 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -131,6 +131,7 @@ "AUTH_SSO_IDENTITY_UNSUPPORTED": "The current session is not backed by Casdoor. Log in again and retry.", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.", "AUTH_FORBIDDEN": "You do not have permission to perform this action.", + "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.", "CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.", "SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.", diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index 4693dfea..bab9068b 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -53,6 +53,7 @@ "shippingNoticeUploadOk": "อัปโหลดสำเร็จ", "shippingNoticeUploadFailed": "อัปโหลดใบแจ้งจัดส่งล้มเหลว", "shippingNoticeBatchSubmitting": "กำลังส่งใบแจ้งจัดส่ง โปรดอย่าทำซ้ำ", + "shippingNoticeSubmitting": "กำลังส่งไฟล์คำสั่งซื้อ…", "shippingNoticeWaitingForParse": "ใบแจ้งจัดส่งกำลังอัปโหลดหรือแยกข้อความ โปรดรอก่อนยืนยันสร้างชุดงาน", "shippingNoticeParseFailedHint": "มีใบแจ้งจัดส่งที่แยกข้อความไม่สำเร็จหรือไฟล์แนบไม่ครบ โปรดลองใหม่หรือลบออกก่อนส่ง", "shippingNoticeUploading": "กำลังอัปโหลด", diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index b95e197b..9c746e0a 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -131,6 +131,7 @@ "AUTH_SSO_IDENTITY_UNSUPPORTED": "เซสชันปัจจุบันไม่ได้ยืนยันผ่าน Casdoor โปรดเข้าสู่ระบบใหม่", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่", "AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้", + "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่", "CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้", "SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน", diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index a1983d58..7e7d810f 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -53,6 +53,7 @@ "shippingNoticeUploadOk": "上传成功。", "shippingNoticeUploadFailed": "发货通知上传失败。", "shippingNoticeBatchSubmitting": "发货通知正在提交,请勿重复操作。", + "shippingNoticeSubmitting": "正在提交订单文件…", "shippingNoticeWaitingForParse": "发货通知正在上传或解析,请稍后再确认建单。", "shippingNoticeParseFailedHint": "存在解析失败或不完整的发货通知附件,请先重试或移除后再发送。", "shippingNoticeUploading": "上传中", diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index 560ff83c..5209e2ec 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -131,6 +131,7 @@ "AUTH_SSO_IDENTITY_UNSUPPORTED": "当前登录不是 Casdoor 身份,请重新登录后重试。", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。", "AUTH_FORBIDDEN": "你没有权限执行该操作。", + "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。", "CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。", "SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。", diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index e7c2d3c7..deef7d52 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -53,6 +53,7 @@ "shippingNoticeUploadOk": "上傳成功。", "shippingNoticeUploadFailed": "發貨通知上傳失敗。", "shippingNoticeBatchSubmitting": "發貨通知正在提交,請勿重複操作。", + "shippingNoticeSubmitting": "正在提交訂單檔案…", "shippingNoticeWaitingForParse": "發貨通知正在上傳或解析,請稍後再確認建單。", "shippingNoticeParseFailedHint": "存在解析失敗或不完整的發貨通知附件,請先重試或移除後再發送。", "shippingNoticeUploading": "上傳中", diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index b8bd7e5f..37e65dbf 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -131,6 +131,7 @@ "AUTH_SSO_IDENTITY_UNSUPPORTED": "目前登入不是 Casdoor 身份,請重新登入後再試。", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。", "AUTH_FORBIDDEN": "你沒有權限執行此操作。", + "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。", "CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。", "SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。", diff --git a/frontend/src/shared/utils/pdfjs.ts b/frontend/src/shared/utils/pdfjs.ts new file mode 100644 index 00000000..aa14fab4 --- /dev/null +++ b/frontend/src/shared/utils/pdfjs.ts @@ -0,0 +1,46 @@ +/** + * shared/utils/pdfjs.ts + * 用途:统一加载 pdfjs-dist,并以正确 MIME 启动 module Worker。 + * 依赖:pdfjs-dist、Vite `?url` 产物。 + * 逻辑:nginx 曾把 .mjs 以 application/octet-stream + immutable 长期缓存; + * Chrome 对 module Worker 硬性校验 MIME,硬刷新也常仍命中错误缓存。 + * 因此用 cache:'reload' 拉最新字节,再以 text/javascript Blob 建 Worker, + * 通过 GlobalWorkerOptions.workerPort 交给 pdf.js 5(始终 type:'module')。 + */ +type PdfJsModule = typeof import('pdfjs-dist'); + +let pdfjsLoader: Promise | null = null; + +/** + * 动态加载 PDF.js,并保证 Worker 以 JavaScript MIME 启动。 + */ +export async function loadPdfJs(): Promise { + if (!pdfjsLoader) { + pdfjsLoader = (async () => { + const [pdfjs, workerMod] = await Promise.all([ + import('pdfjs-dist'), + import('pdfjs-dist/build/pdf.worker.min.mjs?url'), + ]); + const workerUrl = String(workerMod.default || ''); + if (!workerUrl) { + throw new Error('PDF.js worker URL is unavailable'); + } + const response = await fetch(workerUrl, { cache: 'reload' }); + if (!response.ok) { + throw new Error(`PDF worker HTTP ${response.status}`); + } + const source = await response.text(); + const blobUrl = URL.createObjectURL(new Blob([source], { type: 'text/javascript' })); + const worker = new Worker(blobUrl, { type: 'module' }); + pdfjs.GlobalWorkerOptions.workerPort = worker; + pdfjs.GlobalWorkerOptions.workerSrc = workerUrl; + return pdfjs; + })(); + } + return pdfjsLoader; +} + +/** 测试用:重置单例。 */ +export function resetPdfJsLoaderForTests(): void { + pdfjsLoader = null; +}