From d57ecc62f905bf6f0b8ce3a4634ee5a78c22083a Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 7 Oct 2026 18:28:33 +0800 Subject: [PATCH 01/32] =?UTF-8?q?fix:=20=E5=90=88=E5=90=8C=E4=BB=98?= =?UTF-8?q?=E6=AC=BE=E9=A2=84=E8=AD=A6=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.test | 4 +- .../contract_payment/parse_service.py | 83 ++++++++++++++++++- backend/tests/test_contract_payment_parse.py | 34 +++++++- 3 files changed, 115 insertions(+), 6 deletions(-) diff --git a/.env.test b/.env.test index 0b373b49..6b2d87ba 100644 --- a/.env.test +++ b/.env.test @@ -26,11 +26,13 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com AUTH_LOGIN_MODE=casdoor # 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。 +# 令牌 iss 仍是公网域名,不能改成 IP。证书恢复后把 CASDOOR_BASE_URL 改回 https://autht.well-trust.com。 AUTH_JWT_ISSUER=https://autht.well-trust.com AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks # Casdoor -CASDOOR_BASE_URL=https://autht.well-trust.com +# 临时绕开 autht.well-trust.com 过期证书。Casdoor 直连 8870,不经过 443。 +CASDOOR_BASE_URL=http://192.168.100.192:8870 # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab diff --git a/backend/app/services/contract_payment/parse_service.py b/backend/app/services/contract_payment/parse_service.py index deb1bdc7..4df59c34 100644 --- a/backend/app/services/contract_payment/parse_service.py +++ b/backend/app/services/contract_payment/parse_service.py @@ -5,6 +5,7 @@ backend/app/services/contract_payment/parse_service.py 依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。 逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。 合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。 + 增值税税率和「收到定金后 N 天」不计入付款比例。 """ from __future__ import annotations @@ -24,7 +25,12 @@ from app.services.procurement_contract.analyze import extract_text_from_bytes _DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?") _MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I) -_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S) +_STAGE_LABEL_RE = re.compile(r"预付款|定金|出货款|货款|验收款|质保款|保款|尾款") +_PERCENT_VALUE_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%") +_DEPOSIT_SCHEDULE_RE = re.compile(r"定金\s*后\s*\d+\s*(?:个)?(?:工作日|天|日)") +_SENTENCE_BREAK_RE = re.compile(r"[。;;\n]") +_TAX_PREFIX_RE = re.compile(r"(?:增值税|税率)\s*$") +_TAX_SUFFIX_RE = re.compile(r"\s*(?:的\s*)?增值税") _DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)") _WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)") _WARRANTY_PAYMENT_RE = re.compile( @@ -146,12 +152,82 @@ def unique_parse_issues(issues: list[Any] | None) -> list[str]: return result +def _is_tax_percentage(body: str, number_start: int, percent_end: int) -> bool: + """ + 判断百分号是增值税或税率,而不是付款比例。 + + 核心逻辑:数字前紧挨「增值税」或「税率」,或百分号后紧挨「增值税」,都视为税率。 + 「含13%增值税」靠百分号后面的「增值税」识别;单独的「含30%」仍可当作付款比例。 + Args: + body: 合同正文。 + number_start: 百分数数字在正文中的起始下标。 + percent_end: 百分号结束下标,不含其后的文字。 + Returns: + 该百分号是税率时返回 True。 + """ + before = body[max(0, number_start - 16):number_start] + after = body[percent_end:percent_end + 16] + return _TAX_PREFIX_RE.search(before) is not None or _TAX_SUFFIX_RE.match(after) is not None + + +def _first_payment_percentage(body: str, label_end: int) -> re.Match[str] | None: + """ + 在阶段词后的同一句、140 字内取第一个非税率百分号。 + + 核心逻辑:税率百分号跳过并继续看,避免「含13%增值税」挡住同一句里的「总价款的30%」。 + 遇到句号、分号或换行即停止,窗口长度与原先一致。 + Args: + body: 合同正文。 + label_end: 阶段词结束下标。 + Returns: + 付款比例的正则匹配;窗口内没有可用百分号时返回 None。 + """ + window_end = label_end + 140 + sentence = _SENTENCE_BREAK_RE.search(body, label_end) + if sentence and sentence.start() < window_end: + window_end = sentence.start() + cursor = label_end + while cursor < window_end: + value_match = _PERCENT_VALUE_RE.search(body, cursor, window_end) + if value_match is None: + return None + if _is_tax_percentage(body, value_match.start(1), value_match.end()): + cursor = value_match.end() + continue + return value_match + return None + + +def _matched_payment_percentages(body: str) -> list[tuple[str, str]]: + """ + 抽出每个付款阶段词对应的第一个付款比例。 + + 核心逻辑:「收到定金后 N 天」是完成日期,不作为预付款锚点。 + 其余阶段词沿用原窗口,但丢掉增值税、税率百分号。 + Args: + body: 已抽取的合同正文。 + Returns: + (阶段词, 百分数字符串) 列表,按出现顺序。未命中付款比例的阶段词不出现。 + """ + matched: list[tuple[str, str]] = [] + for label_match in _STAGE_LABEL_RE.finditer(body): + label = label_match.group(0) + if label == "定金" and _DEPOSIT_SCHEDULE_RE.match(body, label_match.start()): + continue + value_match = _first_payment_percentage(body, label_match.end()) + if value_match is None: + continue + matched.append((label, value_match.group(1))) + return matched + + def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]: """ 提取四阶段付款比例,并校验阶段完整性及比例合计。 核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复) 视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。 + 增值税税率和「收到定金后 N 天」不计入付款比例。 Args: body: 已抽取的合同正文。 Returns: @@ -159,8 +235,8 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st """ found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES} issues: list[str] = [] - for match in _PERCENT_RE.finditer(body): - label, raw = match.groups() + matched = _matched_payment_percentages(body) + for label, raw in matched: node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label] percentage = _parse_decimal(raw) if percentage is None: @@ -181,7 +257,6 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st if missing: issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}") try: - matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)] snippet = "" for label in ("质保款", "验收款", "尾款"): idx = body.find(label) diff --git a/backend/tests/test_contract_payment_parse.py b/backend/tests/test_contract_payment_parse.py index 22cb3dcd..28e9bd9d 100644 --- a/backend/tests/test_contract_payment_parse.py +++ b/backend/tests/test_contract_payment_parse.py @@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py 用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。 依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。 -逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付。 +逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付;增值税税率和「收到定金后 N 天」不计入付款比例。 """ from datetime import date, datetime @@ -443,6 +443,38 @@ def test_conflicting_shipment_percentages_report_duplicate_once(): assert not any(node["node_type"] == "shipment" for node in result["nodes"]) +def test_vat_rate_beside_deposit_schedule_is_not_prepayment_percentage(): + """关键断言:完成日期「收到定金后135天」后的含13%增值税不算预付款,结算条款的定金30%仍保留。""" + result = parse_contract_text( + "设备定作合同 收到定金后 135天 合计(人民币大写)壹佰伍拾伍万元整(含13%增值税) " + "四、结算方式及期限:甲方支付乙方定金:¥465,000.00元(总价款的30%)," + "甲方支付乙方发货款:¥930,000.00元(总价款的60%)," + "验收款(总价款的10%)¥155,000.00元。" + "设备总价款(含税):1550000.00元" + ) + + percentages = {node["node_type"]: node["percentage"] for node in result["nodes"]} + assert percentages["prepayment"] == "30" + assert percentages["shipment"] == "60" + assert percentages["acceptance"] == "10" + assert "warranty" not in percentages + assert "预付款付款比例重复,需人工确认" not in result["issues"] + assert "付款阶段比例无法识别:质保款" in result["issues"] + + +def test_tax_rate_in_same_clause_does_not_hide_payment_percentage(): + """关键断言:同一句里先写含13%增值税、再写总价款30%时,预付款取30%,不取税率。""" + result = parse_contract_text( + "采购协议 合同号:HT-2026-006;合同总价:100,000元;" + "定金(含13%增值税)为总价款的30%;出货款40%;验收款20%;质保款10%;交货期:2026年09月01日。" + ) + + assert result["status"] == "parsed" + prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment") + assert prepayment["percentage"] == "30" + assert "预付款付款比例重复,需人工确认" not in result["issues"] + + def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch): """关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。""" app.config.update( From 239d373503c65c0d055e86612ce7e8f1d516ab47 Mon Sep 17 00:00:00 2001 From: sophie Date: Thu, 8 Oct 2026 09:49:57 +0800 Subject: [PATCH 02/32] =?UTF-8?q?fix:=20=E4=BC=98=E5=8C=96=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/services/chat/turn_events.py | 26 ++++- backend/app/services/chat/turn_runtime.py | 1 + backend/app/services/integrations/dify.py | 95 ++++++++++++++++++- backend/tests/test_dify_token_usage.py | 32 +++++++ frontend/src/App.vue | 21 +++- .../src/features/chat/composables/useChat.ts | 26 +++-- .../features/chat/composables/useChatTurn.ts | 13 ++- .../chat/utils/streamErrorMessage.spec.ts | 13 ++- .../features/chat/utils/streamErrorMessage.ts | 34 ++++++- .../workspace/composables/useWorkspace.ts | 15 ++- .../workspace/composables/useWorkspaceHome.ts | 12 ++- .../composables/useWorkspaceSession.ts | 28 +++++- frontend/src/shared/utils/auth.test.ts | 19 ++++ frontend/src/shared/utils/auth.ts | 36 +++++++ 14 files changed, 333 insertions(+), 38 deletions(-) diff --git a/backend/app/services/chat/turn_events.py b/backend/app/services/chat/turn_events.py index af2394ab..8a300672 100644 --- a/backend/app/services/chat/turn_events.py +++ b/backend/app/services/chat/turn_events.py @@ -141,7 +141,21 @@ def emit_run_failed( conversation_id: str, message: str, code: str | None = None, + user_facing: bool = False, ) -> str: + """ + 发出本轮失败事件,并附带兼容用的 error 帧。 + + 核心逻辑:user_facing 为 True 时两帧都带标记,前端原样展示 message。 + + Args: + message: 失败说明。user_facing 为 True 时必须已是给用户看的句子。 + code: 业务错误码,可选。 + user_facing: 为 True 时前端不再把 message 收成通用失败提示。 + + Returns: + 连续两段 SSE 帧:run.failed 与 error。 + """ error_payload: dict[str, Any] = { "event": "run.failed", "run_id": run_id, @@ -150,10 +164,18 @@ def emit_run_failed( "message": message, "session_status": "error", } + legacy_payload: dict[str, Any] = { + "event": "error", + "message": message, + "conversation_id": conversation_id, + "session_status": "error", + } if code: error_payload["code"] = code - legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"}) - return sse_frame(error_payload) + legacy + if user_facing: + error_payload["user_facing"] = True + legacy_payload["user_facing"] = True + return sse_frame(error_payload) + sse_frame(legacy_payload) def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str: diff --git a/backend/app/services/chat/turn_runtime.py b/backend/app/services/chat/turn_runtime.py index 93775416..e76a4212 100644 --- a/backend/app/services/chat/turn_runtime.py +++ b/backend/app/services/chat/turn_runtime.py @@ -194,6 +194,7 @@ class ChatTurnRuntime: conversation_id=session.session_id, message=exc.message, code=str(getattr(exc, "code", "") or "") or None, + user_facing=True, ) except Exception as exc: current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id) diff --git a/backend/app/services/integrations/dify.py b/backend/app/services/integrations/dify.py index a9ab69b0..8dbee6e6 100644 --- a/backend/app/services/integrations/dify.py +++ b/backend/app/services/integrations/dify.py @@ -103,6 +103,9 @@ class DifyService: def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str: """ 将 Dify/Tool 技术错误转成用户可读提示。 + + 核心逻辑:优先识别知识库重排授权和知识检索失败,再按工具、上下文长度等归类。 + Args: raw_error: Dify 返回的原始错误文本。 agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。 @@ -112,6 +115,19 @@ class DifyService: text = str(raw_error or "") lower = text.lower() resolved_agent_name = str(agent_name or "").strip() or "当前智能体" + if "rerank" in lower and ("403" in lower or "forbidden" in lower): + return ( + f"{resolved_agent_name}的知识检索重排服务授权失败。" + "请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。" + ) + if any(token in lower for token in ( + "knowledge-retrieval", + "knowledge retrieval", + "dataset not found", + "embedding model", + "知识库", + )): + return f"{resolved_agent_name}的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。" if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower): return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。" if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower: @@ -124,6 +140,52 @@ class DifyService: return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。" return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。" + @staticmethod + def _present_stream_error_message(raw_message: str, status_code: int | None, agent_name: str | None = None) -> str: + """ + 把 Dify 流内 error 事件转成可直接展示的提示。 + + 核心逻辑:重排授权、鉴权、地址和网关状态走上游 HTTP 文案;其余走工作流失败文案。 + + Args: + raw_message: Dify error 事件的 message。 + status_code: 事件里的 HTTP 状态;没有时传 0。 + agent_name: 当前智能体名称。 + + Returns: + 面向用户的中文提示。 + """ + text = str(raw_message or "") + lower = text.lower() + try: + code = int(status_code or 0) + except (TypeError, ValueError): + code = 0 + if "rerank" in lower or code in (401, 403, 404, 429, 502, 503, 504): + return DifyService._friendly_upstream_error_message(code, text, agent_name) + return DifyService._friendly_workflow_failure_message(text, agent_name) + + @staticmethod + def _friendly_stream_request_failure_message(exc: Exception, agent_name: str | None = None) -> str: + """ + 将连接 Dify 时的网络异常转成用户可读提示。 + + 核心逻辑:超时和连接失败分开说明;其余 RequestException 使用当前智能体名称的通用失败句。 + + Args: + exc: requests 抛出的连接、超时或协议异常。 + agent_name: 当前智能体名称。 + + Returns: + 面向用户的中文提示,不包含异常原文。 + """ + resolved_agent_name = str(agent_name or "").strip() or "当前智能体" + if isinstance(exc, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout)): + return f"{resolved_agent_name}等待 AI 服务响应超时,请稍后重试。" + if isinstance(exc, requests.exceptions.ConnectionError): + return f"暂时无法连接{resolved_agent_name}的 AI 服务,请稍后重试。" + return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。" + @staticmethod def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str: """将 Dify HTTP 错误转换为可执行的用户提示。 @@ -1106,7 +1168,7 @@ class DifyService: }, 'error', ) - yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n" + yield f"data: {json.dumps({'event': 'error', 'message': message, 'user_facing': True}, ensure_ascii=False)}\n\n" return response.raise_for_status() yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n" @@ -1140,7 +1202,29 @@ class DifyService: data.get('conversation_id') or normalized_conversation_id, ) - if event == 'node_finished': + if event == 'error': + status_raw = data.get('status') + try: + status_code = int(status_raw) + except (TypeError, ValueError): + status_code = 0 + raw_message = str(data.get('message') or '') + # [STEP] 流内 error 先转成用户提示再转发,避免前端只能看到笼统的请求失败。 + data['message'] = DifyService._present_stream_error_message( + raw_message, + status_code, + getattr(agent, 'name', None), + ) + data['user_facing'] = True + if current_app: + current_app.logger.warning( + "[chat-stream] dify error event request_id=%s agent_id=%s status=%s raw_error=%s", + request_id, + getattr(agent, 'id', None), + status_code, + raw_message, + ) + elif event == 'node_finished': # [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data) @@ -1180,6 +1264,7 @@ class DifyService: ) data['message'] = friendly_error data['error'] = friendly_error + data['user_facing'] = True if isinstance(data.get('data'), dict): data['data']['message'] = friendly_error data['data']['error'] = friendly_error @@ -1226,13 +1311,17 @@ class DifyService: if not is_timeout and attempt < max_retries: time.sleep(attempt * 2) continue - message = DifyService._friendly_stream_request_failure_message(e) + message = DifyService._friendly_stream_request_failure_message( + e, + getattr(agent, 'name', None), + ) # [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。 error_event = { 'event': 'error', 'conversation_id': normalized_conversation_id, 'answer': message, 'message': message, + 'user_facing': True, 'metadata': {}, } persist_stream_chat(error_event, 'error') diff --git a/backend/tests/test_dify_token_usage.py b/backend/tests/test_dify_token_usage.py index 3bc1fc6b..5647257e 100644 --- a/backend/tests/test_dify_token_usage.py +++ b/backend/tests/test_dify_token_usage.py @@ -78,6 +78,38 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。' +def test_friendly_workflow_failure_message_identifies_knowledge_retrieval_failure(): + """知识检索节点失败应说明是知识库,而不是笼统的查询失败。""" + message = DifyService._friendly_workflow_failure_message( + 'Node knowledge-retrieval run failed: dataset not found', + agent_name='研发培训', + ) + assert message == '研发培训的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。' + + +def test_friendly_stream_request_failure_message_distinguishes_timeout(): + """连接 Dify 读超时应提示等待超时,且不带异常原文。""" + import requests + + message = DifyService._friendly_stream_request_failure_message( + requests.exceptions.ReadTimeout('read timed out'), + agent_name='研发培训', + ) + assert message == '研发培训等待 AI 服务响应超时,请稍后重试。' + assert 'read timed out' not in message + + +def test_present_stream_error_message_keeps_rerank_authorization_copy(): + """流内 error 事件里的重排 403 应沿用授权失败文案。""" + message = DifyService._present_stream_error_message( + 'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank', + 400, + '研发培训', + ) + assert '知识检索重排服务授权失败' in message + assert 'https://api.example' not in message + + def test_friendly_upstream_error_message_identifies_rerank_authorization_failure(): """断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。""" message = DifyService._friendly_upstream_error_message( diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 947c072e..6925bdcb 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -4,6 +4,7 @@ * 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。 * 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store。 * 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。 + * 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。 */ import { useI18n } from 'vue-i18n'; import { watch, onMounted, onBeforeUnmount } from 'vue'; @@ -11,7 +12,7 @@ import { useTheme } from '@/shared/composables/useTheme'; import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue'; import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog'; import { useRouter } from 'vue-router'; -import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth'; +import { getAuthHeaders, logoutAuth, markAuthSessionConfirmed, shouldPromptOnSessionUnauthorized } from '@/shared/utils/auth'; import { isPublicPath } from '@/shared/constants/routes'; import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store'; @@ -66,8 +67,9 @@ watch(themePreference, (newTheme) => { }); /** - * 处理接口返回未登录状态,提示用户重新登录并清理失效的本地登录信息。 - * 核心逻辑:忽略可选的关联服务/SSO 目录请求;其余未授权请求统一展示易懂提示,再执行登出。 + * 处理接口返回未登录状态,清理失效的本地登录信息。 + * 核心逻辑:忽略可选的关联服务/SSO 目录请求。书签或刷新带来的冷启动 401 只回登录页; + * 本页已经成功加载过首页后会话才中途失效时,再提示重新登录。 * @param event - 包含请求地址和状态码的全局未授权事件。 */ const onUnauthorized = (event: Event) => { @@ -75,10 +77,17 @@ const onUnauthorized = (event: Event) => { // 侧栏入口目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。 if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return; if (/\/api\/linked-services(?:\?|$)/.test(url)) return; - showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired')); + if (shouldPromptOnSessionUnauthorized()) { + showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired')); + } logoutAuth(); }; +/** + * 登出后离开需要登录的页面。 + * 核心逻辑:带上当前 fullPath 作为 redirect,登录成功后回到书签原来的地址。 + * @param event - hxops:logout,remote 为 true 表示其他标签页触发。 + */ const onLogout = (event: Event) => { useLinkedNavStore().reset(); const detail = (event as CustomEvent<{ remote?: boolean }>).detail; @@ -87,7 +96,8 @@ const onLogout = (event: Event) => { } const path = router.currentRoute.value.path; if (!isPublicPath(path)) { - router.push('/login'); + const redirect = router.currentRoute.value.fullPath; + router.push({ path: '/login', query: { redirect } }); } }; @@ -104,6 +114,7 @@ onMounted(async () => { try { const res = await fetch('/api/user/home', { headers }); if (res.ok) { + markAuthSessionConfirmed(); const data = await res.json(); if (data.user && data.user.language) { locale.value = data.user.language; diff --git a/frontend/src/features/chat/composables/useChat.ts b/frontend/src/features/chat/composables/useChat.ts index f7603335..f046430a 100644 --- a/frontend/src/features/chat/composables/useChat.ts +++ b/frontend/src/features/chat/composables/useChat.ts @@ -7,7 +7,7 @@ import { ref } from 'vue'; import { useI18n } from 'vue-i18n'; import { getAuthHeaders } from '@/shared/utils/auth'; -import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage'; +import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage'; import type { ChatMessage, ChatMessageAttachment, @@ -533,7 +533,7 @@ export function useChat() { * - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200; * - 若这里只按“终态成功”处理,页面会出现“没有任何响应”; * - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案; - * - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed。 + * - 上下文过长与缺省失败文案走 chat.streamError.contextTooLong / workflowFailed,并按用户可读文案展示。 * @param data - SSE 事件 JSON * @returns 用户可读错误;非失败终态返回空串 */ @@ -766,11 +766,6 @@ export function useChat() { run.status = workflowFailureMessage ? 'error' : 'done'; clearLikelyCompletedStreamTimer(); if (messages.value === runMessages) isThinking.value = false; - if (workflowFailureMessage) { - const botMsg = ensureBotMessage(); - if (!botMsg) continue; - applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels()); - } if (typeof data.answer === 'string' && data.answer.length > 0) { const botMsg = ensureBotMessage(); if (!botMsg) continue; @@ -797,6 +792,16 @@ export function useChat() { botMsg.content += normalizedAnswer; } } + if (workflowFailureMessage) { + const botMsg = ensureBotMessage(); + if (botMsg) { + // 后端 user_facing 与本函数生成的 i18n 文案都已是给用户看的,不再收成通用失败句。 + const userFacing = isUserFacingStreamError(data) + || workflowFailureMessage === t('chat.streamError.contextTooLong') + || workflowFailureMessage === t('chat.streamError.workflowFailed'); + applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels(), { userFacing }); + } + } if (botMsgIndex !== null) { const currentBotMsg = runMessages[botMsgIndex]; if (currentBotMsg) applyEventMetadata(currentBotMsg, data); @@ -807,7 +812,12 @@ export function useChat() { // [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问, // 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。 detachActiveStreamFromView(); - applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels()); + applyStreamErrorToMessage( + botMsg, + formatStreamError(data.message), + streamErrorLabels(), + { userFacing: isUserFacingStreamError(data) }, + ); run.status = 'error'; clearLikelyCompletedStreamTimer(); if (messages.value === runMessages) isThinking.value = false; diff --git a/frontend/src/features/chat/composables/useChatTurn.ts b/frontend/src/features/chat/composables/useChatTurn.ts index 74cda5b9..7b4c8f8e 100644 --- a/frontend/src/features/chat/composables/useChatTurn.ts +++ b/frontend/src/features/chat/composables/useChatTurn.ts @@ -3,10 +3,11 @@ * 用途:统一发起 Chat Turn(POST /api/chat/turns/stream),复用与 sendMessage 相同的 SSE 渲染链路。 * 依赖:chat-turn.types、useChat 的 shipping UI 同步、streamErrorMessage、auth headers。 * 逻辑:useChat 构造 startChatTurn 并导出;货代/请假等业务只构造 actionType + payload。 + * error / run.failed 若带 user_facing,则展示后端原文,同一轮只写一次。 */ import { type Ref } from 'vue'; import { getAuthHeaders } from '@/shared/utils/auth'; -import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage'; +import { applyStreamErrorToMessage, isUserFacingStreamError, type StreamErrorLabels } from '../utils/streamErrorMessage'; import type { StartChatTurnOptions } from '../types/chat-turn.types'; import type { ChatMessage, ChatRun } from '../types/chat.types'; import { applyShippingUiStateToMessage } from './useChat'; @@ -210,8 +211,14 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) { hasTerminalEvent = true; run.status = 'error'; const botMsg = ensureBotMessage(); - if (botMsg) { - applyStreamErrorToMessage(botMsg, options.formatStreamError(data.message), options.streamErrorLabels()); + // run.failed 与兼容用的 error 帧会连发;已写入的失败提示不再追加第二遍。 + if (botMsg && !botMsg.stream_error) { + applyStreamErrorToMessage( + botMsg, + options.formatStreamError(data.message), + options.streamErrorLabels(), + { userFacing: isUserFacingStreamError(data) }, + ); } } } catch { diff --git a/frontend/src/features/chat/utils/streamErrorMessage.spec.ts b/frontend/src/features/chat/utils/streamErrorMessage.spec.ts index b6fa6a37..a79a935e 100644 --- a/frontend/src/features/chat/utils/streamErrorMessage.spec.ts +++ b/frontend/src/features/chat/utils/streamErrorMessage.spec.ts @@ -1,8 +1,8 @@ /** * features/chat/utils/streamErrorMessage.spec.ts - * 用途:验证流式异常不会把后端或浏览器技术正文展示给用户。 + * 用途:验证流式异常的展示策略。 * 依赖:Vitest、streamErrorMessage。 - * 逻辑:保留明确连接中断分类,其余中英文异常一律使用通用提示。 + * 逻辑:已标记的用户提示原样展示;连接中断单独分类;未标记的技术正文使用通用提示。 */ import { describe, expect, it } from 'vitest'; import { resolveStreamErrorText } from './streamErrorMessage'; @@ -20,8 +20,15 @@ describe('resolveStreamErrorText', () => { expect(resolveStreamErrorText('response ended prematurely', true, labels)).toBe('回答不完整'); }); - it('does not expose Chinese or English technical errors', () => { + it('shows backend user-facing copy instead of the generic fallback', () => { + const message = '研发培训的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。'; + expect(resolveStreamErrorText(message, false, labels, { userFacing: true })).toBe(message); + }); + + it('does not expose unmarked technical errors', () => { + // 未标记 user_facing 的技术正文仍收成通用提示,避免把节点 ID 或内部报错直接给用户。 expect(resolveStreamErrorText('Dify API Key 配置错误', false, labels)).toBe('请稍后重试'); expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels)).toBe('请稍后重试'); + expect(resolveStreamErrorText('HTTP 500 node_execution_id=abc', false, labels, { userFacing: false })).toBe('请稍后重试'); }); }); diff --git a/frontend/src/features/chat/utils/streamErrorMessage.ts b/frontend/src/features/chat/utils/streamErrorMessage.ts index d695490d..8eac930e 100644 --- a/frontend/src/features/chat/utils/streamErrorMessage.ts +++ b/frontend/src/features/chat/utils/streamErrorMessage.ts @@ -2,8 +2,8 @@ * features/chat/utils/streamErrorMessage.ts * 用途:将 SSE / 浏览器流式读错映射为用户可读文案。 * 依赖:vue-i18n chat.streamError 词条。 - * 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage; - * 只识别明确的连接中断,其余异常正文不向用户透传。 + * 逻辑:useChat / useChatTurn 在 catch 与 error 事件中调用 applyStreamErrorToMessage。 + * 后端已标记 user_facing 的提示原样展示;连接中断单独分类;其余技术原文收成通用提示。 */ import type { ChatMessage } from '../types/chat.types'; @@ -46,22 +46,44 @@ export function isUpstreamDisconnectError(message: string): boolean { return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern)); } +export interface ResolveStreamErrorOptions { + /** 后端已转成可直接展示的提示(SSE user_facing=true,或前端自己的 i18n 文案)。 */ + userFacing?: boolean; +} + +/** + * 判断 SSE 事件是否携带后端已脱敏的用户提示。 + * 核心逻辑:只认布尔 true,避免把字符串 "true" 或技术原文误当成可展示文案。 + * @param data - SSE 事件 JSON + * @returns 为 true 时调用方应原样展示 message + */ +export function isUserFacingStreamError(data: Record): boolean { + return data.user_facing === true; +} + /** * 将原始错误信息映射为面向用户的提示文案。 + * 核心逻辑:已标记的用户提示原样返回;浏览器断网和上游提前断开走专用文案;其余技术正文收成通用提示。 * * @param rawMessage - 浏览器或后端返回的原始错误 * @param hasContent - 是否已有部分回答内容 * @param labels - i18n 文案集合 + * @param options.userFacing - 为 true 时展示 rawMessage,不再收成通用提示 */ export function resolveStreamErrorText( rawMessage: string, hasContent: boolean, labels: StreamErrorLabels, + options?: ResolveStreamErrorOptions, ): string { - if (isNetworkDisconnectError(rawMessage)) { + const message = rawMessage.trim(); + if (options?.userFacing && message) { + return message; + } + if (isNetworkDisconnectError(message)) { return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty; } - if (isUpstreamDisconnectError(rawMessage)) { + if (isUpstreamDisconnectError(message)) { return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected; } return labels.generic; @@ -69,14 +91,16 @@ export function resolveStreamErrorText( /** * 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。 + * @param options.userFacing - 为 true 时保留后端或 i18n 已写好的句子 */ export function applyStreamErrorToMessage( msg: ChatMessage, rawMessage: string, labels: StreamErrorLabels, + options?: ResolveStreamErrorOptions, ): void { const hasContent = Boolean(msg.content.trim()); - const text = resolveStreamErrorText(rawMessage, hasContent, labels); + const text = resolveStreamErrorText(rawMessage, hasContent, labels, options); msg.stream_error = true; if (hasContent) { msg.content += `\n\n${text}`; diff --git a/frontend/src/features/workspace/composables/useWorkspace.ts b/frontend/src/features/workspace/composables/useWorkspace.ts index abe61fee..85fb65cf 100644 --- a/frontend/src/features/workspace/composables/useWorkspace.ts +++ b/frontend/src/features/workspace/composables/useWorkspace.ts @@ -1,6 +1,7 @@ /** * features/workspace/composables/useWorkspace.ts * 工作台编排层:组合各子 composable,挂载生命周期,provide 给 Layout 与子页面。 + * 未登录进入时跳登录页并保留当前 fullPath,供书签登录后回跳。 */ import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'; import { useRouter, useRoute } from 'vue-router'; @@ -10,6 +11,7 @@ import { useTheme } from '@/shared/composables/useTheme'; import { useMessage } from '@/shared/composables/useMessage'; import { useIsMobile } from '@/shared/composables/useIsMobile'; import { WORKSPACE_PATHS } from '../constants/routes'; +import { isPublicPath } from '@/shared/constants/routes'; import type { WorkspaceUser } from '../types/workspace.types'; import { useChatHistory } from '@/features/chat/composables/useChatHistory'; import { useWorkspaceHome } from './useWorkspaceHome'; @@ -32,17 +34,18 @@ export function useWorkspace() { const currentUser = ref(null); const isSidebarCollapsed = ref(false); - const sessionRef: { handleLogout?: () => void } = {}; + const sessionRef: { handleSessionExpired?: () => void } = {}; const home = useWorkspaceHome(deps, { currentUser, isLoading, - onUnauthorized: () => sessionRef.handleLogout?.(), + // 401 只清工作台状态并回到登录页(保留 redirect)。不走手动登出,避免丢掉书签回跳地址。 + onUnauthorized: () => sessionRef.handleSessionExpired?.(), }); const session = useWorkspaceSession(deps, { currentUser, clearHome: home.clearHomeData, }); - sessionRef.handleLogout = session.handleLogout; + sessionRef.handleSessionExpired = session.handleSessionExpired; const profile = useWorkspaceProfile(deps); const schedule = useWorkspaceSchedule(deps); @@ -69,7 +72,11 @@ export function useWorkspace() { session.loadAuthUser(); if (!session.isLoggedIn.value) { - await router.replace('/login'); + // 保留书签地址。裸跳 /login 会丢掉 redirect,登录后回不到 /workspace。 + const redirect = route.fullPath; + await router.replace( + isPublicPath(route.path) ? '/login' : { path: '/login', query: { redirect } }, + ); return; } diff --git a/frontend/src/features/workspace/composables/useWorkspaceHome.ts b/frontend/src/features/workspace/composables/useWorkspaceHome.ts index fedc2825..a7b01175 100644 --- a/frontend/src/features/workspace/composables/useWorkspaceHome.ts +++ b/frontend/src/features/workspace/composables/useWorkspaceHome.ts @@ -3,10 +3,11 @@ * 应用管理/最近更新:首页数据、布局分区、收藏、快捷问题。 * 依赖:requestJson、auth 存储、auth.store。 * 逻辑:拉取 /api/user/home 后把 feature_permissions 写回登录态,供侧栏和路由守卫使用。 + * 首页成功才标记会话已确认;401 只交给全局登出回登录页,冷启动不弹「请先登录」。 */ import { computed, ref, type Ref } from 'vue'; import { config } from '@/config'; -import { getAuthHeaders, patchStoredAuthUser } from '@/shared/utils/auth'; +import { getAuthHeaders, markAuthSessionConfirmed, patchStoredAuthUser } from '@/shared/utils/auth'; import { BusinessError, requestJson } from '@/shared/api/client'; import { useAuthStore } from '@/features/auth/stores/auth.store'; import { @@ -103,6 +104,12 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) { selectedCategory.value = null; }; + /** + * 拉取工作台首页。 + * 核心逻辑:成功后标记本页会话已确认。401 不再弹出「请先登录」——书签或刷新带失效登录态时, + * 全局 hxops:unauthorized 会清会话并带回登录页;使用中途失效才由 App 提示。 + * @returns 无;失败时 401 走 onUnauthorized,其他错误只打日志 + */ const fetchHome = async () => { try { const data = await requestJson('/api/user/home', { headers: getAuthHeaders() }); @@ -187,9 +194,10 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) { return config.workspace.modules[key] !== false; }); } + markAuthSessionConfirmed(); } catch (e) { if ((e as BusinessError)?.status === 401) { - msg.error(t('login.loginRequired')); + // 冷启动(书签 /workspace)失效会话会走到这里。不弹错误框,避免登录页上盖一层「请先登录」。 onUnauthorized(); return; } diff --git a/frontend/src/features/workspace/composables/useWorkspaceSession.ts b/frontend/src/features/workspace/composables/useWorkspaceSession.ts index 2b010560..5c0f4acb 100644 --- a/frontend/src/features/workspace/composables/useWorkspaceSession.ts +++ b/frontend/src/features/workspace/composables/useWorkspaceSession.ts @@ -1,11 +1,13 @@ /** * features/workspace/composables/useWorkspaceSession.ts * 登录态:当前用户、知识库权限判断、登出与 401 清理。 - * 依赖:logoutAuth、getStoredAuthUser。 + * 依赖:logoutAuth、getStoredAuthUser、isPublicPath。 * 逻辑:从本地登录态恢复 id/username/role/feature_permissions,供工作台侧栏判断专项权限。 + * 会话失效回登录页时保留当前 fullPath,登录成功后回到书签地址。 */ import { computed, type Ref } from 'vue'; import { logoutAuth, getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth'; +import { isPublicPath } from '@/shared/constants/routes'; import { KB_ACCESS_DENIED_MESSAGE } from '../types/workspace.types'; import type { WorkspaceUser } from '../types/workspace.types'; import type { WorkspaceDeps } from './workspace.deps'; @@ -16,7 +18,7 @@ interface SessionOptions { } export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions) { - const { router } = deps; + const { router, route } = deps; const { currentUser } = options; const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest'); @@ -68,10 +70,29 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions options.clearHome(); }; + /** + * 用户主动退出。 + * 核心逻辑:清登录态后进入登录页,不带回跳,避免退出后又进刚才的页面。 + */ const handleLogout = () => { logoutAuth(); applyLoggedOutState(); - router.push('/login'); + // replace 清掉全局登出监听先写入的 redirect,主动退出后不再回到刚才的页面。 + router.replace('/login'); + }; + + /** + * 首页等接口 401 后的会话失效处理。 + * 核心逻辑:先记下当前 fullPath,再清登录态;登录页带 redirect,成功后回到书签原来的地址。 + * 不弹错误框,冷启动打开 /workspace 时登录页就是结果。 + */ + const handleSessionExpired = () => { + const redirect = route.fullPath; + logoutAuth(); + applyLoggedOutState(); + if (!isPublicPath(route.path)) { + router.replace({ path: '/login', query: { redirect } }); + } }; const onAuthLogout = () => { @@ -86,6 +107,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions loadAuthUser, applyLoggedOutState, handleLogout, + handleSessionExpired, onAuthLogout, }; } diff --git a/frontend/src/shared/utils/auth.test.ts b/frontend/src/shared/utils/auth.test.ts index e3498123..1c052bbb 100644 --- a/frontend/src/shared/utils/auth.test.ts +++ b/frontend/src/shared/utils/auth.test.ts @@ -11,9 +11,13 @@ import { getRememberedLoginPreference, getRememberedLoginProfile, getStoredAuthUser, + isAuthSessionConfirmed, + logoutAuth, + markAuthSessionConfirmed, saveAuthUser, saveRememberedLoginPreference, saveRememberedLoginProfile, + shouldPromptOnSessionUnauthorized, } from './auth'; class MemoryStorage implements Storage { @@ -101,6 +105,21 @@ describe('shared/utils/auth remember me helpers', () => { expect(localStorage.getItem('hxops_user')).toBeNull(); }); + it('does not prompt when a bookmarked page hits 401 before home succeeds', () => { + // 冷启动默认未确认:书签打开 /workspace 时失效会话不应弹错误框 + expect(isAuthSessionConfirmed()).toBe(false); + expect(shouldPromptOnSessionUnauthorized()).toBe(false); + + markAuthSessionConfirmed(); + // 首页已成功后,使用中途 401 才提示登录失效 + expect(shouldPromptOnSessionUnauthorized()).toBe(true); + + logoutAuth(); + // 登出收回确认标记,下一次书签进入仍不弹窗 + expect(isAuthSessionConfirmed()).toBe(false); + expect(shouldPromptOnSessionUnauthorized()).toBe(false); + }); + it('removes remembered login preference when user cancels remember me', () => { saveRememberedLoginPreference(true); saveRememberedLoginProfile('26040006', 'Hxit@54321'); diff --git a/frontend/src/shared/utils/auth.ts b/frontend/src/shared/utils/auth.ts index 1eb33020..c70bfece 100644 --- a/frontend/src/shared/utils/auth.ts +++ b/frontend/src/shared/utils/auth.ts @@ -3,6 +3,7 @@ * 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步,以及 401 是否表示会话失效的判断。 * 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。 * 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理;改密等业务 401 不得触发全局登出。 + * 冷启动(书签/刷新)在首页请求成功前不算已确认会话,401 只回登录页,不弹错误框。 */ export type FeaturePermissions = { training_hr_manage?: boolean; @@ -179,10 +180,45 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => { const AUTH_LOGOUT_KEY = 'hxops_auth_logout'; const AUTH_BC_NAME = 'hxops_auth'; +/** 本页生命周期内,是否已有一次带登录态的首页请求成功。冷启动 401 用它决定要不要弹窗。 */ +let _authSessionConfirmed = false; + +/** + * 标记当前页的登录会话已被成功的首页数据确认。 + * 核心逻辑:仅 /api/user/home 成功后调用;刷新或书签进入时默认未确认。 + */ +export function markAuthSessionConfirmed(): void { + _authSessionConfirmed = true; +} + +/** + * 当前页是否已确认过有效登录会话。 + * @returns 首页请求成功过则为 true;登出或尚未成功拉取首页时为 false + */ +export function isAuthSessionConfirmed(): boolean { + return _authSessionConfirmed; +} + +/** + * 会话类 401 是否要弹出「登录已失效」。 + * 核心逻辑:书签、地址栏回车、刷新等冷启动还没有成功加载过首页,此时用户预期就是登录页,不能再盖一层错误框。 + * 使用过程中会话中途失效(本页已经确认过登录)才提示。 + * @returns true 时由 App 弹出登录失效提示 + */ +export function shouldPromptOnSessionUnauthorized(): boolean { + return _authSessionConfirmed; +} + +/** 登出或清理登录态时收回“已确认会话”标记,避免下一次冷启动误弹窗。 */ +function resetAuthSessionConfirmed(): void { + _authSessionConfirmed = false; +} + let _authBroadcast: BroadcastChannel | null = null; let _authSyncInitialized = false; const clearAuthStorage = (): void => { + resetAuthSessionConfirmed(); localStorage.removeItem(AUTH_USER_KEY); sessionStorage.removeItem(AUTH_USER_KEY); sessionStorage.removeItem('hxops_wecom_state'); From e8d9dba8a3541fb75444cca10a84dd83d4d70309 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 8 Oct 2026 11:06:25 +0800 Subject: [PATCH 03/32] =?UTF-8?q?fix(freight-rpa):=20=E4=B8=A4=E5=9F=9F?= =?UTF-8?q?=E8=B6=85=E6=97=B6=E6=94=BE=E5=AE=BD=E8=87=B3=201=20=E5=B0=8F?= =?UTF-8?q?=E6=97=B6=E5=B9=B6=E5=BC=BA=E5=88=B6=E6=94=B6=E6=96=99=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E5=AE=8C=E6=95=B4=E9=87=8D=E5=AF=BC=E8=88=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 库存/收料超时 900s 放宽到 3600s:对账按笔间静默判活后,超时须覆盖最坏批次总时长,防健康在飞批次被误回收(RUN20261008003113B726 实测教训) - 收料 worker 重试尝试(attempt>1)强制完整重导航:对齐库存 AWSRTM 兜底,报表导出菜单缺失属瞬态故障,须回入口页重选菜单,绝不在错误页直接重试 - 凭据校验类失败(invalid/verification)为确定性失败,不进入重试 - 同步 test 环境超时配置 --- .env.test | 5 +++- .../freight_rpa/receipt/receipt_rpa_worker.py | 24 +++++++++++++++---- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/.env.test b/.env.test index 99e5e40a..1f124d1a 100644 --- a/.env.test +++ b/.env.test @@ -155,7 +155,10 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐) FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data -FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+), +# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训) +FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600 +FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 diff --git a/scripts/freight_rpa/receipt/receipt_rpa_worker.py b/scripts/freight_rpa/receipt/receipt_rpa_worker.py index 23fa3cf1..efc97be9 100644 --- a/scripts/freight_rpa/receipt/receipt_rpa_worker.py +++ b/scripts/freight_rpa/receipt/receipt_rpa_worker.py @@ -490,17 +490,25 @@ def _export_unit_download( page: Any, context: Any, drop_dir: Path, + attempt: int = 1, ) -> tuple[Any, Any]: """ 导出单个收料单元的 Playwright Download;必要时干净页重试会话。 + Args: + attempt: 第几次尝试(1 起)。>1 时强制完整重导航(对齐库存 2026-09-20 AWSRTM + 兜底:报表页导出菜单缺失属瞬态故障,绝不在错误页上直接重试,须回入口页 + 重选菜单进报表),且 prepare 的导航/会话类异常一并走干净页安全网 + (凭据校验类 invalid/verification 为确定性失败,不重试)。 Returns: (download, page):download 为 Playwright Download;page 可能已切换为干净页。 """ unit['__download_dir'] = str(drop_dir) if connector == 'dbs': source = receipt_dbs_export.build_receipt_dsv_source(unit, entry_url=login_url) - previous_unit = group[index - 1] if index > 0 else None + # 重试尝试强制完整重导航:不携带前一单元上下文,prepare 从入口页重选菜单进报表。 + force_full_navigation = attempt > 1 + previous_unit = group[index - 1] if (index > 0 and not force_full_navigation) else None previous_source = ( receipt_dbs_export.build_receipt_dsv_source(previous_unit, entry_url=login_url) if previous_unit is not None else None @@ -509,14 +517,18 @@ def _export_unit_download( try: skip_navigation = bool( dsv_report_export.prepare_dsv_batch_export_step( - page, login_url, previous_source, source, index=index, + page, login_url, previous_source, source, + index=0 if force_full_navigation else index, ) ) except Exception as exc: - if not _is_login_session_error(exc): + # 安全网:登录/会话与导航类瞬态异常均新开干净页重跑完整准备; + # 仅凭据校验类(invalid/verification)确定性失败不重试(对齐库存)。 + message = str(exc).lower() + if any(token in message for token in ('invalid', 'verification')): raise print( - f'[receipt-batch] dbs session prepare failed for {unit.get("source_code")}, ' + f'[receipt-batch] dbs prepare failed for {unit.get("source_code")}, ' f'retry with clean page: {exc}', file=_sys.stderr, ) @@ -531,7 +543,8 @@ def _export_unit_download( ) return download, page - first_in_profile = index == 0 + # Crane 重试尝试同样强制完整重登导航(first_in_profile=True 走首源完整登录)。 + first_in_profile = index == 0 or attempt > 1 try: download = receipt_crane_export.export_receipt_report( page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), @@ -643,6 +656,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None: page=page, context=context, drop_dir=drop_dir, + attempt=attempt, ) output = _save_download( download, drop_dir, unit, batch_run_no=batch_run_no, From 91a4bd538d8ad93029ebb12097e5012f527a6037 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 8 Oct 2026 11:31:09 +0800 Subject: [PATCH 04/32] =?UTF-8?q?fix(shipping-notice):=20=E6=89=BE?= =?UTF-8?q?=E5=9B=9E=E9=87=8D=E6=9E=84=E5=90=88=E5=B9=B6=E4=B8=A2=E5=A4=B1?= =?UTF-8?q?=E7=9A=84=E6=94=B6=E6=96=99=E8=BF=9B=E5=BA=A6=E4=B8=8A=E6=8A=A5?= =?UTF-8?q?=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 恢复 receipt-unit-progress / receipt-batch-progress 两路由(Tool 蓝图):Worker 上报全程 404、活动锚失效、在飞批次被超时对账误杀 - 路由注释标注「勿再从旧路径文件删除」防回归;新增路由注册回归锁测试,路由缺失在部署前即红 - 单元领取 mark 落单元 started_at,接续收料超时对账的笔间静默判活链路 --- backend/app/api/tools/shipping_notice.py | 20 +++++++++++++++++ .../test_freight_receipt_rpa_callback.py | 22 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/backend/app/api/tools/shipping_notice.py b/backend/app/api/tools/shipping_notice.py index 8827e9d9..911427f9 100644 --- a/backend/app/api/tools/shipping_notice.py +++ b/backend/app/api/tools/shipping_notice.py @@ -334,6 +334,26 @@ def rpa_receipt_batch_ready(): return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())}) +@shipping_notice_bp.route('/rpa/receipt-unit-progress', methods=['POST']) +def rpa_receipt_unit_progress(): + """收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。 + + 本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at); + 曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。 + """ + from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing + + return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())}) + + +@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST']) +def rpa_receipt_batch_progress(): + """收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。""" + from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress + + return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())}) + + @shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST']) def rpa_inventory_batch_claimed(): """v2 Worker 领取回调:仅记录 Attempt 执行阶段。""" diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index 43c02feb..b55f0b56 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -266,3 +266,25 @@ def test_ingest_empty_persists_no_receipt_data(app): assert saved.status == 'empty' assert saved.error_code == 'no_receipt_data' assert saved.error_message == 'no_receipt_data' + + +def test_receipt_progress_routes_are_registered(app): + """回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。 + + 2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、 + 在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。 + """ + app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key' + client = app.test_client() + headers = {'X-Integration-Key': 'test-tool-key'} + for path, payload in ( + ('/api/shipping-notice/rpa/receipt-unit-progress', + {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}), + ('/api/shipping-notice/rpa/receipt-batch-progress', + {'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}), + ): + # [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层 + # 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。 + resp = client.post(path, json=payload, headers=headers) + assert resp.status_code == 200, (path, resp.status_code, resp.get_json()) + assert resp.get_json()['data']['updated'] is False From 4e97553f42be3fb0994ba2dc2acbc957f47cc62f Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 8 Oct 2026 13:14:47 +0800 Subject: [PATCH 05/32] =?UTF-8?q?fix(shipping-notice):=20=E6=94=B6?= =?UTF-8?q?=E6=96=99=E5=9B=9E=E8=B0=83=E8=B7=AF=E5=BE=84=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20drop=20=E6=A0=B9=E5=86=85=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修复跨机成功回调全程 400:Worker(Windows)与后端(Linux 挂载根)分属两机根路径不同,后端无法解析 Worker 本机绝对路径 - Worker 只上报文件名(output.name),后端按自身挂载的 drop 根拼接定位;历史载荷携带绝对路径亦按末段文件名兼容解析 - 同步收料 worker 路径契约注释与跨机路径回归测试 --- .../shipping_notice/receipt_report_storage.py | 12 ++++++++-- .../test_freight_receipt_rpa_callback.py | 24 +++++++++++++++++++ .../freight_rpa/receipt/receipt_rpa_worker.py | 8 +++++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/receipt_report_storage.py index 11019780..2ad47d85 100644 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ b/backend/app/services/shipping_notice/receipt_report_storage.py @@ -29,12 +29,20 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve def _read_receipt_callback_file(file_path: str) -> bytes: - """只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。""" + """只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 + + 路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属 + 两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...), + Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史 + 载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。 + """ configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip() if not configured_root: raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') root = Path(configured_root).resolve() - path = Path(file_path).resolve() + # 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。 + name = Path(str(file_path).replace('\\', '/')).name + path = (root / name).resolve() try: path.relative_to(root) except ValueError as exc: diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index b55f0b56..b237cdbe 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -288,3 +288,27 @@ def test_receipt_progress_routes_are_registered(app): resp = client.post(path, json=payload, headers=headers) assert resp.status_code == 200, (path, resp.status_code, resp.get_json()) assert resp.get_json()['data']['updated'] is False + + +def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path): + """跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file + + with app.app_context(): + drop_root = tmp_path / 'receipt-drop' + drop_root.mkdir() + app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root) + target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx' + target.write_bytes(b'receipt-bytes') + + # [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都 + # 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。 + assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes' + assert _read_receipt_callback_file( + r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx' + ) == b'receipt-bytes' + outside = tmp_path / 'outside.xlsx' + outside.write_bytes(b'x') + with pytest.raises(ValidationError, match='receipt callback file'): + _read_receipt_callback_file(str(outside)) diff --git a/scripts/freight_rpa/receipt/receipt_rpa_worker.py b/scripts/freight_rpa/receipt/receipt_rpa_worker.py index efc97be9..d10f199e 100644 --- a/scripts/freight_rpa/receipt/receipt_rpa_worker.py +++ b/scripts/freight_rpa/receipt/receipt_rpa_worker.py @@ -584,12 +584,16 @@ def _write_mock_receipt_excel(path: Path) -> None: def _post_unit_ready(unit: dict[str, Any], output: Path) -> None: - """落盘成功后上报 receipt-batch-ready(归档);调用方须放在导出重试之外。""" + """落盘成功后上报 receipt-batch-ready(归档);调用方须放在导出重试之外。 + + file_path 契约为「drop 根内文件名」:Worker(Windows)与后端(Linux 挂载根)分属 + 两机、根路径不同,后端按自身挂载根拼接定位(跨机部署下发本机绝对路径必 400)。 + """ _post_callback({ 'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', - 'file_path': str(output), + 'file_path': output.name, 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest(), }) From 386f93108c39f5128e3add415ec78e4f25ae370d Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Sun, 11 Oct 2026 17:42:55 +0800 Subject: [PATCH 06/32] =?UTF-8?q?feat(shipping-notice):=20=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E7=BC=BA=E5=8F=A3=E6=96=99=E5=8F=B7=E5=85=9C=E5=BA=95?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=94=BE=E8=A1=8C=E5=B9=B6=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=96=99=E5=8F=B7=E5=8F=AF=E7=94=A8=E9=87=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 匹配器按料号二次汇总 part_available_qty 随行级匹配事实持久化(新列,迁移 0a575f3a) - 缺口行料号总库存满足需求时系统自动放行,复用人工放行同一落库/审计/门禁链路,证据按预约优先→料号兜底自动带出 - 前端库存匹配表原「可用数量」列改为「预约数量」,其后新增「可用数量」(料号总库存)列 - DSV 连接器防误点「忘记密码」链接并参数化料号报表取数,库存 worker 按料号查询配套 - 收料就绪与来源状态联动调整;casdoor 未识别认证错误日志保留原始异常堆栈 - 同步门禁/投影/持久化测试、调拨卡片文案四语言与文档 --- .../app/api/in_transit_transfer/__init__.py | 26 + .../shipping_notice_line_inventory_match.py | 3 + backend/app/services/auth/casdoor/errors.py | 7 +- .../in_transit_transfer/file_parser.py | 33 +- .../receipt_trigger_service.py | 119 ++- .../in_transit_transfer/source_file_status.py | 10 +- .../shipping_notice/fulfillment_workflow.py | 19 + .../line_inventory_match_persistence.py | 13 + .../line_inventory_match_projection.py | 11 + ...der_review_fulfillment_decision_service.py | 498 ++++++++-- .../shipping_notice/process_gate_service.py | 63 +- .../processing_projection_invariants.py | 5 + .../stp_line_inventory_match.py | 45 + .../app/services/shipping_notice/ui_state.py | 5 +- ...c32_add_part_available_qty_to_shipping_.py | 25 + .../tests/api/test_in_transit_transfer_api.py | 35 + .../test_receipt_file_parser.py | 36 +- .../test_receipt_trigger_service.py | 169 +++- .../test_source_file_status.py | 11 + backend/tests/test_dsv_report_parameters.py | 164 +++ ...est_freight_rpa_worker_inventory_params.py | 176 ++++ .../test_line_inventory_match_persistence.py | 139 ++- .../test_line_inventory_match_projection.py | 30 +- .../tests/test_shipping_notice_ui_state.py | 25 + .../test_shipping_process_gate_service.py | 50 + ...ipping_processing_projection_invariants.py | 23 + ...ipping_review_line_fulfillment_decision.py | 612 +++++++++++- .../test_shipping_stp_match_completed_gate.py | 52 + ...hipping_stp_phase4_line_inventory_match.py | 86 ++ docs/demand.md | 2 + .../features/in-transit-transfer/technical.md | 1 + docs/features/shipping-notice/business.md | 39 + docs/features/shipping-notice/technical.md | 61 ++ docs/funclist.md | 2 + ...6-10-09-inventory-part-fallback-release.md | 937 ++++++++++++++++++ .../ShippingFieldAssetsPage.vue | 5 +- .../ShippingIdentityRulesPage.vue | 24 +- .../ShippingInventoryPage.vue | 40 +- .../OrderProfileCreateWizardPage.vue | 4 +- .../OrderProfilePublishCheckPage.vue | 2 +- .../OrderProfileVersionDetailPage.vue | 5 +- .../components/OrderProfileSampleStep.vue | 2 +- .../ShippingOrderSchemaPage.vue | 4 +- .../src/features/chat/api/transfer.api.ts | 24 + .../messages/TransferExecutableCard.vue | 6 +- .../components/messages/TransferMatchCard.vue | 7 +- .../messages/TransferMessageView.vue | 10 +- .../messages/TransferSourceSelectCard.spec.ts | 82 +- .../messages/TransferSourceSelectCard.vue | 122 ++- .../chat/composables/useChatTransfer.ts | 11 + .../features/chat/types/shipping.api.types.ts | 2 + .../src/features/chat/types/transfer.types.ts | 4 +- .../views/ShippingOrderReviewView.spec.ts | 10 +- .../chat/views/ShippingOrderReviewView.vue | 10 +- frontend/src/locales/en/chat.json | 8 + frontend/src/locales/th/chat.json | 8 + frontend/src/locales/zh-CN/chat.json | 8 + frontend/src/locales/zh-TW/chat.json | 8 + .../freight_rpa/connectors/dsv/dsv_auth.py | 57 +- .../connectors/dsv/dsv_report_export.py | 65 +- .../connectors/dsv/dsv_report_parameters.py | 117 ++- .../inventory/inventory_rpa_worker.py | 42 +- 62 files changed, 4000 insertions(+), 219 deletions(-) create mode 100644 backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py create mode 100644 docs/superpowers/plans/2026-10-09-inventory-part-fallback-release.md diff --git a/backend/app/api/in_transit_transfer/__init__.py b/backend/app/api/in_transit_transfer/__init__.py index 570bbc5d..6d7e9977 100644 --- a/backend/app/api/in_transit_transfer/__init__.py +++ b/backend/app/api/in_transit_transfer/__init__.py @@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str): }, status=202) +@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"]) +@require_transfer_permission +def retry_sources_rpa_batch_api(): + """批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。 + + 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用; + 逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器; + 合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。 + + 请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与 + fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。 + """ + payload = request.get_json(silent=True) or {} + source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()] + if not source_codes: + raise ValidationError("source_codes is required") + from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch + + outcome = trigger_receipt_rpa_batch( + source_codes=source_codes, + business_date=str(business_date_now()), + reason="transfer_retry_receipt", + ) + return _ok(outcome) + + @in_transit_transfer_bp.route("/backlog", methods=["GET"]) @require_transfer_permission def backlog_api(): diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py index 6007838a..32625f87 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base): required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + # 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。 + # 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。 + part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) diff --git a/backend/app/services/auth/casdoor/errors.py b/backend/app/services/auth/casdoor/errors.py index 35b5a81e..a44164cc 100644 --- a/backend/app/services/auth/casdoor/errors.py +++ b/backend/app/services/auth/casdoor/errors.py @@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None: ) if 'invalid or expired casdoor state' in lowered_raw: raise ValidationError('Invalid or expired Casdoor state') - current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data) + # [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。 + current_app.logger.warning( + '[casdoor] unmapped auth error context=%s payload=%s source=%r', + context, data, source, + exc_info=source if isinstance(source, BaseException) else None, + ) raise AppError( code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', diff --git a/backend/app/services/in_transit_transfer/file_parser.py b/backend/app/services/in_transit_transfer/file_parser.py index 4e91f488..dfffd6ec 100644 --- a/backend/app/services/in_transit_transfer/file_parser.py +++ b/backend/app/services/in_transit_transfer/file_parser.py @@ -10,7 +10,7 @@ from __future__ import annotations from dataclasses import dataclass from datetime import date, datetime -from decimal import Decimal +from decimal import Decimal, InvalidOperation from typing import Any, Iterable, Mapping from app.core.errors import AppError @@ -59,16 +59,26 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None: rows.append({"row_no": row_no, "reason": reason}) -def _is_unreceived_row(date_value: Any) -> bool: - """判断是否为"无收料事实的在途行":无异动日期即跳过。 +def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool: + """判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。 - WMS 异动报告会携带两类无日期行,均不是可用的收料事实: + WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实: ① 未收料在途 ASN(Date Received 空、Qty Received 0); - ② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。 - 收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配; - 跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。 + ② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章); + ③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE + WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。 + 收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程 + 抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。 """ - return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()) + if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()): + return True + try: + # 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。 + return Decimal(str(quantity_raw)) == 0 + except (InvalidOperation, ValueError, TypeError): + # 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由 + # validate_receipt_quantity 按非法数量阻断,不在此吞掉。 + return not str(quantity_raw or "").strip() def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: @@ -174,7 +184,7 @@ def _parse_rows( if row_source and row_source.upper() != str(source_code).upper(): _fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}") continue - if _is_unreceived_row(receipt_date_value): + if _is_unusable_receipt_row(receipt_date_value, quantity_raw): continue try: receipt_date = parse_date(receipt_date_value) @@ -202,5 +212,8 @@ def _parse_rows( unit=str(row.get("unit") or "").strip(), )) if errors: - raise ReceiptFileSchemaError(rows=errors) + # 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message + # 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。 + summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3]) + raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors) return parsed diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/receipt_trigger_service.py index 25a87aa1..6aba80a2 100644 --- a/backend/app/services/in_transit_transfer/receipt_trigger_service.py +++ b/backend/app/services/in_transit_transfer/receipt_trigger_service.py @@ -1,6 +1,6 @@ """在途调拨真实收料 RPA 触发服务。 -用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。 +用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。 按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile, 先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达), 再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。 @@ -8,11 +8,14 @@ 逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围; 一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed;写 trigger 失败把单元行标 failed 并 commit。 + trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件: + Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。 """ from __future__ import annotations import uuid +from datetime import datetime from typing import Any, Callable from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger @@ -151,3 +154,117 @@ def trigger_receipt_rpa( unit.trigger_snapshot_json = unit_payload db.session.commit() return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path} + + +def trigger_receipt_rpa_batch( + *, + source_codes: list[str], + business_date: str, + reason: str = 'transfer_retry_receipt', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。 + + 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用; + 行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。 + + 核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批; + parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行 + ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。 + Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。 + + Args: + source_codes: 来源实例编码列表(去重保序;空串自动剔除)。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger payload)。 + writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。 + + Returns: + {"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。 + ok=本次请求产生了主效果(写盘成功,或无需写盘且全部来源经本地重解析恢复); + triggered=是否写了 batch trigger;results 逐来源携带真实结果 + (触发:{source_code, ok: true};重解析:{..., reparsed: true, file_status}; + 跳过:{source_code, ok: false, error_code, error_message})。 + """ + from app import db + from app.models import ShippingReceiptRpaUnitRun + from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + + codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip())) + results: list[dict[str, Any]] = [] + units: list[ShippingReceiptRpaUnitRun] = [] + unit_payloads: list[dict[str, Any]] = [] + + # [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。 + for code in codes: + status = resolve_source_file_status(source_code=code) + if status.get('file_status') == 'parse_failed' and status.get('file_sha256'): + sync_and_commit_for_callback( + source_code=code, business_date=business_date, now=datetime.utcnow(), + ) + status = resolve_source_file_status(source_code=code) + results.append({ + 'source_code': code, + 'ok': status.get('file_status') == 'ready', + 'reparsed': True, + 'file_status': status.get('file_status'), + }) + continue + try: + unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason)) + except RuntimeError as exc: + results.append({ + 'source_code': code, 'ok': False, + 'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc), + }) + + if not unit_payloads: + # 无可触发来源:全部经重解析恢复 → 请求已达成目的;否则如实报无可用来源。 + reparse_recovered = any(item.get('reparsed') and item.get('ok') for item in results) + db.session.commit() + if reparse_recovered: + return {"ok": True, "triggered": False, "results": results} + return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results} + + # [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。 + for payload in unit_payloads: + unit = ShippingReceiptRpaUnitRun( + inventory_source_id=payload['inventory_source_id'], + source_code=payload['source_code'], + connector_type=payload['connector_type'], + warehouse_id=payload.get('warehouse_id'), + callback_id=payload['callback_id'], + status='awaiting_rpa', + config_snapshot_json=dict(payload['config_snapshot']), + ) + db.session.add(unit) + units.append(unit) + db.session.flush() + for unit, payload in zip(units, unit_payloads): + payload['unit_run_id'] = unit.id + + # [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。 + run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or write_receipt_export_batch_trigger + path = writer_fn(run_no, unit_payloads, payload={ + 'schema_version': 'shipping_receipt_rpa.v1', + 'action': 'receipt_export_batch', + 'business_date': business_date, + 'reason': reason, + 'source_codes': [payload['source_code'] for payload in unit_payloads], + }) + if not path: + for unit in units: + unit.status = 'failed' + unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE' + unit.error_message = 'receipt trigger directory unavailable' + db.session.commit() + return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results} + + # [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 + for unit, payload in zip(units, unit_payloads): + unit.trigger_snapshot_json = payload + results.append({'source_code': unit.source_code, 'ok': True}) + db.session.commit() + return {"ok": True, "triggered": True, "trigger_path": path, "results": results} diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py index 44036750..3aba05bf 100644 --- a/backend/app/services/in_transit_transfer/source_file_status.py +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -26,7 +26,10 @@ from app.services.in_transit_transfer.receipt_file_gate import ( ) RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing') -FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled') +FAILED_UNIT_STATUSES = ('failed', 'cancelled') +# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障, +# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。 +NO_DATA_UNIT_STATUSES = ('empty',) def resolve_source_file_status(*, source_code: str) -> dict: @@ -37,7 +40,7 @@ def resolve_source_file_status(*, source_code: str) -> dict: Returns: {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, - file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'}; + file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'}; parse_failed 表示文件仍可用但解析失败:has_ready_file=False, 仍带 file_no/file_sha256 便于诊断与前端提示。 """ @@ -84,6 +87,9 @@ def resolve_source_file_status(*, source_code: str) -> dict: .order_by(ShippingReceiptRpaUnitRun.id.desc()) .first() ) + if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES: + # 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。 + return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES: return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 4c85580e..423469da 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -1277,6 +1277,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, ) # 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。 _merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None) + # [BE-料号兜底自动放行] 行事实落库后、聚合重算【前】执行(与 match_inventory 同款钩子): + # 料号总量满足需求的缺口行由系统自动放行,使下方聚合重算把放行行计入满足、 + # 行级重匹配可直接落 MATCHED_FULFILLABLE;重入安全性说明见 match_inventory 钩子注释。 + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + auto_release_part_fallback_shortages(task) line_results = list(match_payload.get('line_results') or []) from app.services.shipping_notice.reservation_service import record_inventory_verification @@ -1778,6 +1786,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None, matching_rule_version='stp_line_v2', ) + # [BE-料号兜底自动放行] 行事实落库后、聚合与 match_completed 判定【前】执行: + # 料号总量满足需求的缺口行由系统自动放行(满足即放行,非仅可放行),使随后的 + # 聚合重算与满足性判定把放行行计入满足、任务可直接落 MATCHED_FULFILLABLE。 + # 重入安全:匹配跑在 AutoProgress Gate 执行器事务内时,submit_auto_progress 按 + # 「任务唯一活动 Job + 活动 Attempt 复用」幂等,不会重复入队或自触发;auto fulfill + # Job 重复入队由协调器 eligible+幂等键吸收(与既有匹配路径的多入队行为一致)。 + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + auto_release_part_fallback_shortages(task) # 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单, # 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。 match_status, shortages = _recompute_task_match_aggregate(task) diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 63835bef..56bb7ed8 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_persistence.py 依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。 逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库; 新快照新增行并切换 is_current;不覆盖历史快照事实。 + 匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列, + 供后续投影层与自动放行服务读取。 """ from __future__ import annotations @@ -277,6 +279,12 @@ def persist_line_inventory_match_facts( required_qty=str(required) if required is not None else None, available_qty=str(available) if available is not None else None, shortage_qty=str(shortage) if shortage is not None else None, + # 料号兜底总量(Task 1 匹配器下发):字符串化落列;无键/None → NULL, + # BE-5 / not_found 分支不篡改,直接取匹配器原值。 + part_available_qty=( + str(result['part_available_qty']) + if result.get('part_available_qty') is not None else None + ), reservation_id=rsv, part_number=pn, unit=unit_value, @@ -342,6 +350,11 @@ def persist_line_inventory_match_facts( existing.required_qty = str(required) if required is not None else None existing.available_qty = str(available) if available is not None else None existing.shortage_qty = str(shortage) if shortage is not None else None + # 更新分支同样以最新匹配结果刷新兜底总量;键缺失 → NULL,不残留旧值。 + existing.part_available_qty = ( + str(result['part_available_qty']) + if result.get('part_available_qty') is not None else None + ) existing.reservation_id = rsv existing.part_number = pn existing.unit = unit_value diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py index ca793819..8a150b4b 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py 依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。 逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用; ready+not_found→available=0;result_missing 不得转 0; + part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None, + 不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算); inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮); line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail; load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo, @@ -562,6 +564,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'required_qty': row.required_qty, 'available_qty': row.available_qty, 'shortage_qty': row.shortage_qty, + 'part_available_qty': getattr(row, 'part_available_qty', None), 'reservation_id': row.reservation_id, 'part_number': row.part_number, 'unit': row.unit, @@ -661,6 +664,7 @@ def project_line_inventory_view( 'inventory_status': None, 'match_result': None, 'available_qty': None, + 'part_available_qty': None, 'shortage_qty': None, 'is_shortage': False, 'display_available': 'pending', @@ -699,6 +703,12 @@ def project_line_inventory_view( required_qty=required_qty if required_qty is not None else fact.get('required_qty'), available_qty=fact.get('available_qty'), ) + # [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控); + # 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。 + part_total = _parse_qty(fact.get('part_available_qty')) + part_available_value = ( + str(part_total) if inventory_status == STATUS_READY and part_total is not None else None + ) user_status = project_user_line_status( inventory_status=inventory_status, match_result=match_result, @@ -770,6 +780,7 @@ def project_line_inventory_view( 'inventory_status': inventory_status, 'match_result': match_result, 'available_qty': qty['available_qty'], + 'part_available_qty': part_available_value, 'shortage_qty': qty['shortage_qty'], 'is_shortage': bool(qty['is_shortage']), 'display_available': qty['display_available'], diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index 8a856313..d8a18cdc 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -30,6 +30,9 @@ from app.models import ( ShippingOrderTask, ShippingTaskInventoryRpaAttempt, ) +from app.services.shipping_notice.line_inventory_match_persistence import ( + resolve_review_case_for_task, +) from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) @@ -317,8 +320,14 @@ def _shortage_release_required_fields( line_index: int | None, inventory_snapshot_id: int | None, inventory_source_code: str | None, -) -> list[dict[str, str]]: - """按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。""" +) -> tuple[list[dict[str, Any]], str]: + """按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。 + + Returns: + (fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读, + 其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'}, + 'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。 + """ if line_index is None: raise ConflictError( 'Current line inventory evidence is unavailable', @@ -371,7 +380,8 @@ def _shortage_release_required_fields( and str(item.get('source_key') or '').strip().isdigit() } labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {} - return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + # 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。 + return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot' definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else [] expected = [ @@ -395,6 +405,24 @@ def _shortage_release_required_fields( dict(row) for row in inventory_lines if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) ] + evidence_scope = 'inventory_snapshot' + if not candidates: + # [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行, + # 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键; + # 匹配方案不含料号键则维持空候选(全人工补录,fail-closed)。 + part_field_ids = { + int(field_id) for field_id, _value in expected + if str(field_id).strip().isdigit() + and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number' + } + if part_field_ids: + candidates = [ + dict(row) for row in inventory_lines + if all(_match_text(row.get(str(field_id))) == value + for field_id, value in expected if int(field_id) in part_field_ids) + ] + if candidates: + evidence_scope = 'part_fallback' field_ids = { int(str(item.get('source_key') or '').strip()) for item in mappings @@ -411,7 +439,7 @@ def _shortage_release_required_fields( mappings=mappings, candidates=candidates, field_labels=labels, - ) + ), evidence_scope def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]: @@ -429,7 +457,7 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s def _sync_confirmed_task_fulfillment_gates( *, case: ShippingOrderReviewCase, - actor_id: int, + actor_id: int | None, trigger: str = 'inventory_shortage_released', ) -> None: """ @@ -924,7 +952,8 @@ def project_review_case_line_decisions( release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact) if release_line_index is None: release_line_index = draft_line.get('_line_index') - release_template_fields = _shortage_release_required_fields( + # scope 仅在 decide 落库时写入审计快照;投影契约本期不新增字段。 + release_template_fields, _evidence_scope = _shortage_release_required_fields( task=task, line_index=release_line_index, inventory_snapshot_id=release_snapshot_id, @@ -1076,6 +1105,185 @@ def build_inventory_issue_fallback( } +def _apply_shortage_line_release( + task: ShippingNotice, + line_index: int, + release_field_values: dict[str, Any], + *, + evidence_scope: str | None = None, + actor_type: str = 'user', + actor_id: int | None = None, + auto_release: bool = False, + case: ShippingOrderReviewCase | None = None, + reason: str | None = None, +) -> ShippingOrderReviewLineDecision: + """ + 人工 decide 与缺口自动放行共用的短缺放行执行体:解析证据字段、校验补录、 + 版本化落库、同步正式 OT 门禁并写审计。 + + 核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。 + 证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中 + 按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 + + 人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并 + 同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过, + 本执行体不重复校验放行资格。 + + Args: + task: 正式 OT 聚合根(含 order_snapshot_id;自动放行来自匹配钩子, + 人工 decide 来自 case.confirmed_task_id)。 + line_index: 目标行号(0-based,与行匹配事实 line_index 同口径)。 + release_field_values: 人工补录值(decide)或自动带出全量值(自动放行); + 校验后与模板字段合并为全量值字典落库。 + evidence_scope: 调用方已解析的证据范围;None 时按行事实重新解析 + (人工 decide 路径,由本执行体统一解析避免双重查询语义分叉)。 + actor_type: 决定来源('user' 人工 / 'system' 自动放行),写入 decision_source。 + actor_id: 操作人(人工为操作用户;自动为触发匹配的用户,可为 None)。 + auto_release: True 时在决定与审计快照标记 auto_release(系统自动放行溯源)。 + case: 可选;人工 decide 已加载的可写 Case。缺省时按 confirmed_task_id 反查。 + reason: 可选人工放行原因;自动放行为 None。 + + Returns: + 新建的 ShippingOrderReviewLineDecision(已 flush、含主键)。 + + Raises: + ConflictError: Case/草稿行缺失、证据不可解析或人工必填字段缺失。 + """ + release_case = case if case is not None else resolve_review_case_for_task(task) + if release_case is None or getattr(release_case, 'id', None) is None: + raise ConflictError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + draft_line_by_index = { + int(row.get('_line_index')): (key, row) + for key, row in _draft_line_map(release_case).items() + if row.get('_line_index') is not None + } + pair = draft_line_by_index.get(int(line_index)) + if pair is None: + raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') + key, draft_line = pair + + from app.models import ShippingNoticeLineInventoryMatch + + fact = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True) + .first() + if getattr(task, 'id', None) is not None else None + ) + release_line_index = getattr(fact, 'line_index', None) if fact is not None else int(line_index) + release_template_fields, resolved_scope = _shortage_release_required_fields( + task=task, + line_index=release_line_index, + inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None, + inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None, + ) + release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot') + release_required_fields = _manual_required_release_fields(release_template_fields) + release_values = _validate_inventory_shortage_release_fields( + required_fields=release_required_fields, + supplied_values=release_field_values or {}, + ) + # [STEP] 落库为「自动带出 + 人工补录」全量模板字段值字典:人工提交值覆盖自动带出值 + # (校验白名单仅用于必填校验,不再裁剪落库字典)。export.release_overrides_by_source_line + # 只读本字典——若仍落仅人工项,料号兜底/预约命中自动带出的字段在 Excel 证据列将为空。 + manual_field_ids = {str(field.get('field_id') or '') for field in release_required_fields} + release_values = { + str(field.get('field_id') or ''): ( + release_values[str(field.get('field_id') or '')] + if str(field.get('field_id') or '') in manual_field_ids + else (None if field.get('value') is None else str(field.get('value'))) + ) + for field in release_template_fields + } + + projections = _line_projection_map(release_case) + proj = projections.get(key) or {} + from app.services.shipping_notice.order_review_workbench_projection import ( + schema_fields_from_case, + ) + + schema_fields = schema_fields_from_case(release_case) + req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields)) + avail_qty = _parse_qty(proj.get('available_qty')) + + current = _active_decision(release_case, key) + # [STEP 1] 停用旧活动决定(放行资格与终态校验由调用方完成)。 + if current is not None: + current.is_active = False + current.updated_at = datetime.utcnow() + + status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE] + row = ShippingOrderReviewLineDecision( + review_case_id=int(release_case.id), + draft_line_id=key, + line_index=draft_line.get('_line_index'), + decision_version=_next_version(release_case, key), + decision_code=DECISION_RELEASE_SHORTAGE, + decision_source=actor_type, + line_status=status, + is_active=True, + reason=str(reason or '').strip()[:2000] or None, + required_qty=str(req_qty) if req_qty is not None else None, + available_qty=str(avail_qty) if avail_qty is not None else ( + str(proj.get('available_qty') or '').strip() or None + ), + reservation_id=_line_reservation_id(draft_line, proj), + part_number=_line_part_number( + draft_line, + proj, + schema_fields=schema_fields, + ), + actor_user_id=int(actor_id) if actor_id is not None else None, + snapshot_json={ + 'decision_code': DECISION_RELEASE_SHORTAGE, + 'decision_source': actor_type, + 'required_qty': str(req_qty) if req_qty is not None else None, + 'available_qty': str(avail_qty) if avail_qty is not None else None, + 'draft_line_id': key, + 'release_field_values': release_values, + 'release_required_fields': release_required_fields, + # 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。 + 'release_evidence_scope': release_evidence_scope, + **({'auto_release': True} if auto_release else {}), + }, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow(), + ) + db.session.add(row) + # [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。 + db.session.flush() + # [BE-结案-豁免] 放行是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。 + _sync_confirmed_task_fulfillment_gates( + case=release_case, + actor_id=actor_id, + trigger='inventory_shortage_released', + ) + + from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + + record_fulfillment_audit( + event_type='review_line_fulfillment_decided', + aggregate_type='order_review_case', + aggregate_id=str(release_case.case_no), + action=DECISION_RELEASE_SHORTAGE, + actor_type=actor_type, + actor_id=int(actor_id) if actor_id is not None else None, + review_case_no=str(release_case.case_no), + run_no=str(release_case.run.run_no) if release_case.run is not None else None, + metadata={ + 'draft_line_id': key, + 'decision_code': DECISION_RELEASE_SHORTAGE, + 'decision_version': int(row.decision_version), + 'line_status': status, + 'release_field_count': len(release_values), + **({'auto_release': True} if auto_release else {}), + }, + before=_serialize_decision(current) if current is not None else None, + after=_serialize_decision(row), + source='order_review_fulfillment_decision', + ) + return row + + def decide_review_line_fulfillment( *, user_id: int, @@ -1100,7 +1308,9 @@ def decide_review_line_fulfillment( draft_line_id: 草稿行键。 decision_code: 决定码。 reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。 - release_field_values: 短缺放行时模板行级库存字段的人工补录值。 + release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照 + release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源), + release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。 expected_draft_version: 可选草稿乐观锁。 actor_is_admin: 是否管理员(重开授权)。 @@ -1200,93 +1410,94 @@ def decide_review_line_fulfillment( details={'draft_line_id': key}, ) release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index') - release_template_fields = _shortage_release_required_fields( - task=task, - line_index=release_line_index, - inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None, - inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None, - ) if task is not None else [] - release_required_fields = _manual_required_release_fields(release_template_fields) - release_values = _validate_inventory_shortage_release_fields( - required_fields=release_required_fields, - supplied_values=release_field_values or {}, - ) - else: - release_required_fields = [] - release_values = {} - - # [STEP 1] 停用旧活动决定 - if current is not None: - current.is_active = False - current.updated_at = datetime.utcnow() - - status = _STATUS_BY_DECISION.get(code, 'pending_decision') - row = ShippingOrderReviewLineDecision( - review_case_id=int(case.id), - draft_line_id=key, - line_index=draft_line.get('_line_index'), - decision_version=_next_version(case, key), - decision_code=code, - decision_source='user', - line_status=status, - is_active=True, - reason=str(reason or '').strip()[:2000] or None, - required_qty=str(req_qty) if req_qty is not None else None, - available_qty=str(avail_qty) if avail_qty is not None else ( - str(proj.get('available_qty') or '').strip() or None - ), - reservation_id=_line_reservation_id(draft_line, proj), - part_number=_line_part_number( - draft_line, - proj, - schema_fields=schema_fields, - ), - actor_user_id=int(user_id), - snapshot_json={ - 'decision_code': code, - 'decision_source': 'user', - 'required_qty': str(req_qty) if req_qty is not None else None, - 'available_qty': str(avail_qty) if avail_qty is not None else None, - 'draft_line_id': key, - 'release_field_values': release_values, - 'release_required_fields': release_required_fields, - }, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow(), - ) - db.session.add(row) - # [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。 - db.session.flush() - if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}: - # [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。 - _sync_confirmed_task_fulfillment_gates( - case=case, + # [STEP] 短缺放行统一走共享执行体:证据字段解析、全量字段落库、停用旧决定、 + # 门禁同步与审计均在 _apply_shortage_line_release 内完成(人工与系统自动放行 + # 同一条链路,行为不变)。无 task 时上方放行资格校验已拒绝(无事实且无 RPA + # 终态失败豁免),不会到达此处。 + row = _apply_shortage_line_release( + task, + release_line_index, + release_field_values or {}, + actor_type='user', actor_id=int(user_id), - trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed', + case=case, + reason=reason, ) + status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE] + else: + # [STEP 1] 停用旧活动决定 + if current is not None: + current.is_active = False + current.updated_at = datetime.utcnow() - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + status = _STATUS_BY_DECISION.get(code, 'pending_decision') + row = ShippingOrderReviewLineDecision( + review_case_id=int(case.id), + draft_line_id=key, + line_index=draft_line.get('_line_index'), + decision_version=_next_version(case, key), + decision_code=code, + decision_source='user', + line_status=status, + is_active=True, + reason=str(reason or '').strip()[:2000] or None, + required_qty=str(req_qty) if req_qty is not None else None, + available_qty=str(avail_qty) if avail_qty is not None else ( + str(proj.get('available_qty') or '').strip() or None + ), + reservation_id=_line_reservation_id(draft_line, proj), + part_number=_line_part_number( + draft_line, + proj, + schema_fields=schema_fields, + ), + actor_user_id=int(user_id), + snapshot_json={ + 'decision_code': code, + 'decision_source': 'user', + 'required_qty': str(req_qty) if req_qty is not None else None, + 'available_qty': str(avail_qty) if avail_qty is not None else None, + 'draft_line_id': key, + 'release_field_values': {}, + 'release_required_fields': [], + 'release_evidence_scope': None, + }, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow(), + ) + db.session.add(row) + # [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。 + db.session.flush() + if code == DECISION_CLOSE: + # [BE-结案-豁免] 结案是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。 + _sync_confirmed_task_fulfillment_gates( + case=case, + actor_id=int(user_id), + trigger='line_fulfillment_closed', + ) - record_fulfillment_audit( - event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided', - aggregate_type='order_review_case', - aggregate_id=str(case.case_no), - action=code, - actor_type='user', - actor_id=int(user_id), - review_case_no=str(case.case_no), - run_no=str(case.run.run_no) if case.run is not None else None, - metadata={ - 'draft_line_id': key, - 'decision_code': code, - 'decision_version': int(row.decision_version), - 'line_status': status, - 'release_field_count': len(release_values), - }, - before=_serialize_decision(current) if current is not None else None, - after=_serialize_decision(row), - source='order_review_fulfillment_decision', - ) + from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + + record_fulfillment_audit( + event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action=code, + actor_type='user', + actor_id=int(user_id), + review_case_no=str(case.case_no), + run_no=str(case.run.run_no) if case.run is not None else None, + metadata={ + 'draft_line_id': key, + 'decision_code': code, + 'decision_version': int(row.decision_version), + 'line_status': status, + 'release_field_count': 0, + }, + before=_serialize_decision(current) if current is not None else None, + after=_serialize_decision(row), + source='order_review_fulfillment_decision', + ) from app.services.shipping_notice.order_review_resume_service import ( attach_resume_outcome, @@ -1311,6 +1522,113 @@ def decide_review_line_fulfillment( return attach_resume_outcome(payload, resume) +def _active_decision_line_indexes(task: ShippingNotice) -> set[int]: + """读取当前任务全部活动行决定的 line_index(含 release/close/fulfill 等一切决定)。 + + 核心逻辑:自动放行只处理「无任何活动决定」的行——已放行、已结案、已入波次或 + 已有其他人工决定的行一律跳过,保证幂等且绝不自动撤销既有决定(与 + ``_released_snapshot_line_ids_for_task`` 同款 Case 反查口径)。 + """ + from app.models import ShippingOrderReviewCase + + if getattr(task, 'id', None) is None: + return set() + rows = ( + ShippingOrderReviewLineDecision.query + .join( + ShippingOrderReviewCase, + ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id, + ) + .filter( + ShippingOrderReviewCase.confirmed_task_id == int(task.id), + ShippingOrderReviewLineDecision.is_active.is_(True), + ShippingOrderReviewLineDecision.line_index.isnot(None), + ) + .all() + ) + return {int(row.line_index) for row in rows} + + +def auto_release_part_fallback_shortages( + task: ShippingNotice, + *, + actor_id: int | None = None, +) -> list[int]: + """ + 匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。 + + 核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可 + 自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工 + 路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动 + 履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销 + 既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。 + + Args: + task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。 + actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。 + + Returns: + 自动放行的 line_index 列表(按行号升序)。 + """ + from app.services.shipping_notice.line_inventory_match_projection import ( + load_current_match_facts_by_task, + ) + + task_id = getattr(task, 'id', None) + if task_id is None: + return [] + facts = load_current_match_facts_by_task(int(task_id)) + if not facts: + return [] + decided_indexes = _active_decision_line_indexes(task) + ordered_facts = sorted( + (fact for fact in facts.values() if fact.get('line_index') is not None), + key=lambda fact: int(fact['line_index']), + ) + released: list[int] = [] + for fact in ordered_facts: + line_index = int(fact['line_index']) + try: + if line_index in decided_indexes: + continue + if not _is_shortage_match_fact(fact): + continue + required = _parse_qty(fact.get('required_qty')) + part_total = _parse_qty(fact.get('part_available_qty')) + if required is None or part_total is None or part_total < required: + # 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。 + continue + fields, evidence_scope = _shortage_release_required_fields( + task=task, + line_index=line_index, + inventory_snapshot_id=fact.get('inventory_snapshot_id'), + inventory_source_code=fact.get('inventory_source_code'), + ) + if any(bool(field.get('requires_manual')) for field in fields): + # 证据字段无法唯一取值(requires_manual 残留)→ 降级人工放行,补录要求保留。 + continue + auto_values = { + str(field.get('field_id') or ''): ( + None if field.get('value') is None else str(field.get('value')) + ) + for field in fields + } + _apply_shortage_line_release( + task, + line_index, + auto_values, + evidence_scope=evidence_scope, + actor_type='system', + actor_id=actor_id, + auto_release=True, + ) + released.append(line_index) + except ConflictError: + # 证据不可解析(无源/模板未发布/无快照/草稿行缺失)→ 维持人工路径,不中断其余行。 + continue + return released + + def close_remaining_fulfillment( *, user_id: int, diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index a134e5c5..5080cb3b 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -352,6 +352,13 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: continue current = gate break + facts_before = ( + execution.last_passed_gate_code, + execution.current_gate_code, + execution.primary_next_action_code, + execution.responsible_party, + execution.status, + ) execution.last_passed_gate_code = last_passed if current is None: execution.current_gate_code = None @@ -359,7 +366,16 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: execution.responsible_party = None if execution.status not in {'cancelled', 'failed'}: execution.status = 'completed' - _sync_order_task_stage_after_gate_refresh(execution) + _sync_order_task_stage_after_gate_refresh( + execution, + facts_changed=facts_before != ( + execution.last_passed_gate_code, + execution.current_gate_code, + execution.primary_next_action_code, + execution.responsible_party, + execution.status, + ), + ) return execution.current_gate_code = current.gate_code execution.primary_next_action_code = current.next_action_code @@ -376,10 +392,23 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: # [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读 # 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。 # 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。 - _sync_order_task_stage_after_gate_refresh(execution) + _sync_order_task_stage_after_gate_refresh( + execution, + facts_changed=facts_before != ( + execution.last_passed_gate_code, + execution.current_gate_code, + execution.primary_next_action_code, + execution.responsible_party, + execution.status, + ), + ) -def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None: +def _sync_order_task_stage_after_gate_refresh( + execution: ShippingProcessExecution, + *, + facts_changed: bool = False, +) -> None: """Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。""" if getattr(execution, 'task_id', None) is None: return @@ -397,10 +426,38 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio if task is not None else None ) if notice is not None: + version_before = int(getattr(task, 'progress_version', 0) or 0) sync_order_task_stage_for_notice(notice, order_task=task) + # 库存缺口/文件就绪等 Gate 事实变化但映射后 stage/status 未变时,仍须推进 + # progress_version:工作台以该版本变化触发 [REFRESH_ON_CHANGE] 重拉任务详情, + # 版本冻结会让行级可用数量/缺口停留在上一次快照。 + if ( + facts_changed + and task is not None + and int(getattr(task, 'progress_version', 0) or 0) == version_before + ): + _bump_order_task_progress_version(task) elif task is not None: # Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。 task.stage = task.stage or 'notification_preparation' + # 无 Notice 绑定(通知准备/库存匹配常态)时上方 Notice 映射不存在,Gate 每次真实 + # 推进都必须经中央写入口递增 progress_version,否则统一投影版本冻结, + # 前端轮询只更新右卡门禁、任务详情表格永不刷新。 + if facts_changed: + _bump_order_task_progress_version(task) + + +def _bump_order_task_progress_version(task: ShippingOrderTask) -> None: + """Gate 事实已变化但 stage/status 无值可变时,经中央写入口强制递增进度版本。""" + from app.services.shipping_notice.order_task_service import sync_order_task_processing_state + + sync_order_task_processing_state( + task, + bump_progress=True, + force_progress_bump=True, + reason_code='gate_facts_advanced', + source='process_gate_service', + ) def ensure_execution_for_workflow_version( diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index d7cdf65e..35a3e855 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -812,6 +812,11 @@ def apply_user_projection_fields( return 'waiting_human' if unverified_upload_terminal: return 'waiting_human' + if gate_status in {'queued', 'running', 'waiting_external'}: + # Gate/Execution 在途 = 系统处理中:Notice 生成前 OT.status 会停留在建单前 + # 的 waiting_review,不得据此把 RPA 自动推进误报成待人工——前端把 + # waiting_human 视为终态并停止投影轮询,回调完成将永远无法被感知。 + return 'running' # 1) 终态短路:old_status completed/cancelled/failed if old_status == 'completed': return 'completed' diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index 3132401d..a246421e 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -8,6 +8,7 @@ services/shipping_notice/stp_line_inventory_match.py __source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 + 行结果另含料号兜底总量 part_available_qty(允许源内、忽略预约号与单位的二次汇总)。 """ from __future__ import annotations @@ -77,6 +78,37 @@ def _inventory_row_qty(row: dict[str, Any]) -> Decimal: return Decimal('0') +def _part_total_available_qty( + buckets: dict[tuple[str, str, str, str], dict[str, Any]], + *, + part: str, + allowed_source_codes: list[str], + has_candidate_scope: bool, +) -> Decimal | None: + """ + 按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。 + + Args: + buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。 + part: 归一化料号;空串返回 None。 + allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。 + has_candidate_scope: 行是否携带候选源范围事实。 + + Returns: + 料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。 + """ + if not part: + return None + total = Decimal('0') + for key, bucket in buckets.items(): + if key[1] != part: + continue + if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes: + continue + total += bucket['available_qty'] + return total + + def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None: """ 从冻结 Snapshot 读取 Header 级 reservation_id。 @@ -275,6 +307,9 @@ def match_order_lines_across_candidates( 核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定, 库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。 + 料号兜底:仅 not_found(预约不匹配)/ok/shortage 行额外下发 + ``part_available_qty``(行允许源内、忽略预约号、不限单位的料号总可用量); + 缺料号、invalid(超出候选范围)、multi_file_conflict、缺预约行不写该键,由下游按缺失→None 处理。 Args: order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。 @@ -348,6 +383,13 @@ def match_order_lines_across_candidates( else True ) ] + # [STEP] 料号兜底总量:行允许源内、忽略预约号、不限单位,供预约不匹配/缺口行自动放行判断。 + part_total = _part_total_available_qty( + buckets, + part=part, + allowed_source_codes=allowed_source_codes, + has_candidate_scope=has_candidate_scope, + ) if not effective or not part: disposition = 'not_found' @@ -408,6 +450,7 @@ def match_order_lines_across_candidates( 'required_qty': float(required), 'available_qty': 0.0, 'shortage_qty': float(required), + 'part_available_qty': float(part_total) if part_total is not None else None, 'line_status': 'shortage', 'disposition': disposition, 'resolved_inventory_source_code': None, @@ -431,6 +474,7 @@ def match_order_lines_across_candidates( 'required_qty': float(required), 'available_qty': float(available), 'shortage_qty': 0.0, + 'part_available_qty': float(part_total) if part_total is not None else None, 'line_status': 'ok', 'disposition': disposition, 'resolved_inventory_source_code': resolved_source, @@ -453,6 +497,7 @@ def match_order_lines_across_candidates( 'required_qty': float(required), 'available_qty': float(available), 'shortage_qty': float(max(required - available, Decimal('0'))), + 'part_available_qty': float(part_total) if part_total is not None else None, 'line_status': 'partial' if available > 0 else 'shortage', 'disposition': disposition, 'resolved_inventory_source_code': resolved_source, diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 22b4cc55..cfe8babd 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -16,6 +16,7 @@ services/shipping_notice/ui_state.py + 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT), 行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源); 短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line; + prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列; 下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass); 用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要; project_notice_available_actions 供货代上传聚合行内菜单轻量消费。 @@ -950,7 +951,8 @@ def _build_stage_context( release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact) if release_line_index is None and getattr(snapshot_line, 'position', None) is not None: release_line_index = int(snapshot_line.position) - release_template_fields = _shortage_release_required_fields( + # scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。 + release_template_fields, _evidence_scope = _shortage_release_required_fields( task=order_task, line_index=release_line_index, inventory_snapshot_id=release_snapshot_id, @@ -976,6 +978,7 @@ def _build_stage_context( 'required_qty': required_qty, 'available_qty': inv_view.get('available_qty'), 'shortage_qty': inv_view.get('shortage_qty'), + 'part_available_qty': inv_view.get('part_available_qty'), 'source_code': source_code, 'selected_source_code': selected_source_code, 'status': inv_view.get('user_line_status'), diff --git a/backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py b/backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py new file mode 100644 index 00000000..b9a4a071 --- /dev/null +++ b/backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py @@ -0,0 +1,25 @@ +"""add part_available_qty to shipping_notice_line_inventory_matches + +Revision ID: 0a575f3afc32 +Revises: 9e5045511198 +Create Date: 2026-10-09 14:46:05.242283 + +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '0a575f3afc32' +down_revision = '9e5045511198' +branch_labels = None +depends_on = None + + +def upgrade(): + # 本迁移由 autogenerate 生成后人工裁剪:本地 dev 库与模型存在大量与本任务无关的 + # 结构漂移,仅保留目标表新列(料号维度总可用量),其余漂移由后续专项迁移处理。 + op.add_column('shipping_notice_line_inventory_matches', sa.Column('part_available_qty', sa.String(32), nullable=True)) + + +def downgrade(): + op.drop_column('shipping_notice_line_inventory_matches', 'part_available_qty') diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index 3473e8d4..b6ed3b11 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -625,6 +625,41 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h assert called["rpa"] == 0 +def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers): + """空 source_codes → 400(批量端点参数卡控)。""" + response = client.post( + f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, json={"source_codes": []}, + ) + assert response.status_code == 400 + + +def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch): + """批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。""" + captured: dict = {} + + def fake_batch(*, source_codes, business_date, reason): + captured.update(source_codes=source_codes, business_date=business_date, reason=reason) + return { + "ok": True, "triggered": True, "trigger_path": "/tmp/trigger.json", + "results": [{"source_code": code, "ok": True} for code in source_codes], + } + + monkeypatch.setattr( + "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch, + ) + response = client.post( + f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, + json={"source_codes": ["DSV360_AWSDU", "DSV360_AWSSG"]}, + ) + assert response.status_code == 200 + body = response.get_json()["data"] + # [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。 + assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"] + assert captured["reason"] == "transfer_retry_receipt" + assert body["ok"] is True and body["triggered"] is True + assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"] + + def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps): """运营指标端点:返回 Run/明细/待处理/通知失败结构。""" response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py index a09636fa..bd32a88d 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py @@ -75,10 +75,22 @@ def test_invalid_quantity_rejected(): parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc")) -def test_zero_quantity_rejected(): - """0 数量必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0")) +def test_zero_quantity_stamped_row_skipped(): + """零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。""" + parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0")) + assert parsed == [] + + +def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed(): + """合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。""" + rows = [ + dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0", + receipt_date="2026-10-01 14:37:43"), + dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"), + ] + parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) + assert [row.row_no for row in parsed] == [789] + assert parsed[0].invoice_no == "INV-002" def test_negative_quantity_rejected(): @@ -121,3 +133,19 @@ def test_error_carries_row_details(): parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc")) details = excinfo.value.details assert any(str(item.get("row_no")) == "77" for item in details.get("rows", [])) + + +def test_schema_error_message_carries_row_details(): + """诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。""" + rows = [ + dict(VALID_ROW, row_no=5, invoice_no=""), + dict(VALID_ROW, row_no=9, receipt_quantity="abc"), + ] + with pytest.raises(ReceiptFileSchemaError) as exc_info: + parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) + # [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因; + # 明细同时保留在 details.rows 供管理端展示。 + text = str(exc_info.value) or (exc_info.value.message or "") + assert "row 5" in text and "missing_invoice_no" in text + detail_rows = (exc_info.value.details or {}).get("rows") or [] + assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py index 9fe39c4a..acff5854 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -1,11 +1,13 @@ """真实收料 RPA 触发服务测试。 -用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者; - 触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); +用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit + 并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); 配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。 -依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、 +依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、 既有测试种子(ShippingRpaProfile/ShippingInventorySource)。 -逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。 +逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False; + 批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批, + parse_failed 先本地重解析不触发 RPA)。 """ from __future__ import annotations @@ -13,7 +15,10 @@ from __future__ import annotations import pytest from app.models import ShippingInventorySource, ShippingReceiptReportConfig -from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa +from app.services.in_transit_transfer.receipt_trigger_service import ( + trigger_receipt_rpa, + trigger_receipt_rpa_batch, +) @pytest.fixture @@ -170,3 +175,157 @@ def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, rec ShippingReceiptRpaUnitRun.id.desc()).first() assert unit.status == "failed" assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE" + + +# --------------------------------------------------------------------------- +# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件, +# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。 +# --------------------------------------------------------------------------- + +@pytest.fixture +def second_receipt_source(app): + """再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定 + 解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。""" + from app import db + from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig + + seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + profile = ShippingRpaProfile( + profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs', + login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'}, + ) + source = ShippingInventorySource( + source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs', + rpa_profile=profile, + parsing_profile=seed.parsing_profile, excel_template=seed.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG', + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + enabled=True, + ) + db.session.add_all([profile, source]) + db.session.flush() # 先取 source.id(新建对象 flush 前无主键) + config = ShippingReceiptReportConfig( + inventory_source_id=source.id, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], + ) + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source): + """多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。""" + from app.models import ShippingReceiptRpaUnitRun + + calls: list = [] + + def fake_writer(run_no, units, payload=None): + calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}}) + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_receipt_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09', + reason='transfer_retry_receipt', writer=fake_writer, + ) + # [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。 + assert len(calls) == 1 + assert outcome['ok'] is True and outcome['triggered'] is True + assert calls[0]['run_no'].startswith('TRIG-BATCH-') + assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG'] + assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1' + # 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。 + callback_ids = {u['callback_id'] for u in calls[0]['units']} + assert len(callback_ids) == 2 + rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() + assert {row.status for row in rows} == {'awaiting_rpa'} + assert all(row.schedule_run_id is None for row in rows) + assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']} + + +def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source): + """单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。""" + captured: dict = {} + + def fake_writer(run_no, units, payload=None): + captured['units'] = units + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_receipt_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09', + writer=fake_writer, + ) + # [断言意图] 来源级隔离:坏源不炸整批,trigger 只含有效源;结果逐源如实分层。 + assert outcome['ok'] is True and outcome['triggered'] is True + assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU'] + by_code = {item['source_code']: item for item in outcome['results']} + assert by_code['DSV360_AWSDU']['ok'] is True + assert by_code['DSV360_NOPE']['ok'] is False + assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING' + + +def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app): + """全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。""" + outcome = trigger_receipt_rpa_batch( + source_codes=['DSV360_NOPE'], business_date='2026-10-09', + writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE' + + +def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source): + """trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。""" + from app.models import ShippingReceiptRpaUnitRun + + outcome = trigger_receipt_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09', + writer=lambda *a, **k: None, + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE' + rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() + assert {row.status for row in rows} == {'failed'} + assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'} + + +def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch): + """parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。""" + statuses = { + 'DSV360_AWSDU': [ + {'file_status': 'parse_failed', 'file_sha256': 'abc'}, + {'file_status': 'ready', 'file_sha256': 'abc'}, + ], + } + + def fake_resolve(*, source_code): + # [断言意图] 解析失败分层:首次投影 parse_failed 触发本地重解析, + # sync 后再查投影回 ready——该来源不得进入 batch trigger。 + queue = statuses.get(source_code) + if queue and len(queue) > 1: + return queue.pop(0) + return queue[0] if queue else {'file_status': 'none'} + + monkeypatch.setattr( + 'app.services.in_transit_transfer.source_file_status.resolve_source_file_status', fake_resolve, + ) + synced: list = [] + monkeypatch.setattr( + 'app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback', + lambda *, source_code, business_date, now: synced.append(source_code) or True, + ) + + def fake_writer(run_no, units, payload=None): + raise AssertionError('reparsed source must not be triggered via RPA') + + outcome = trigger_receipt_rpa_batch( + source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer, + ) + # [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。 + assert synced == ['DSV360_AWSDU'] + assert outcome['ok'] is True and outcome['triggered'] is False + assert outcome['results'] == [{ + 'source_code': 'DSV360_AWSDU', 'ok': True, 'reparsed': True, 'file_status': 'ready', + }] diff --git a/backend/tests/services/in_transit_transfer/test_source_file_status.py b/backend/tests/services/in_transit_transfer/test_source_file_status.py index 8adb03f2..a42df15e 100644 --- a/backend/tests/services/in_transit_transfer/test_source_file_status.py +++ b/backend/tests/services/in_transit_transfer/test_source_file_status.py @@ -207,3 +207,14 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): clear_receipt_parse_failure(report=report) db.session.commit() assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready" + + +def test_empty_unit_is_no_data(app, receipt_unit_run): + """空数据单元(抓取成功、当日无收料记录)→ no_data,不得与抓取失败混淆。""" + from app import db + + receipt_unit_run.status = 'empty' + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'no_data' + assert status['has_ready_file'] is False diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 37248f97..9f31bc09 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -448,3 +448,167 @@ def test_fill_multi_value_js_uses_entry_text_not_bare_text(): # 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。 assert "desiredValues.includes(text" not in source assert "normalize(text)" not in source or "entryText" in source + + +class _RecordingFrame: + """脚本化 frame:evaluate 返回预置结果或抛预置异常,并记录收到的 label。""" + + def __init__(self, result=None, error: Exception | None = None): + self._result = result + self._error = error + self.calls: list[str] = [] + + def evaluate(self, script: str, label: str): + self.calls.append(label) + if self._error is not None: + raise self._error + return self._result + + +class _RecordingPage: + def __init__(self, frames): + self.frames = frames + + +_STRUCTURAL_CONTROLS = { + "text": "#ReportViewerMain_ctl08_ctl15_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl15_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown", +} + + +def test_structural_resolver_hit_returns_controls_and_trims_label(): + """命中 frame 返回三件套;label 先 trim 再传入页面脚本。""" + module = _load_module() + early = _RecordingFrame(result=None) + hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS)) + page = _RecordingPage([early, hit]) + + got = module.resolve_parameter_controls_structural(page, " Owner ") + + assert got == _STRUCTURAL_CONTROLS + assert hit.calls == ["Owner"] + + +def test_structural_resolver_all_frames_miss_or_error_returns_none(): + """全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。""" + module = _load_module() + page = _RecordingPage([ + _RecordingFrame(result=None), + _RecordingFrame(error=RuntimeError("execution context destroyed")), + _RecordingFrame(result=None), + ]) + assert module.resolve_parameter_controls_structural(page, "Owner") is None + + +def test_structural_resolver_empty_label_short_circuits(): + """空标签短路:不打扰任何 frame。""" + module = _load_module() + frame = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS)) + page = _RecordingPage([frame]) + assert module.resolve_parameter_controls_structural(page, " ") is None + assert frame.calls == [] + + +def test_structural_resolver_none_page_returns_none(): + """无页面上下文(纯函数调用):直接返回 None。""" + module = _load_module() + assert module.resolve_parameter_controls_structural(None, "Owner") is None + + +def test_fill_multi_select_template_miss_falls_back_to_structural(monkeypatch): + """接线:报表模板未命中 Owner 时,落到结构性解析并把三件套传入 multi_value 填充。 + + [断言意图] 2026-10-08 事故回归:Owner@Receipt Detail@AWSRTM 未登记 ctl15 模板时, + 不得静默失败弃填(导致全货主巨报表渲染超时),必须结构性解析后正常填充。 + """ + module = _load_module() + captured: dict[str, object] = {} + + def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all): + captured.update(config_override) + return True + + monkeypatch.setattr(module, "resolve_parameter_controls", lambda *a, **k: {}) + probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS)) + page = _RecordingPage([probe]) + monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill) + + ok = module.fill_dsv_multi_select_parameter( + page, "Owner", ["CRTM-0000000100"], select_all=False, + browser_timeout_ms=lambda: 3_000, + report_name="Receipt Detail", program_label="AWSRTM", + ) + + assert ok is True + assert captured == {"control": "multi_value", **_STRUCTURAL_CONTROLS} + assert probe.calls == ["Owner"] + + +def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch): + """优先级:结构性解析优先(ctl 编号随渲染漂移,注册表 ctl 条目只作回退)。 + + [断言意图] 结构性命中时使用结构性三件套、注册表回退不被消费; + 结构性未命中时才回退注册表控件。 + """ + module = _load_module() + registry_controls = { + "text": "#ReportViewerMain_ctl08_ctl29_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl29_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown", + } + resolve_calls: list[tuple] = [] + monkeypatch.setattr( + module, "resolve_parameter_controls", + lambda *a, **k: (resolve_calls.append(a), dict(registry_controls))[1], + ) + probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS)) + page = _RecordingPage([probe]) + captured: dict[str, object] = {} + + def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all): + captured.update(config_override) + return True + + monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill) + + ok = module.fill_dsv_multi_select_parameter( + page, "Warehouse", ["RTM"], select_all=False, + browser_timeout_ms=lambda: 3_000, + report_name="Receipt Detail", program_label="AWSRTM", + ) + + assert ok is True + assert captured.get("text") == _STRUCTURAL_CONTROLS["text"] # 结构性解析优先生效 + assert resolve_calls == [] # 结构性命中:注册表回退未被消费 + + # 结构性未命中 → 回退注册表控件 + probed = _RecordingFrame(result=None) + page = _RecordingPage([probed]) + captured.clear() + ok = module.fill_dsv_multi_select_parameter( + page, "Warehouse", ["RTM"], select_all=False, + browser_timeout_ms=lambda: 3_000, + report_name="Receipt Detail", program_label="AWSRTM", + ) + assert ok is True + assert captured.get("text") == registry_controls["text"] # 回退到注册表 + assert probed.calls == ["Warehouse"] + + +def test_multi_value_already_set_set_equality_not_substring(): + """2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV, + 目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。""" + module = _load_module() + all_owners_csv = ",".join(f"CRTM-0000000{n:03d}" for n in range(5, 449)) + + # [断言意图] 目标值是全选 CSV 的"子串"但非"全集"——不得判已设置(旧 bug 行为)。 + assert module._multi_value_already_set(all_owners_csv, ["CRTM-0000000100"]) is False + # 完全相等的选中集合才允许跳过。 + assert module._multi_value_already_set("CRTM-0000000100", ["CRTM-0000000100"]) is True + assert module._multi_value_already_set("CRTM-0000000100, CRTM-0000000101", + ["CRTM-0000000101", "CRTM-0000000100"]) is True + # 边界:空当前值/空目标不判已设置;大小写与空白不敏感。 + assert module._multi_value_already_set("", ["CRTM-0000000100"]) is False + assert module._multi_value_already_set(all_owners_csv, []) is False + assert module._multi_value_already_set(" crtm-0000000100 ", ["CRTM-0000000100"]) is True diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index b5a42f31..5511262b 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -29,6 +29,7 @@ _RPA_MODULE_PATHS = { "dsv_auth": "connectors/dsv/dsv_auth.py", "dsv_session": "connectors/dsv/dsv_session.py", "dsv_debug": "connectors/dsv/dsv_debug.py", + "dsv_report_parameters": "connectors/dsv/dsv_report_parameters.py", } @@ -449,6 +450,7 @@ def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch): monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock()) monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock()) monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock()) + monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock()) worker._navigate_dsv_to_report_form( page, @@ -581,6 +583,7 @@ def test_navigate_dsv_to_report_form_retries_once_with_home_reset(monkeypatch): monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock()) monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock()) monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock()) + monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock()) reset = MagicMock() monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset) monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock()) @@ -608,6 +611,7 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch): monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock()) monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock()) monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock()) + monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock()) reset = MagicMock() monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset) chain = MagicMock() @@ -630,6 +634,177 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch): assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list) +def _fake_dsv_page_with_frames(*frames): + page = MagicMock() + page.frames = list(frames) + return page + + +def _fake_dsv_frame(url: str, body: str): + frame = MagicMock() + frame.url = url + frame.locator.return_value.inner_text.return_value = body + return frame + + +def test_assert_dsv_report_viewer_identity_passes_for_expected_program(): + """SSRS viewer 标题含 program_label 时应判定打开了目标报表,直接放行。""" + worker = _load_dsv_report_export() + viewer = _fake_dsv_frame( + "https://s360.dbschenker.com/S360Reports/SSRS/f26275b5?token=x&isLegacy=true", + "On Hand Inventory By Location AWS > Moerdijk > AWSRTM favorite_border", + ) + page = _fake_dsv_page_with_frames(viewer) + + worker._assert_dsv_report_viewer_identity( + page, + {"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}}, + timeout_ms=1000, + ) + + +def test_assert_dsv_report_viewer_identity_raises_on_wrong_program(): + """viewer 载入 Bison 3lv(AWS > Bison > AWSBI)时应报身份不匹配。 + + 2026-10-09 AWSRTM 事故回归:portal 顶层 Recent Reports 文本同样含 AWSRTM, + 门禁只认 /s360reports/ssrs/ viewer frame,顶层的 AWSRTM 字样不得误判为匹配。 + """ + worker = _load_dsv_report_export() + portal = _fake_dsv_frame( + "https://s360.dbschenker.com/main/portal/frame/reports/x", + "RECENT REPORTS On Hand Inventory By Location (Moerdijk > AWSRTM)", + ) + viewer = _fake_dsv_frame( + "https://s360.dbschenker.com/S360Reports/SSRS/d40ada0a?token=x&isLegacy=true", + "On Hand Inventory By Location 3lv AWS > Bison > AWSBI favorite_border", + ) + page = _fake_dsv_page_with_frames(portal, viewer) + + import pytest + + with pytest.raises(RuntimeError, match="identity mismatch"): + worker._assert_dsv_report_viewer_identity( + page, + {"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}}, + timeout_ms=1000, + ) + + +def test_assert_dsv_report_viewer_identity_skips_without_program_label(): + """配置缺 program_label 时应跳过身份校验(保持旧行为,不因无身份信息而失败)。""" + worker = _load_dsv_report_export() + page = _fake_dsv_page_with_frames() + + worker._assert_dsv_report_viewer_identity(page, {"navigation": {"report_name": "X"}}, timeout_ms=1000) + + +def test_navigate_dsv_to_report_form_resets_home_when_viewer_identity_mismatch(monkeypatch): + """viewer 载错报表(身份不匹配)时应整页 reset 后重导一次(2026-10-09 AWSRTM 串报修复)。""" + worker = _load_dsv_report_export() + page = MagicMock() + monkeypatch.setattr(worker, "_env", lambda key, default=None: "") + monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock()) + monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock()) + monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock()) + monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock()) + monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock()) + identity = MagicMock(side_effect=[RuntimeError("identity mismatch"), None]) + monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", identity) + reset = MagicMock() + monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset) + monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock()) + + source = { + "entry_url": "https://s360.dbschenker.com/main/portal", + "navigation": { + "program_group": "Moerdijk", + "program_label": "AWSRTM", + "report_group": "Inventory", + "report_name": "On Hand Inventory by Location", + }, + } + assert worker._navigate_dsv_to_report_form(page, source) == "On Hand Inventory by Location" + assert identity.call_count == 2 + reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal") + + +def test_fill_dsv_filter_returns_false_when_all_paths_fail(monkeypatch): + """配置了值但 multi_value/select/脚本/fill 全部失败时应返回 False(FILL-FAIL-FAST 契约)。""" + params = _load_rpa_module("dsv_report_parameters") + monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=False)) + monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False)) + monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: []) + monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None)) + monkeypatch.setattr(params, "_probe_report_parameter_controls", lambda page: {}) + + result = params.fill_dsv_filter_if_needed( + MagicMock(), + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + "RTM", + env=lambda key, default=None: "", + browser_timeout_ms=lambda: 1000, + report_name="On Hand Inventory by Location", + ) + assert result is False + + +def test_fill_dsv_filter_returns_true_on_success_and_legitimate_skip(monkeypatch): + """填充成功或合法跳过(值为空)应返回 True,不得被包装层误判为失败。""" + params = _load_rpa_module("dsv_report_parameters") + # JDA 模板下 Warehouse 是 multi_value 控件:mock 主路径成功即可验证 True 契约。 + monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=True)) + monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False)) + monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: []) + monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None)) + + filled = params.fill_dsv_filter_if_needed( + MagicMock(), + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + "RTM", + env=lambda key, default=None: "", + browser_timeout_ms=lambda: 1000, + report_name="On Hand Inventory by Location", + ) + skipped = params.fill_dsv_filter_if_needed( + MagicMock(), + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + None, + env=lambda key, default=None: "", + browser_timeout_ms=lambda: 1000, + report_name="On Hand Inventory by Location", + ) + assert filled is True + assert skipped is True + + +def test_fill_dsv_filter_wrapper_raises_on_fill_failure(monkeypatch): + """包装层在 fill 返回 False 时必须抛错中止本源(2026-10-09 静默吞掉曾连环误报)。""" + worker = _load_dsv_report_export() + fake_module = MagicMock() + fake_module.fill_dsv_filter_if_needed.return_value = False + monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock()) + monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module) + + import pytest + + with pytest.raises(RuntimeError, match="fill failed"): + worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM") + + +def test_fill_dsv_filter_wrapper_silent_on_fill_success(monkeypatch): + """fill 返回 True(已填充/合法跳过)时包装层不得抛错。""" + worker = _load_dsv_report_export() + fake_module = MagicMock() + fake_module.fill_dsv_filter_if_needed.return_value = True + monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock()) + monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module) + + worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM") + + def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch): """同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。""" worker = _load_dsv_report_export() @@ -696,6 +871,7 @@ def test_navigate_dsv_to_report_form_clicks_program_group_before_program_label(m lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)), ) monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock()) + monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock()) source = { "navigation": { diff --git a/backend/tests/test_line_inventory_match_persistence.py b/backend/tests/test_line_inventory_match_persistence.py index b1fbb997..b3ed9299 100644 --- a/backend/tests/test_line_inventory_match_persistence.py +++ b/backend/tests/test_line_inventory_match_persistence.py @@ -1,15 +1,17 @@ """ tests/test_line_inventory_match_persistence.py -用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。 -依赖:pytest、line_inventory_match_persistence。 -逻辑:纯单元;不写库。 +用途:锁定 disposition → match_result 映射、not_found/invalid_key 语义, + 及行级匹配事实落库契约(含料号兜底总量 part_available_qty)。 +依赖:pytest、line_inventory_match_persistence、app 夹具(persist 用例)。 +逻辑:映射用例纯单元;persist 用例写库(内存测试库),不触外部集成。 """ from __future__ import annotations from app.services.shipping_notice.line_inventory_match_persistence import ( map_disposition_to_match_codes, + persist_line_inventory_match_facts, ) @@ -54,3 +56,134 @@ def test_ok_and_shortage_are_matched_ready(): assert map_disposition_to_match_codes( disposition='shortage', part_number='A', reservation_id='B', ) == ('matched', 'ready') + + +# --------------------------------------------------------------------------- +# persist_line_inventory_match_facts 落库契约(依赖 app 夹具,写内存测试库) +# --------------------------------------------------------------------------- + + +def _make_snapshot_task(task_no: str): + """ + 构造含两行冻结快照的 OT 任务,供 persist 落库测试复用。 + + 核心逻辑:持久化按 order_snapshot_id → ShippingOrderSnapshot.lines 的 line_no + 解析 snapshot_line_id;第 1 行料号/预约号齐全,第 2 行缺料号 + (对齐匹配器「缺料号行不下发 part_available_qty 键」的真实产出,见 + test_shipping_stp_phase4_line_inventory_match.py 的兜底总量用例)。 + """ + from app import db + from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask + + task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=1, + order_data_version=1, + rule_versions_json={}, + source_manifest_json={}, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + lines = [ + {'line_no': 1, 'part_number': 'PN-1', 'reservation_id': '3000092917', 'qty': 8}, + {'line_no': 2, 'part_number': None, 'reservation_id': '3000092918', 'qty': 1}, + ] + for position, line in enumerate(lines): + db.session.add( + ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=position, + line_no=line['line_no'], + part_number=line['part_number'], + reservation_id=line['reservation_id'], + qty=line['qty'], + field_values_json={}, + ) + ) + task.order_snapshot_id = snapshot.id + db.session.flush() + return task + + +def _not_found_result(*, part_available_qty, line_index: int = 0) -> dict: + """ + 构造 not_found 行结果桩。 + + 核心逻辑:part_available_qty 传 None 时**不下发该键**(而非显式 None), + 对齐匹配器对 conflict/缺料号行「无键即无兜底」的契约;持久化必须按 + 无键 → NULL 处理。 + """ + result = { + 'line_index': line_index, + 'disposition': 'not_found', + 'part_number': 'PN-1', + 'reservation_id': '3000092917', + 'required_qty': 8.0, + 'available_qty': 0.0, + } + if part_available_qty is not None: + result['part_available_qty'] = part_available_qty + return result + + +def test_persist_writes_part_available_qty_for_not_found_line(app): + """预约不匹配行的料号兜底总量必须随匹配事实落库。""" + with app.app_context(): + task = _make_snapshot_task('OT-PART-AVAILABLE-NEW') + match_payload = { + 'line_results': [ + _not_found_result(part_available_qty=8.0), + _not_found_result(part_available_qty=None, line_index=1), + ], + 'resolutions': [], + } + rows = persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=None, + ) + # 断言意图:兜底总量字符串化落列 + assert str(rows[0].part_available_qty) == '8.0' + # 断言意图:无键/None 时必须落 NULL 而非 'None' + assert rows[1].part_available_qty is None + + +def test_persist_updates_part_available_qty_on_existing_row(app): + """同快照幂等更新时,料号兜底总量必须以最新匹配结果为准。""" + with app.app_context(): + task = _make_snapshot_task('OT-PART-AVAILABLE-UPDATE') + persist_line_inventory_match_facts( + task=task, + match_payload={ + 'line_results': [_not_found_result(part_available_qty=8.0)], + 'resolutions': [], + }, + inventory_snapshot_id=None, + ) + rows = persist_line_inventory_match_facts( + task=task, + match_payload={ + 'line_results': [_not_found_result(part_available_qty=13.0)], + 'resolutions': [], + }, + inventory_snapshot_id=None, + ) + # 断言意图:更新分支同样把新兜底总量字符串化落列 + assert str(rows[0].part_available_qty) == '13.0' + # 断言意图:更新时键缺失 → 回写 NULL,不得残留旧值或 'None' + rows = persist_line_inventory_match_facts( + task=task, + match_payload={ + 'line_results': [_not_found_result(part_available_qty=None)], + 'resolutions': [], + }, + inventory_snapshot_id=None, + ) + assert rows[0].part_available_qty is None + # 断言意图:同快照幂等更新,始终只有一条 current 事实 + assert len(rows) == 1 diff --git a/backend/tests/test_line_inventory_match_projection.py b/backend/tests/test_line_inventory_match_projection.py index 8d829af8..c7083d65 100644 --- a/backend/tests/test_line_inventory_match_projection.py +++ b/backend/tests/test_line_inventory_match_projection.py @@ -10,6 +10,7 @@ from __future__ import annotations from app.services.shipping_notice.line_inventory_match_projection import ( ACTION_CLOSE, + ACTION_RELEASE_SHORTAGE, ACTION_RETRY_MATCHING, ACTION_RETRY_PREPARATION, normalize_match_quantities, @@ -116,7 +117,9 @@ def test_shortage_actions_preparation_and_close_only(): user_line_status='shortage', ) assert inv == [ACTION_RETRY_PREPARATION] - assert line == [ACTION_CLOSE] + # 断言意图(既有用例修复):对齐已上线契约(eed1068ae)——短缺行除关闭外 + # 同时下发 release_inventory_shortage(填写原因放行),本用例原断言已过期。 + assert line == [ACTION_CLOSE, ACTION_RELEASE_SHORTAGE] def test_wave_created_hides_line_actions(): @@ -204,3 +207,28 @@ def test_user_status_maps_closed_and_system_ready(): stored_line_status='ready_to_fulfill', decision_source='system', ) == 'auto_fulfilling' + + +def test_view_exposes_part_available_qty_gated_by_ready(): + """料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。""" + base = { + 'match_result': 'not_found', 'inventory_status': 'ready', + 'required_qty': '8', 'available_qty': None, + 'inventory_snapshot_id': 1, 'matched_at': None, + 'inventory_source_code': 'DSV', 'detail_json': {}, + } + view = project_line_inventory_view( + has_formal_ot=True, fact={**base, 'part_available_qty': '9'}, + required_qty='8', stored_line_status=None, decision_source=None, + can_fulfill_complete_line=False, + ) + # 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。 + assert view['available_qty'] == '0' + assert view['part_available_qty'] == '9' + pending = project_line_inventory_view( + has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'}, + required_qty='8', stored_line_status=None, decision_source=None, + can_fulfill_complete_line=False, + ) + # 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。 + assert pending['part_available_qty'] is None diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 92f621db..abcffd5a 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -891,6 +891,31 @@ def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_read assert preparation["has_match_result"] is False +def test_preparation_lines_carry_part_available_qty(app) -> None: + """prep 行必须下发料号兜底总量,供前端新增「可用数量」列。""" + with app.app_context(): + task, line = _frozen_task_with_line( + task_no="OT-UI-PART-AVAILABLE", + reservation_id="RSV-PART-AVAIL", + part_number="PN-PART-AVAIL", + qty="8", + ) + # 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0, + match_result="matched", inventory_status="ready", required_qty="8", + available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9", + reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL", + inventory_source_code="DBS_DUB", is_current=True, + )) + db.session.commit() + + state = build_task_ui_state(task, include_stage_context=True) + prep_line = state["stage_context"]["preparation"]["lines"][0] + # 断言意图:ui_state 单源直透投影值,前端不做二次推导;不下发任何派生布尔标志。 + assert prep_line["part_available_qty"] == "9" + + def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None: """库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。""" from app.models import ShippingInventoryFile, ShippingTaskInventoryLink diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py index bc4c9747..4fec23da 100644 --- a/backend/tests/test_shipping_process_gate_service.py +++ b/backend/tests/test_shipping_process_gate_service.py @@ -459,6 +459,56 @@ def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_ex assert gate_execution.status == 'blocked' +def test_refresh_pointers_bumps_task_progress_version_without_notice(gate_execution): + """无 Notice 绑定时 Gate 指针事实变化必须递增 OT progress_version。 + + 复现:通知准备/库存匹配阶段 Notice 尚未生成,历史实现只回填 stage、不推进版本; + 统一投影 progress_version 冻结导致工作台 [REFRESH_ON_CHANGE] 永不重拉任务详情, + RPA 重取成功后行级可用数量/缺口停留在旧快照(界面显示「库存文件未准备」)。 + """ + from datetime import datetime, timezone + + from app.services.shipping_notice import process_gate_service + + task = db.session.get(ShippingOrderTask, int(gate_execution.task_id)) + version_before = int(task.progress_version or 1) + + 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 in { + 'document_materialization', 'layout_parsing', 'document_profile_routing', + 'order_field_extraction', 'field_completeness', 'reservation_validation', + 'customer_resolution', 'duplicate_detection', 'field_conflict_resolution', + 'task_creation', '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() + + # 关键断言:缺口落定属于真实事实变化,无 Notice 也必须经中央写入口推进版本。 + assert gate_execution.current_gate_code == 'inventory_sufficiency' + assert gate_execution.status == 'blocked' + assert int(task.progress_version or 1) == version_before + 1 + + process_gate_service._refresh_execution_pointers(gate_execution) + db.session.flush() + + # 关键断言:事实未变的重复刷新不得递增版本,避免轮询期被放大成详情刷新风暴。 + assert int(task.progress_version or 1) == version_before + 1 + + diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index 71b0c886..29e9124f 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -519,6 +519,29 @@ def test_waiting_human_without_reconcile_action_has_no_false_primary_action(): assert payload['primary_action'] is None +def test_in_flight_gate_projects_running_not_waiting_human(): + """RPA 在途(Gate waiting_external)必须投影 running,不得误报待人工。 + + Notice 生成前 OT.status 停留在建单前的 waiting_review;若在途期被投影成 + waiting_human,前端会把任务当终态停止投影轮询,RPA 回调完成将永远无法被 + 感知(库存匹配表格冻结在「库存文件未准备」)。与门禁契约 + GATE_STATUS_TO_USER_STATUS['waiting_external']=='running' 对齐。 + """ + payload = apply_user_projection_fields({ + 'status': 'waiting_review', + 'stage': 'inventory_preparation', + 'source_type': 'order_task', + 'current_gate': { + 'gate_code': 'inventory_preparation', + 'status': 'waiting_external', + }, + 'available_actions': [], + }) + + # 关键断言:Gate 在途 = 系统处理中;待人工只属于 blocked_manual 等人工阻断。 + assert payload['user_status'] == 'running' + + def test_apply_user_projection_fields_fail_closes_inconsistent_projection(): """事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。""" payload = apply_user_projection_fields({ diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index 4be7ea24..847530bf 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -4,7 +4,9 @@ tests/test_shipping_review_line_fulfillment_decision.py 用途:行级履约决定的库存安全、reopen 约束与审计参数契约测试。 依赖:pytest、order_review_fulfillment_decision_service。 逻辑:覆盖库存不足禁止先行、task_created 禁止 reopen、管理员重开边界、 - 数量解析与评估助手;不依赖完整建单 Fixture。 + 数量解析与评估助手;以及缺口放行证据字段按「预约号+料号」筛快照、 + 预约键 0 行命中时按料号键兜底重筛(evidence_scope=part_fallback)与 + 放行全量字段值落库契约;不依赖完整建单 Fixture。 """ from __future__ import annotations @@ -28,6 +30,7 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo _release_template_system_fields, _release_fact_identity, _resolve_shortage_release_inventory_source, + _shortage_release_required_fields, _sync_confirmed_task_fulfillment_gates, _is_shortage_match_fact, _has_terminal_inventory_rpa_failure, @@ -616,3 +619,610 @@ def test_project_empty_case_without_draft(app): result = project_review_case_line_decisions(case) assert result['lines'] == [] assert result['has_open_lines'] is False + + +# --------------------------------------------------------------------------- +# [Task 6] 缺口料号兜底:放行证据字段按「预约号+料号」筛库存快照;预约键 0 行命中 +# 时按料号键重筛带出(evidence_scope=part_fallback,审计可见),并落全量模板字段值。 +# --------------------------------------------------------------------------- + +def _seed_part_fallback_release_fixture( + app, + *, + inventory_rows: list[dict[str, str]] | None = None, + order_reservation_id: str = 'R-ORDER', + order_part_number: str = 'ODM-001', + required_qty: str = '10', + part_available_qty: str | None = None, +): + """ + 构造放行字段判定夹具:「预约号+料号」匹配方案 + 行级库存快照 + 模板消费 ODM 字段。 + + 核心逻辑:复用 conftest 种子源 DSV360_AWSDU(profile.match_keys=part_number + + reservation_id,订单键 test-order-part-number / test-order-reservation-id), + 订单行预约号默认 'R-ORDER';库存快照行预约号默认 'R-INV'(≠订单)以制造 + 预约键 0 行命中、料号键可命中的兜底场景。同时落一条真实行匹配事实 + (not_found 且指向本快照),供 decide 放行分支走真实模型查询。 + + Args: + inventory_rows: 库存快照行(语义键 part / reservation / odm); + None 时默认单行且 odm 值唯一('ODM-VAL')。 + required_qty: 行需求量(默认 '10' 保持 Task 6 口径)。 + part_available_qty: 匹配器下发的料号兜底总量;None 时不落列 + (自动放行服务视为不可判定并跳过,Task 7 使用)。 + + Returns: + (task, inventory_file, odm_field)。 + """ + from app import db + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryField, + ShippingInventoryFile, + ShippingInventorySource, + ShippingNoticeLineInventoryMatch, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, + User, + ) + + part_field = ShippingInventoryField.query.filter_by(field_code='part_number').one() + reservation_field = ShippingInventoryField.query.filter_by(field_code='reservation_id').one() + odm_field = ShippingInventoryField.query.filter_by(field_code='odm_id').one() + + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id)) + assert template is not None + # 发货模板只消费 ODM 字段:该字段在快照行上的唯一值即放行自动带出的证据值。 + template.definition_json = { + 'mappings': [ + {'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': str(odm_field.id)}, + ], + } + + user = User(username='part-fallback', email='part-fallback@example.com') + db.session.add(user) + db.session.flush() + schema = ShippingOrderSchema(schema_code='PART_FALLBACK', display_name='Part Fallback') + db.session.add(schema) + db.session.flush() + schema_version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + definition_json={'fields': []}, + ) + db.session.add(schema_version) + db.session.flush() + + task = ShippingOrderTask( + task_no='OT-PART-FALLBACK', + user_id=user.id, + stage='inventory_matching', + ) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=schema_version.id, + order_data_version=1, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + # 订单行 match-key 值必须写入 field_values_json(键 = match_keys.order_field_id)。 + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + reservation_id=order_reservation_id, + part_number=order_part_number, + qty=required_qty, + field_values_json={ + 'test-order-part-number': order_part_number, + 'test-order-reservation-id': order_reservation_id, + }, + ) + db.session.add(snapshot_line) + db.session.flush() + + rows = [ + { + str(part_field.id): str(row.get('part') or ''), + str(reservation_field.id): str(row.get('reservation') or ''), + str(odm_field.id): str(row.get('odm') or ''), + } + for row in (inventory_rows if inventory_rows is not None else [ + {'part': order_part_number, 'reservation': 'R-INV', 'odm': 'ODM-VAL'}, + ]) + ] + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-PART-FALLBACK', + storage_path='test/part-fallback.xlsx', + source_file_name='part-fallback.xlsx', + source_code='DSV360_AWSDU', + snapshot_status='ready', + inventory_lines_json=rows, + line_count=len(rows), + ) + db.session.add(inventory_file) + db.session.flush() + + # 放行资格走真实模型查询:行匹配事实 = not_found(库存不足),指向本快照与本库存源。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line.id, + line_no=1, + line_index=0, + match_result='not_found', + inventory_status='ready', + required_qty=required_qty, + available_qty='0', + matched_qty='0', + shortage_qty=required_qty, + part_available_qty=part_available_qty, + reservation_id=order_reservation_id, + part_number=order_part_number, + inventory_source_code='DSV360_AWSDU', + inventory_snapshot_id=inventory_file.id, + is_current=True, + )) + db.session.commit() + return task, inventory_file, odm_field + + +def _decide_release_with_captured_snapshot(app, monkeypatch, *, task): + """ + 经 decide_review_line_fulfillment 公开路径提交放行(预约不匹配场景),捕获落库快照。 + + 核心逻辑:Case/草稿/决定行为进程内替身;放行分支真实执行(真实行匹配事实 + + 真实 _shortage_release_required_fields + 真实校验),Gate 重算、审计写库与 + resume/投影替身化,隔离外部副作用。提交 release_field_values={}, + 用于证明自动带出值无须人工输入即可落库。 + + Returns: + captured:决定行构造 kwargs(含 snapshot_json 全量内容)。 + """ + from types import SimpleNamespace + + from app.services.shipping_notice import order_review_fulfillment_decision_service as svc + + draft = SimpleNamespace( + draft_version=1, + lines_json=[{ + 'draft_line_id': 'L1', + 'qty': '10', + 'reservation_id': 'R-ORDER', + 'part_number': 'ODM-001', + }], + validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '0'}]}, + ) + case = SimpleNamespace( + id=1, + case_no='CASE-PART-FALLBACK', + status='ready', + current_draft=draft, + run=SimpleNamespace(run_no='RUN-1'), + confirmed_task_id=int(task.id), + ) + row = SimpleNamespace( + id=None, + draft_line_id='L1', + line_index=0, + decision_version=1, + decision_code=DECISION_RELEASE_SHORTAGE, + decision_source='user', + line_status='released_shortage', + is_active=True, + reason=None, + required_qty='10', + available_qty='0', + reservation_id='R-ORDER', + part_number='ODM-001', + task_id=None, + wave_no=None, + actor_user_id=1, + snapshot_json={}, + created_at=None, + updated_at=None, + ) + captured = {} + + monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case) + monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None) + monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1) + monkeypatch.setattr( + svc, + 'ShippingOrderReviewLineDecision', + lambda **kwargs: (captured.update(kwargs), row)[1], + ) + monkeypatch.setattr(svc.db.session, 'add', lambda value: None) + monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42)) + # [STEP] 放行后 Gate 同步会重算任务履约态;测试中替身化重算与审计/resume/投影副作用。 + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state', + lambda task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_resume_service.resume_after_review_change', + lambda **kwargs: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome', + lambda payload, resume: payload, + ) + monkeypatch.setattr(svc, '_get_soft_loader', lambda: (lambda **kwargs: case)) + monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {}) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_projection.serialize_review_case', + lambda value: {}, + ) + + result = svc.decide_review_line_fulfillment( + user_id=1, + case_no=case.case_no, + draft_line_id='L1', + decision_code=DECISION_RELEASE_SHORTAGE, + reason='库存缺口按料号兜底放行', + expected_draft_version=1, + release_field_values={}, + ) + # 断言意图:决定行已分配主键并完成落库流程(flush 替身回填)。 + assert result['decision']['id'] == 42 + return captured + + +def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses(app): + """预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app) + + fields, scope = _shortage_release_required_fields( + task=task, + line_index=0, + inventory_snapshot_id=inventory_file.id, + inventory_source_code='DSV360_AWSDU', + ) + + # 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual), + # 且证据范围显式标记为 part_fallback(审计可见)。 + assert scope == 'part_fallback' + assert fields == [{ + 'field_id': str(odm_field.id), + 'display_name': 'ODM 编号', + 'value': 'ODM-VAL', + 'value_source': 'inventory_snapshot', + 'requires_manual': False, + }] + + +def test_shortage_release_part_fallback_still_manual_when_values_ambiguous(app): + """料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture( + app, + inventory_rows=[ + {'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'}, + {'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'}, + ], + ) + + fields, scope = _shortage_release_required_fields( + task=task, + line_index=0, + inventory_snapshot_id=inventory_file.id, + inventory_source_code='DSV360_AWSDU', + ) + + # 断言意图:scope 仍标记 part_fallback(确按料号重筛),但分歧字段禁止任取值, + # 必须回退为人工必填、值为空。 + assert scope == 'part_fallback' + assert fields == [{ + 'field_id': str(odm_field.id), + 'display_name': 'ODM 编号', + 'value': None, + 'value_source': 'manual_required', + 'requires_manual': True, + }] + + +def test_shortage_release_reservation_hit_keeps_inventory_snapshot_scope(app): + """预约号+料号同时命中时不得误标兜底,证据范围必须保持 inventory_snapshot。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture( + app, + inventory_rows=[ + {'part': 'ODM-001', 'reservation': 'R-ORDER', 'odm': 'ODM-VAL'}, + ], + ) + + fields, scope = _shortage_release_required_fields( + task=task, + line_index=0, + inventory_snapshot_id=inventory_file.id, + inventory_source_code='DSV360_AWSDU', + ) + + # 断言意图:预约命中场景 scope 恒为 inventory_snapshot,字段照常自动带值。 + assert scope == 'inventory_snapshot' + assert fields == [{ + 'field_id': str(odm_field.id), + 'display_name': 'ODM 编号', + 'value': 'ODM-VAL', + 'value_source': 'inventory_snapshot', + 'requires_manual': False, + }] + + +def test_shortage_release_decision_records_part_fallback_scope(app, monkeypatch): + """放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app) + captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task) + + # 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」——scope 落在 + # 决定审计快照 snapshot_json['release_evidence_scope'](导出/审计同源读取)。 + assert captured['snapshot_json']['release_evidence_scope'] == 'part_fallback' + + +def test_shortage_release_persists_full_template_field_values(app, monkeypatch): + """落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app) + captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task) + + # 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读 + # snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空; + # 全部字段自动带出时人工必填清单为空、人工提交为空 dict 仍可放行。 + assert captured['snapshot_json']['release_field_values'] == {str(odm_field.id): 'ODM-VAL'} + assert captured['snapshot_json']['release_required_fields'] == [] + + +def test_shortage_release_part_fallback_still_requires_manual_fill_on_decide(app, monkeypatch): + """料号兜底分歧字段未人工补录时,公开 decide 路径仍必须 409(fail-closed 不回退)。""" + with app.app_context(): + task, inventory_file, odm_field = _seed_part_fallback_release_fixture( + app, + inventory_rows=[ + {'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'}, + {'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'}, + ], + ) + + with pytest.raises(ConflictError) as exc: + _decide_release_with_captured_snapshot(app, monkeypatch, task=task) + + # 断言意图:兜底只解决「能唯一取值」的补录;分歧字段缺失人工补录仍按原契约拒绝。 + assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED' + + +# --------------------------------------------------------------------------- +# [Task 7] 料号兜底自动放行:料号总量满足需求时,匹配完成后缺口行由系统自动放行 +# (decision_source='system'、snapshot.auto_release=True、scope=part_fallback); +# 量不足 / 证据分歧 / 已有活动决定一律跳过并维持人工路径(fail-closed)。 +# --------------------------------------------------------------------------- + +def _seed_auto_release_fixture( + app, + *, + required_qty: str = '8', + part_available_qty: str = '9', + inventory_rows: list[dict[str, str]] | None = None, +): + """ + 构造自动放行端到端夹具:真实 OT/快照行/行事实(part_available_qty)/复核 Case+草稿。 + + 核心逻辑:复用 Task 6 seed(预约号改用 10 位纯数字域契约值;订单预约号与库存行 + 预约号不同 → 预约键 0 行命中、料号键命中),再落一条真实 Review Case 与草稿 + (与既有投影测试同构:run/unit/document 用悬挂占位 ID),使自动放行可走真实的 + Case 反查、草稿行定位、决定落库与门禁满足性查询。 + + Returns: + (task, case, odm_field)。 + """ + from app import db + from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderSnapshot + + task, _inventory_file, odm_field = _seed_part_fallback_release_fixture( + app, + inventory_rows=inventory_rows, + order_reservation_id='3000112934', + required_qty=required_qty, + part_available_qty=part_available_qty, + ) + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + case = ShippingOrderReviewCase( + case_no='CASE-AUTO-RELEASE', run_id=921, unit_id=922, document_id=923, + owner_user_id=int(task.user_id), status='confirmed', confirmed_task_id=task.id, + ) + db.session.add(case) + db.session.flush() + db.session.add(ShippingOrderReviewDraft( + case_id=case.id, draft_version=1, schema_version_id=int(snapshot.schema_version_id), + header_values_json={}, + lines_json=[{ + 'draft_line_id': 'line-1', + 'qty': required_qty, + 'reservation_id': '3000112934', + 'part_number': 'ODM-001', + }], + validation_result_json={'line_projections': [ + {'draft_line_id': 'line-1', 'available_qty': '0'}, + ]}, + )) + db.session.flush() + case.current_draft_id = case.drafts[0].id if case.drafts else None + db.session.flush() + db.session.commit() + return task, case, odm_field + + +def _patch_auto_release_side_effects(monkeypatch, *, stub_recompute: bool = True) -> list[dict]: + """ + 替身化自动放行的编排副作用(与 Task 6 decide 测试同口径)。 + + Args: + stub_recompute: True 时替身化任务履约态重算;False 保留真实重算 + (供门禁满足性测试走完整「放行→重算→sufficiency 放行」链路)。 + + Returns: + auto_fulfill_jobs:enqueue_post_ot_auto_fulfill_job 捕获列表。 + """ + if stub_recompute: + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state', + lambda task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **kwargs: None, + ) + auto_fulfill_jobs: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job', + lambda **kwargs: auto_fulfill_jobs.append(kwargs), + ) + return auto_fulfill_jobs + + +def _active_auto_release_decisions(case): + """读取该 Case 活动的 release_inventory_shortage 决定(真实模型查询)。""" + from app.models import ShippingOrderReviewLineDecision + + return ( + ShippingOrderReviewLineDecision.query + .filter_by( + review_case_id=int(case.id), + decision_code=DECISION_RELEASE_SHORTAGE, + is_active=True, + ) + .all() + ) + + +def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatch): + """料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。""" + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + with app.app_context(): + # 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、 + # 模板字段(ODM)可由料号命中的快照行唯一取值。 + task, case, odm_field = _seed_auto_release_fixture(app) + _patch_auto_release_side_effects(monkeypatch) + + released = auto_release_part_fallback_shortages(task) + + # 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。 + assert released == [0] + decisions = _active_auto_release_decisions(case) + assert len(decisions) == 1 + decision = decisions[0] + assert decision.decision_source == 'system' + assert decision.snapshot_json['auto_release'] is True + assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback' + # 自动带出值必须落库(导出覆盖唯一来源),与人工 decide 放行同契约。 + assert decision.snapshot_json['release_field_values'] == {str(odm_field.id): 'ODM-VAL'} + assert decision.snapshot_json['release_required_fields'] == [] + + +def test_auto_release_skips_when_part_total_below_required(app, monkeypatch): + """料号兜底量不足时不得自动放行,行保持人工待处置。""" + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + with app.app_context(): + # 同上构造,但料号总量改为 3(< 8)。 + task, case, _odm_field = _seed_auto_release_fixture(app, part_available_qty='3') + _patch_auto_release_side_effects(monkeypatch) + + released = auto_release_part_fallback_shortages(task) + + # 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。 + assert released == [] + assert _active_auto_release_decisions(case) == [] + + +def test_auto_release_skips_when_evidence_field_ambiguous(app, monkeypatch): + """证据字段无法唯一取值(requires_manual 残留)时不得自动放行。""" + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + with app.app_context(): + # 同上构造,但两条同料号快照行在模板字段(ODM)上取值不同。 + task, case, _odm_field = _seed_auto_release_fixture( + app, + inventory_rows=[ + {'part': 'ODM-001', 'reservation': '3000420001', 'odm': 'ODM-V1'}, + {'part': 'ODM-001', 'reservation': '3000420002', 'odm': 'ODM-V2'}, + ], + ) + _patch_auto_release_side_effects(monkeypatch) + + released = auto_release_part_fallback_shortages(task) + + # 断言意图:降级为人工放行(补录要求保留),不产生自动决定。 + assert released == [] + assert _active_auto_release_decisions(case) == [] + + +def test_auto_release_does_not_duplicate_existing_decision(app, monkeypatch): + """已有人工放行/结案决定(或已放行)的行不得重复自动放行。""" + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + with app.app_context(): + task, case, _odm_field = _seed_auto_release_fixture(app) + _patch_auto_release_side_effects(monkeypatch) + + first = auto_release_part_fallback_shortages(task) + second = auto_release_part_fallback_shortages(task) + + # 断言意图:幂等——不新建第二个活动决定,原决定保持不变。 + assert first == [0] + assert second == [] + assert len(_active_auto_release_decisions(case)) == 1 + + +def test_auto_release_counted_in_sufficiency_and_gate_releases(app, monkeypatch): + """自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。""" + from app.services.shipping_notice.fulfillment_workflow import ( + _recompute_task_match_aggregate, + match_completed, + ) + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + with app.app_context(): + task, _case, _odm_field = _seed_auto_release_fixture(app) + # 保留真实 recompute:完整走「放行落库 → 任务履约态重算 → 满足性门禁」链路。 + _patch_auto_release_side_effects(monkeypatch, stub_recompute=False) + + # 放行前:缺口行未放行 → 整单不满足。 + assert match_completed(task) is False + + released = auto_release_part_fallback_shortages(task) + + # 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过, + # inventory_sufficiency 不再因该行 blocked_manual。 + assert released == [0] + assert match_completed(task) is True + status, shortages = _recompute_task_match_aggregate(task) + assert status == 'fulfillable' + assert shortages == [] + line_results = task.step_payload_json['current_match_projection']['line_results'] + assert line_results[0]['line_status'] == 'released' diff --git a/backend/tests/test_shipping_stp_match_completed_gate.py b/backend/tests/test_shipping_stp_match_completed_gate.py index 0b86283c..d5f0b64f 100644 --- a/backend/tests/test_shipping_stp_match_completed_gate.py +++ b/backend/tests/test_shipping_stp_match_completed_gate.py @@ -236,3 +236,55 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke assert task.review_status == 'shortage_review' assert task.pending_human_reason == 'shortage' assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage' + + +def test_system_auto_release_decision_counts_as_released(app): + """系统自动放行(decision_source='system')的活动决定必须被满足性门禁按放行读取。 + + 核心逻辑:料号兜底自动放行(Task 7)落库的 release_inventory_shortage 决定 + decision_source='system';``_released_snapshot_line_ids_for_task`` 的真实查询 + (不经测试 seam)必须同等识别,match_completed / 聚合重算才能把放行行计入满足。 + """ + from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderReviewLineDecision + from app.services.shipping_notice.fulfillment_workflow import _recompute_task_match_aggregate + + with app.app_context(): + task = _task_with_current_matches( + task_no='SN-AUTO-RELEASE-GATE', + rows=[{'match_result': 'not_found', 'shortage_qty': '1'}], + ) + # 放行前:缺口行未放行 → 整单不满足。 + assert match_completed(task) is False + case = ShippingOrderReviewCase( + case_no='SNRC-AUTO-RELEASE-GATE', run_id=931, unit_id=932, document_id=933, + owner_user_id=task.user_id, status='confirmed', confirmed_task_id=task.id, + ) + db.session.add(case) + db.session.flush() + db.session.add(ShippingOrderReviewDraft( + case_id=case.id, draft_version=1, schema_version_id=1, + header_values_json={}, + lines_json=[{'draft_line_id': 'line-1', 'qty': '1', 'reservation_id': '3000112934'}], + )) + db.session.flush() + case.current_draft_id = case.drafts[0].id if case.drafts else None + db.session.flush() + db.session.add(ShippingOrderReviewLineDecision( + review_case_id=int(case.id), + draft_line_id='line-1', + line_index=0, + decision_version=1, + decision_code='release_inventory_shortage', + decision_source='system', + line_status='released_shortage', + is_active=True, + snapshot_json={'auto_release': True, 'release_evidence_scope': 'part_fallback'}, + )) + db.session.flush() + + # 系统自动放行决定落库后走真实放行查询(不打 seam 补丁)必须满足。 + assert match_completed(task) is True + status, shortages = _recompute_task_match_aggregate(task) + assert status == 'fulfillable' + assert shortages == [] + assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released' diff --git a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py index cf563018..1746a8ee 100644 --- a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py +++ b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py @@ -215,6 +215,92 @@ def test_allowed_system_facts_use_notice_line_no_not_export_sequence(): assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS +def test_part_fallback_total_aggregates_across_reservations_within_allowed_source(): + """预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。""" + # Reservation 契约只接受 5/10 位纯数字(validated_reservation_id), + # 故用互不相同的数字预约号表达「订单预约号 vs 其它预约号」。 + order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}] + inventory_lines = [ + {'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'}, + {'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'}, + {'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=inventory_lines, + header_reservation_id=None, + ) + result = payload['line_results'][0] + # 断言意图:订单预约号无库存桶 → not_found;料号兜底总量 0+5+3=8 必须随行结果下发。 + assert result['disposition'] == 'not_found' + assert result['available_qty'] == 0.0 + assert result['part_available_qty'] == 8.0 + + +def test_part_fallback_total_respects_allowed_source_and_ignores_unit(): + """料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。""" + order_lines = [{ + 'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8, + 'allowed_source_codes': ['DSV'], 'candidate_line_id': 1, + }] + inventory_lines = [ + {'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'}, + {'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'}, + {'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + result = payload['line_results'][0] + # 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。 + assert result['disposition'] == 'not_found' + assert result['part_available_qty'] == 105.0 + + +def test_part_fallback_total_absent_for_conflict_and_missing_part(): + """multi_file_conflict / 缺料号 / invalid(超出候选范围)行不下发料号总量,避免误导用户。""" + order_lines = [ + {'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 1, + 'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1}, + {'line_no': 2, 'reservation_id': '3000092918', 'quantity': 1, + 'allowed_source_codes': ['A'], 'candidate_line_id': 2}, + {'line_no': 3, 'part_number': 'P-2', 'reservation_id': '1380000000', 'quantity': 1, + 'allowed_source_codes': ['A'], 'candidate_line_id': 3}, + ] + inventory_lines = [ + {'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'}, + {'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'}, + {'reservation_id': '1380000000', 'part_number': 'P-2', 'qty': 5, '__source_code': 'B'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + # 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。 + assert 'part_available_qty' not in payload['line_results'][0] + assert 'part_available_qty' not in payload['line_results'][1] + # 断言意图:命中仅存在于候选范围外源(invalid)的行同样不写键,不得误导放行判断。 + assert payload['line_results'][2]['disposition'] == 'invalid' + assert 'part_available_qty' not in payload['line_results'][2] + + +def test_part_fallback_total_on_shortage_line_sums_other_reservations(): + """预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。""" + order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}] + inventory_lines = [ + {'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'}, + {'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + result = payload['line_results'][0] + # 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。 + assert result['disposition'] == 'shortage' + assert result['available_qty'] == 2.0 + assert result['shortage_qty'] == 6.0 + assert result['part_available_qty'] == 9.0 + + def test_permanent_audit_events_have_no_retention_expiry(app): """货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。""" from app.services.shipping_notice.audit_service import append_shipping_audit_event diff --git a/docs/demand.md b/docs/demand.md index 313fe53d..0128b0e5 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -460,6 +460,8 @@ - 人工上传是 RPA 的受控降级:业务人员仅按 `business_no` 确认已上传,不上传截图、回执或 PDF;服务端仍通过该 Notice 的受控 Attempt 与状态机记录成功事实。 - 上传以 Excel Artifact 为边界:每次 RPA 或人工操作均创建独立 Attempt,trigger 和回调必须携带 `artifact_id`、`attempt_id` 与幂等 `callback_id`。相同回调只生效一次;网络失败只能重试原 Artifact,只有货代明确拒绝并经授权才可作废 Artifact、释放未上传预约单;Task 上传字段仅为 Artifact/Attempt 的聚合投影。 +- **缺口放行规则变化(2026-10-09,料号兜底自动放行,已实现)**:预约单号匹配出缺口的行,若该料号在行允许库存源内的总可用数量 ≥ 需求数量、且放行证据字段可全部自动取值,系统在库存匹配落库后自动创建 `release_inventory_shortage` 放行决定(系统来源、快照记 `auto_release` 与证据范围),不再要求人工逐字段补录;证据带出优先级为「预约号+料号精确命中 → 库存无该预约单号时按料号重筛 → 人工补录」,自动带出与人工补录合并保存并作为导出 Excel 证据的唯一来源。料号总量不足、证据无法自动取值或已有放行决定时一律保持人工放行,系统不自动撤销。出单条件不变:仍由用户人工勾选波次触发,放行行可勾选资格规则与既有口径一致;工作台匹配表原「可用数量」列改「预约数量」(预约匹配口径),新增「可用数量」列展示料号口径总量(与明细表/聊天卡同名列是否统一待产品定)。 + ### 3.1 本期范围 - 查询员工本人假期余额 diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 9a266400..896501c0 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -69,6 +69,7 @@ | GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) | | GET | `/sources` | 来源实例列表(附收料文件状态 ready/parse_failed/fetching/failed/expired/none + has_ready_file,供前端门禁;2026-09-29 起 `parse_failed`=当日文件在但 movement 解析失败(`has_ready_file=false`),路由失败仅行内 `blocked_route_not_resolved`、不抬升来源顶栏) | | POST | `/sources/{source_code}/retry-rpa` | 来源收料重试(2026-09-29 起分层:parse_failed 且有当日可用文件时优先本地重解析——成功 ready / 仍失败 parse_failed,200 `reparsed=true`,不触发 RPA;否则原样重新触发一次收料 RPA 抓取,202+fetching,配置缺失 fail-closed ok=False) | +| POST | `/sources/retry-rpa-batch` | 批量来源收料重试(body `source_codes`;2026-10-09 起多来源合并写**一个** batch trigger 文件——Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;逐来源分层与 fail-closed 语义同单来源端点,单源配置缺失跳过并记录不阻断整批,响应 `triggered`+逐源 `results`) | | GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) | | GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) | diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 3612f1a1..5325475c 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -745,3 +745,42 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理; - Excel 一旦生成,头字段、行字段、行源全部转为**只读**;页面按后端 `edit_window` 禁用对应输入。 - 若已确认信息有误,只能走既有的撤销 / 人工纠错流程(D12:编辑窗只覆盖「确认后、Excel 前」;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销)。 + +--- + +## 17. 缺口放行(料号兜底自动放行) + +> 针对预约单号匹配出缺口、但同料号在库存中还有其他预约号余量的场景。系统会按料号维度自动核对总量,满足条件时**直接替您完成放行**,不再要求逐字段补录放行证据;不满足时仍回到人工放行,流程更省但不放松管控。 + +### 17.1 什么时候系统会自动放行 + +匹配完成后,同时满足以下条件的缺口行由系统自动放行(无需您确认): + +- 该行按「预约单号 + 料号」匹配存在缺口(含库存中查不到该预约单号的情况); +- 该料号在本行允许的库存源内的**总可用数量 ≥ 需求数量**(忽略预约号、不限单位的料号口径); +- 放行需要的证据字段(库存数量、批次等)都能从库存中**自动取到唯一值**。 + +### 17.2 什么时候降级为人工放行 + +以下任一情况系统不会自动放行,该行保持原人工流程(由您补录证据后放行): + +- 料号总可用数量不足(差多少都不行,系统不会拿部分数量放行); +- 放行证据字段无法自动取值或取值存在分歧; +- 该行已有放行决定时,系统不会自动撤销或改写,仍以已有人工决定为准。 + +### 17.3 放行证据从哪里来(带出优先级) + +1. 优先按「预约单号 + 料号」精确命中取值; +2. 库存中查不到该预约单号时,按料号重新筛选库存取值; +3. 仍取不到的字段由人工补录。自动带出与人工补录的字段值会合并保存,作为生成发货 Excel 时证据列的唯一来源。 + +### 17.4 Excel 出单条件不变 + +- 出单仍由您**人工勾选波次**触发,系统不会因自动放行而自动出单; +- 放行行的可勾选资格规则与之前完全一致(已满足行 + 已放行行可勾选),缺货且未放行行仍不能进入本轮 Excel。 + +### 17.5 页面上的数量列 + +- 库存匹配表中,原「可用数量」列更名为「**预约数量**」(按预约单号匹配到的数量); +- 新增「**可用数量**」列,显示该料号在允许库存源内的总可用量(料号口径),供您判断能否放行; +- 注意:订单明细表、聊天匹配卡中的「可用数量」仍是预约匹配口径,与工作台新列同名不同义,是否统一名称待产品确认。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index d1596681..69bd3425 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -3907,3 +3907,64 @@ inventory_preparation Gate - 预检触发守卫(`_DefaultRpaTrigger`):收料配置存在但未绑/规则未发布/用途不符 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,不写 trigger(防徒劳抓取循环);无收料配置仍走既有 `RPA_RECEIPT_CONFIG_MISSING`。 - 站点库存解析绑定(`ShippingInventorySource.parsing_profile_id`,站点表单与批量绑定弹窗)只列 `purpose==='inventory'` 的已发布规则,防止误绑异动规则。 - `movement_file_repository.latest_ready_file` 复用条件不变:归档文件存在且绑定规则就绪;无排程按需触发的单元行 `schedule_run_id` 为 NULL(FK 禁止 0 占位)。 + +## 通知准备阶段进度版本推进契约修复(2026-10-09) + +> 背景:单笔「重新获取库存(RPA)」成功并检出库存缺口后,工作台「库存匹配」表格的可用数量/缺口/匹配状态停留在旧快照(显示「库存文件未准备」),仅右卡门禁更新。根因有两处,均在后端投影契约,前端 `[REFRESH_ON_CHANGE]`(progressVersion 变化 → 重拉任务详情)机制本身无缺陷。 + +### 缺陷 1:无 Notice 绑定期 Gate 推进不递增 progress_version + +- `ShippingNotice` 生成前(通知准备/库存匹配常态),`process_gate_service._sync_order_task_stage_after_gate_refresh` 的无 Notice 分支只回填 `task.stage`,从不写 status、从不递增 `progress_version`。实测 OT-20260919-97A7EB0C 自 9/19 建单后版本冻结在 20,10/9 的 RPA 重取→匹配→缺口全链路零递增。 +- 修复:`_refresh_execution_pointers` 捕获指针事实(last_passed/current_gate/primary_next_action/responsible_party/status)前后差异得 `facts_changed`;无 Notice 分支在事实变化时经 `sync_order_task_processing_state(force_progress_bump=True, reason_code='gate_facts_advanced')` 强制递增(保留 BE-06 中央审计);有 Notice 分支在映射后 stage/status 未变但事实已变化时同样补递增。事实未变的重复刷新不递增,避免轮询期刷新风暴。 + +### 缺陷 2:RPA 在途被投影成 waiting_human 导致前端轮询提前自停 + +- Notice 生成前 `OT.status` 停留在建单前的 `waiting_review`;`processing_projection_invariants._compute_user_status` 在 Gate `waiting_external`(系统等 Worker)时会落到 `waiting_review → waiting_human` 分支,前端把该用户态视为终态并停止投影轮询,回调完成永远无法被感知。 +- 修复:在 `blocked_manual`/未证实上传终态判定之后新增「Gate 在途(queued/running/waiting_external)→ running」短路,与既有门禁契约 `GATE_STATUS_TO_USER_STATUS['waiting_external']=='running'` 对齐;`blocked_manual` 等人工阻断判定优先级不变。 + +### 回归与影响面 + +- 新增测试:`test_shipping_process_gate_service.py::test_refresh_pointers_bumps_task_progress_version_without_notice`(事实变化递增一次、未变化不递增)、`test_shipping_processing_projection_invariants.py::test_in_flight_gate_projects_running_not_waiting_human`。 +- 修复后闭环:提交重取(waiting_external,版本+1,轮询存活)→ Worker 回调/AutoProgress 重评(匹配落库缺口、Gate blocked_manual,版本+1)→ 前端轮询感知终态并重拉任务详情,行级可用数量/缺口/匹配状态即时刷新。 + +--- + +## 料号兜底自动放行与数量列(2026-10-09) + +> 背景:预约单号匹配缺口行,在「同料号库存尚有其他预约号余量」时仍需人工逐字段补录放行证据。本节记录已实现并过评审的「料号兜底自动放行」与料号维度可用数量列,均为追加能力,不改既有缺口判定与出单条件。 + +### 匹配器:part_available_qty(料号兜底总量) + +- 缺口判定不变:仍按「预约单号 + 料号」主键匹配(`backend/app/services/shipping_notice/stp_line_inventory_match.py` 的 `match_order_lines_across_candidates`)。 +- 行结果新增 `part_available_qty`:口径 = 行允许源内、忽略预约号、不限单位的料号总可用量(对行允许源快照按料号键二次汇总);跨源不合并(多源行只汇总该行允许源,不做全库合计)。 +- 下发范围:仅 `not_found`(预约不匹配)/ `ok` / `shortage` 行下发;`multi_file_conflict` / `invalid` / 缺料号 / 缺预约行不下发。 + +### 存储:新列与回填策略 + +- 新列 `shipping_notice_line_inventory_matches.part_available_qty`(`String(32)` 可空),迁移 `0a575f3afc32`(`backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py`)。 +- 落库:`line_inventory_match_persistence` 在匹配落库(新建与更新路径)时随行事实字符串化写列。 +- 存量行 NULL 不回填,重新匹配后回填。 + +### 投影与前端数量列 + +- 投影:`line_inventory_match_projection.serialize_match_fact` 与 view 透出 `part_available_qty`(仅库存就绪时非空,否则 None);`ui_state.py` preparation 行直透该数量。 +- 前端库存匹配表:原「可用数量」列改「预约数量」(`lifecycle.prepare.reservedQty`,仍为预约匹配语义),新增「可用数量」列(`lifecycle.prepare.partAvailableQty`,数据源为料号兜底总量);四语言已补齐。 + +### 自动放行:auto_release_part_fallback_shortages + +- 位置:`backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py` 的 `auto_release_part_fallback_shortages`,在库存匹配落库后调用。 +- 触发条件(全部满足才由系统放行):行为缺口行 + 该行料号兜底总量 `part_available_qty` ≥ 需求数量 + 放行证据字段全部可自动取值(无 `requires_manual` 残留)。 +- 放行写路径:复用 `_apply_shortage_line_release`,由系统创建 `release_inventory_shortage` 决定,`decision_source='system'`、`actor_type='system'`;决定快照记 `auto_release: true` 与 `release_evidence_scope`(`inventory_snapshot` / `part_fallback`)供审计。审计/门禁同步/自动履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证。 +- 降级人工:证据不可解析(ConflictError)、字段分歧或料号总量不足时一律跳过该行并保持人工放行路径(fail-closed),不中断其余行。 +- 不自动撤销:自动放行只创建决定,不撤销/重开任何既有放行。 + +### 放行证据带出优先级与 release_field_values + +- 带出优先级:预约号 + 料号精确命中优先 → 库存中无该预约单号时按料号键重筛(`release_evidence_scope=part_fallback`)→ 剩余字段人工补录。 +- `release_field_values` 落库为「自动带出 + 人工补录」全量字段值字典,是导出 Excel 证据覆盖的唯一来源。 + +### 不变项与边界备忘 + +- Excel/波次条件零改动:出单仍需人工勾选波次,放行行可勾选资格规则不变(`export.py` / wave 服务 / 满足性聚合未改动)。 +- 同名不同义:订单明细表 / 聊天匹配卡的「可用数量」仍是预约匹配语义;prep 工作台新「可用数量」列是料号兜底总量,两处是否统一待产品定。 +- 存量 canonical-only 快照行料号兜底不生效(与基线一致)。 diff --git a/docs/funclist.md b/docs/funclist.md index 04324707..5e3bb703 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -224,6 +224,7 @@ | **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 | | **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | | **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | +| 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 | ### 排程平台任务契约中心(schedule) @@ -806,6 +807,7 @@ | 按行执行与执行门禁 | 已实现 | execute(item_ids) **202 异步**:API 两道门禁(存在可执行 + 文件版本对账,fail-closed)通过即建 queued Run + 五元组分组建票 + 一次入队,worker 逐票执行(文件对账复核 + 写前路由/库存复查——库存复查仅全量重跑路径,final_only 续跑不复查);Run 留痕不绑匹配;进度/结果无状态回读(GET /runs 轮询票清单);行级新鲜度 TTL 门禁与 ITEMS_STALE 错误码退役,TTL 降为 stale 徽标展示阈值(2026-09-25 定稿,见 features/in-transit-transfer/technical.md §6.3) | | ERP 建单写路径(票级顺序引擎,2026-09-24) | 已实现 | 写路径经集成连接器统一出口:`database` 连接器(oracle/mysql/sqlserver/postgresql 四库直连,SQL 接口 identifiers 白名单替换)+ `create_transfer` 绑定一对多有序步骤(steps_json:写 ERP 中间表 → 触发 WS);顺序引擎四规则(resume 跳过非末步/非末步失败即中止/末步映射+裁决钩子/末步超时 result_unknown);融合卡「票清单=进度=结果」、result_unknown retrigger(D11 唯一出口,禁关闭重建)、失败票人工关票(D18 行脱离回可执行)、首页「已执行」票维护区块;管理端配置配方/SOP/UAT 确认项/已知限制统一见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10(含 SOP 红线 §10.8;交付说明:新增依赖 pymysql/pymssql,psycopg2-binary 既有;本期零新增环境变量) | | 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 T+lag 成熟规则(默认业务日 T-2,可配 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 | +| 来源重试合并触发与知情范围确认(2026-10-09) | 已实现 | 批量重试 RPA 合并写**单个** batch trigger(POST `/sources/retry-rpa-batch`,Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;单源失败跳过不阻断整批,parse_failed 仍先本地重解析);来源选择卡混合选择(含非就绪项)确认前先披露范围(可匹配/暂不可匹配计数+按状态分组明细),显式确认后提交 ready-only,全就绪直达(知情部分确认,替代静默剔除;其余来源就绪后可重新匹配增量补入) | | 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态) | --- diff --git a/docs/superpowers/plans/2026-10-09-inventory-part-fallback-release.md b/docs/superpowers/plans/2026-10-09-inventory-part-fallback-release.md new file mode 100644 index 00000000..e8797811 --- /dev/null +++ b/docs/superpowers/plans/2026-10-09-inventory-part-fallback-release.md @@ -0,0 +1,937 @@ +# 库存缺口料号兜底放行 + 数量列改造 实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 库存缺口仍按「预约单号+料号」判定;当料号维度总库存满足需求时,缺口行由**系统自动放行**(无需人工确认,证据字段按预约优先→料号兜底自动带出);Excel/波次生成条件不变;前端「库存匹配」表原「可用数量」列改为「预约数量」,其后新增「可用数量」(料号总库存)列。 + +**Architecture:** 匹配器在现有 `(reservation, part, unit, source)` 聚合桶上按料号二次汇总出 `part_available_qty`,随行级匹配事实持久化(新列+迁移);匹配完成后由自动放行服务对「料号总量≥需求且放行证据可全部自动取值」的缺口行创建系统放行决定(复用人工放行的同一落库/审计/门禁同步/自动履约链路),其余缺口行维持人工放行(证据预约优先→料号兜底);导出消费的放行字段值扩展为「自动带出+人工补录」全量字典。前端新增料号可用数量列,自动放行行沿用既有「已放行」状态展示。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(后端);Vue 3 + TypeScript + Vue I18n 四语言(前端)。 + +**Spec:** 本计划顶部「需求与假设」节即规格;执行者须连同本节一起阅读。 + +## 需求与假设(评审重点,与用户确认过的口径) + +1. **缺口判定公式不变**:`match_order_lines_across_candidates` 的预约号+料号匹配、`available_qty`/`shortage_qty`/`match_result` 计算与持久化语义完全不变。料号兜底**不**改变缺口判定(否则会改变 Excel 条件,违反需求)。 +2. **料号总库存口径(用户已确认 2026-10-09)**:在该行允许的库存源范围内(`allowed_source_codes`,无候选范围时不过滤)、**不限单位**、**忽略预约号**汇总库存行 `available_qty`。跨库存源不合并(与 `multi_file_conflict` 人工选源语义一致);`multi_file_conflict`/`invalid`(超出候选范围)行不下发料号总量(显示 —,需先选源)。 +3. **自动放行规则(用户确认 2026-10-09:料号总库存满足 = 自动放行,不是仅"可放行")**:匹配落库后,对同时满足以下全部条件的缺口行,由系统(actor_type='system')自动创建 `release_inventory_shortage` 行决定: + - 行为缺口(`inventory_status='ready'` 且 shortage/not_found); + - `part_available_qty >= required_qty`(料号兜底量满足); + - 无活动决定(未放行/未结案)且行非终态(未入波次/未履约); + - 放行模板字段**全部**可自动取值(证据行按「预约号+料号」优先、库存中无该预约单号时按料号键重筛;任一字段无法唯一取值 → 不自动放行,降级为现有人工放行并保留补录要求); + - 证据解析本身失败(无源/模板未发布/无快照等 ConflictError 场景)→ 不自动放行,维持现状。 + 自动放行复用人工放行的同一内部落库函数(审计、门禁同步、自动履约入队不变),决策快照记 `auto_release: true` 与 `release_evidence_scope`。**不自动撤销**:已放行行不因后续重匹配总量变化而回退(与人工放行一致,撤销走既有流程)。 +4. **放行字段值持久化扩展**:导出侧的放行证据覆盖(`release_overrides_by_source_line`)只读 `decision.snapshot_json['release_field_values']`,而现行该字典经白名单只存人工补录项。自动放行没有人工输入,故 decide/自动放行落库时把「自动带出 + 人工补录」的**全量**模板字段值写入 `release_field_values`(校验逻辑不变:人工必填项缺失仍 409)。 +4. **Excel/波次条件不变**:`exportable_snapshot_line_ids` / `current_available_snapshot_line_ids` / `create_post_ot_fulfillment_wave` / `excel_gate_error` / `can_fulfill_complete_line` 一律不改。放行过的缺口行按既有规则获得出单资格。 +5. **前端范围**:仅改「订单生命周期工作台 → 通知准备 → 库存匹配」表(ui_state `preparation.lines` 单源)。订单明细表(draft lines,`fulfillmentDecision.availableQty` 键)与聊天匹配卡(`ShippingMatchLineResult`)**本期不动**,键值文案同为「可用数量」但语义仍是预约匹配量——已在文档任务中注明,若需统一由用户后续决定。 +6. **存量数据**:历史 Match 行 `part_available_qty` 为 NULL(前端显示 —),不回填;用户点「重新匹配库存 / 重新获取库存」后自动补齐。 + +## Global Constraints + +- 🧬 新增数据库列必须配套 Alembic 迁移(`flask db migrate -m "..."` → 检查 → `flask db upgrade`),禁止只改模型。 +- 🌍 前端新增文案必须同时补 `zh-CN / zh-TW / en / th` 四语言;禁止硬编码中文。`chat.json` 的 `lifecycle.prepare` 块是**单行 JSON**,编辑用精确子串替换(Edit 工具)或 python io,禁用 PowerShell Get-Content/Set-Content。 +- 🚫 不做 git commit;每个任务以 `git add <具体文件>` 收尾(用户批准后统一提交)。 +- ⚠️ Excel/波次/满足性聚合行为不变:Task 10 的守护测试必须全绿(`test_post_ot_fulfillment_wave_p0.py`、`test_shipping_rolling_fulfillment.py`、`test_shipping_stp_match_completed_gate.py`)。 +- 📝 新函数必须有含 Args/Returns 的 docstring;测试断言必须有断言意图注释(§5.4)。 +- 后端测试命令:`cd backend && ./.venv/Scripts/python.exe -m pytest -q`。 + +## File Structure(改动全景) + +| 文件 | 动作 | 职责 | +| --- | --- | --- | +| `backend/app/services/shipping_notice/stp_line_inventory_match.py` | 修改 | 匹配器按料号二次聚合,产出 `part_available_qty` | +| `backend/app/models/shipping_notice_line_inventory_match.py` | 修改 | 新列 `part_available_qty`(String(32) nullable) | +| `backend/migrations/versions/_add_part_available_qty_to_line_inventory_matches.py` | 新建 | 加列迁移 | +| `backend/app/services/shipping_notice/line_inventory_match_persistence.py` | 修改 | 新建/更新两分支写入新列 | +| `backend/app/services/shipping_notice/line_inventory_match_projection.py` | 修改 | serialize/view 透出新列 `part_available_qty`(ready 门控) | +| `backend/app/services/shipping_notice/ui_state.py` | 修改 | prep 行下发两个新字段 | +| `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py` | 修改 | 放行补录字段按料号兜底重筛;decide/自动放行落库全量字段值;自动放行共享内部函数 | +| `backend/app/services/shipping_notice/fulfillment_workflow.py` | 修改 | `match_inventory`/`match_inventory_line` 落库后挂自动放行钩子 | +| `frontend/src/features/chat/types/shipping.api.types.ts` | 修改 | prep 行 / Case 行类型加可选新字段 | +| `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | 修改 | `lifecycle.prepare` 加 `reservedQty`、`partAvailableQty` | +| `frontend/src/features/chat/views/ShippingOrderReviewView.vue` | 修改 | 表头/单元格/colspan/格式化 | +| `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts` | 修改 | i18n mock + 列渲染断言 | +| `backend/tests/test_shipping_stp_phase4_line_inventory_match.py` | 修改 | 匹配器新用例 | +| `backend/tests/test_line_inventory_match_persistence.py` | 修改 | 持久化断言 | +| `backend/tests/test_line_inventory_match_projection.py` | 修改 | 投影派生断言 | +| `backend/tests/test_shipping_notice_ui_state.py` | 修改 | prep 行字段断言 | +| `backend/tests/test_shipping_review_line_fulfillment_decision.py` | 修改 | 放行兜底 evidence 用例 | +| `docs/features/shipping-notice/technical.md`、`business.md`、`docs/funclist.md`、`docs/demand.md` | 修改 | 文档同步 | + +**不动清单(明确不改)**:`export.py`、`reservation_service.current_available_snapshot_line_ids`、`post_ot_fulfillment_wave_service.py`、`fulfillment_workflow.match_completed/_recompute_task_match_aggregate/excel_gate_error`、`process_gate_bridge.py` sufficiency 评估、`ShippingMatchResultCard.vue`、任务中心。 + +--- + +### Task 1: 匹配器按料号聚合总可用量 + +**Files:** +- Modify: `backend/app/services/shipping_notice/stp_line_inventory_match.py`(桶聚合在 :289-300,行循环 :314 起,各 disposition 分支 :347-461) +- Test: `backend/tests/test_shipping_stp_phase4_line_inventory_match.py` + +**Interfaces:** +- Consumes: 现有 `buckets: dict[(reservation, part, unit, source) -> {'available_qty': Decimal, 'sample_row', 'source_code'}]`、`allowed_source_codes: list[str]`、`has_candidate_scope: bool`、`part: str`。 +- Produces: 每个 `line_results[i]`(disposition ∈ `not_found`(预约不匹配/预约缺失但有料号)、`ok`、`shortage`)新增键 `part_available_qty: float | None`;`multi_file_conflict`/`invalid`/缺料号行**不写该键**(后续按缺失处理)。口径:行允许源内、忽略预约号、**不限单位**。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_shipping_stp_phase4_line_inventory_match.py` 追加(沿用该文件现有的订单行/库存行构造 helper,若 helper 名不同以文件内现名为准): + +```python +def test_part_fallback_total_aggregates_across_reservations_within_allowed_source(): + """预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。""" + order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-ORDER', 'quantity': 8}] + inventory_lines = [ + {'reservation_id': 'R-ORDER', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'}, + {'reservation_id': 'R-OTHER-A', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'}, + {'reservation_id': 'R-OTHER-B', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=inventory_lines, + header_reservation_id=None, + ) + result = payload['line_results'][0] + # 断言意图:预约桶 0 → not_found;料号兜底总量 5+3=8 必须随行结果下发。 + assert result['disposition'] == 'not_found' + assert result['available_qty'] == 0.0 + assert result['part_available_qty'] == 8.0 + + +def test_part_fallback_total_respects_allowed_source_and_ignores_unit(): + """料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。""" + order_lines = [{ + 'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-ORDER', 'quantity': 8, + 'allowed_source_codes': ['DSV'], 'candidate_line_id': 1, + }] + inventory_lines = [ + {'reservation_id': 'R-A', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'}, + {'reservation_id': 'R-B', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'}, + {'reservation_id': 'R-C', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + result = payload['line_results'][0] + # 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。 + assert result['disposition'] == 'not_found' + assert result['part_available_qty'] == 105.0 + + +def test_part_fallback_total_absent_for_conflict_and_missing_part(): + """multi_file_conflict 与缺料号行不下发料号总量,避免误导用户。""" + order_lines = [ + {'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-1', 'quantity': 1, + 'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1}, + {'line_no': 2, 'reservation_id': 'R-2', 'quantity': 1, + 'allowed_source_codes': ['A'], 'candidate_line_id': 2}, + ] + inventory_lines = [ + {'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'}, + {'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + # 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。 + assert 'part_available_qty' not in payload['line_results'][0] + assert 'part_available_qty' not in payload['line_results'][1] + + +def test_part_fallback_total_on_shortage_line_sums_other_reservations(): + """预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。""" + order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-1', 'quantity': 8}] + inventory_lines = [ + {'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'}, + {'reservation_id': 'R-9', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'}, + ] + payload = match_order_lines_across_candidates( + order_lines=order_lines, inventory_lines=inventory_lines, + ) + result = payload['line_results'][0] + # 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。 + assert result['disposition'] == 'shortage' + assert result['available_qty'] == 2.0 + assert result['shortage_qty'] == 6.0 + assert result['part_available_qty'] == 9.0 +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py -q -k part_fallback` +Expected: FAIL(`KeyError: 'part_available_qty'`) + +- [ ] **Step 3: 实现** + +在 `stp_line_inventory_match.py` 的模块级 helper 区(`_inventory_row_qty` 之后,约 :78)新增: + +```python +def _part_total_available_qty( + buckets: dict[tuple[str, str, str, str], dict[str, Any]], + *, + part: str, + allowed_source_codes: list[str], + has_candidate_scope: bool, +) -> Decimal | None: + """ + 按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。 + + Args: + buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。 + part: 归一化料号;空串返回 None。 + allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。 + has_candidate_scope: 行是否携带候选源范围事实。 + + Returns: + 料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。 + """ + if not part: + return None + total = Decimal('0') + for key, bucket in buckets.items(): + if key[1] != part: + continue + if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes: + continue + total += bucket['available_qty'] + return total +``` + +在行循环内、`all_source_hits` 计算之后(约 :350)加: + +```python + part_total = _part_total_available_qty( + buckets, + part=part, + allowed_source_codes=allowed_source_codes, + has_candidate_scope=has_candidate_scope, + ) +``` + +各 disposition 分支的 `result` dict 增补(`invalid`、`multi_file_conflict`、`not part` 的 not_found 三个分支**不加**): + +- `elif not source_hits:` 的 not_found 分支(预约不匹配):`'part_available_qty': float(part_total) if part_total is not None else None,` +- `ok` 分支与 `shortage` 分支:同上键。 + +- [ ] **Step 4: 运行确认通过** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py -q` +Expected: 全部 PASS(含既有用例,证明缺口判定未变) + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/stp_line_inventory_match.py backend/tests/test_shipping_stp_phase4_line_inventory_match.py +``` + +--- + +### Task 2: 模型新列 + Alembic 迁移 + +**Files:** +- Modify: `backend/app/models/shipping_notice_line_inventory_match.py:104-106`(数量列区) +- Create: `backend/migrations/versions/_add_part_available_qty_to_line_matches.py` + +**Interfaces:** +- Produces: `ShippingNoticeLineInventoryMatch.part_available_qty: Mapped[Optional[str]]`(String(32) nullable,与 `available_qty` 同风格——数量以字符串化 Decimal 持久化)。 + +- [ ] **Step 1: 改模型** + +在 `shortage_qty` 列(:106)之后加: + +```python + # 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。 + # 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。 + part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) +``` + +- [ ] **Step 2: 生成迁移** + +```bash +cd backend && ./.venv/Scripts/python.exe -m flask db migrate -m "add part_available_qty to shipping_notice_line_inventory_matches" +``` + +检查生成的迁移文件:仅含 `op.add_column('shipping_notice_line_inventory_matches', sa.Column('part_available_qty', sa.String(32), nullable=True))` 与对应 `drop_column`;确认 `down_revision` 指向当前 head(`flask db heads` 核对单头)。 + +- [ ] **Step 3: 升级并验证** + +```bash +cd backend && ./.venv/Scripts/python.exe -m flask db upgrade && ./.venv/Scripts/python.exe -m flask db downgrade && ./.venv/Scripts/python.exe -m flask db upgrade +``` + +Expected: upgrade/downgrade/upgrade 均无错误(本地 dev 库)。 + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/models/shipping_notice_line_inventory_match.py backend/migrations/versions/ +``` + +--- + +### Task 3: 持久化写入 part_available_qty + +**Files:** +- Modify: `backend/app/services/shipping_notice/line_inventory_match_persistence.py`(新建行分支约 :266-305;更新分支约 :352-382) +- Test: `backend/tests/test_line_inventory_match_persistence.py` + +**Interfaces:** +- Consumes: Task 1 的 `line_results[i]['part_available_qty']`。 +- Produces: `ShippingNoticeLineInventoryMatch.part_available_qty`(`str(qty)` 或 None)。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_line_inventory_match_persistence.py` 追加(复用该文件既有夹具构造 task/snapshot/match_payload): + +```python +def test_persist_writes_part_available_qty_for_not_found_line(): + """预约不匹配行的料号兜底总量必须随匹配事实落库。""" + # 复用文件内既有 persist 测试夹具(task + inventory snapshot + 冻结候选), + # match_payload 的 line_results[0] 使用 disposition='not_found' 并附 + # 'part_available_qty': 8.0(构造方式对齐文件内首个 not_found 用例)。 + rows = persist_line_inventory_match_facts(task=task, match_payload=match_payload) + # 断言意图:兜底总量字符串化落列;无键/None 时必须落 NULL 而非 'None'。 + assert str(rows[0].part_available_qty) == '8.0' +``` + +(执行者按该文件现有用例的夹具名补齐构造代码;断言语义必须保留本注释所述两点。) + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_persistence.py -q -k part_available` +Expected: FAIL(AttributeError: part_available_qty) + +- [ ] **Step 3: 实现** + +新建行分支(`row = ShippingNoticeLineInventoryMatch(...)`)在 `shortage_qty=...` 之后加: + +```python + part_available_qty=( + str(result['part_available_qty']) + if result.get('part_available_qty') is not None else None + ), +``` + +更新分支(`existing.xxx = ...` 区)对应加: + +```python + existing.part_available_qty = ( + str(result['part_available_qty']) + if result.get('part_available_qty') is not None else None + ) +``` + +注意:BE-5 守卫(`snap_id is None` → result_missing)与 `not_found 强制 available=0` 分支不需改——`part_available_qty` 直接取匹配器原值;`snap_id is None` 时匹配器本身无库存行、值为 None,天然一致。 + +- [ ] **Step 4: 运行确认通过** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_persistence.py -q` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/line_inventory_match_persistence.py backend/tests/test_line_inventory_match_persistence.py +``` + +--- + +### Task 4: 投影层透出料号总可用量 + +**Files:** +- Modify: `backend/app/services/shipping_notice/line_inventory_match_projection.py`(`serialize_match_fact` :544-590;`project_line_inventory_view` :597-798) +- Test: `backend/tests/test_line_inventory_match_projection.py` + +**Interfaces:** +- Consumes: Match 行列 `part_available_qty`(Task 3)。 +- Produces: + - `serialize_match_fact(row)['part_available_qty'] -> str | None`(Task 7 自动放行服务经 `load_current_match_facts_by_task` 消费) + - `project_line_inventory_view(...)['part_available_qty'] -> str | None`(仅 `inventory_status=='ready'` 时有值,否则 None;Task 5 ui_state 消费) +- 不做的事:不派生「可兜底放行」布尔字段——自动放行判定在 Task 7 服务内基于行事实现算,投影层无人消费该标志(YAGNI)。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_line_inventory_match_projection.py` 追加: + +```python +def test_view_exposes_part_available_qty_gated_by_ready(): + """料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。""" + base = { + 'match_result': 'not_found', 'inventory_status': 'ready', + 'required_qty': '8', 'available_qty': None, + 'inventory_snapshot_id': 1, 'matched_at': None, + 'inventory_source_code': 'DSV', 'detail_json': {}, + } + view = project_line_inventory_view( + has_formal_ot=True, fact={**base, 'part_available_qty': '9'}, + required_qty='8', stored_line_status=None, decision_source=None, + can_fulfill_complete_line=False, + ) + # 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。 + assert view['available_qty'] == '0' + assert view['part_available_qty'] == '9' + pending = project_line_inventory_view( + has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'}, + required_qty='8', stored_line_status=None, decision_source=None, + can_fulfill_complete_line=False, + ) + # 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。 + assert pending['part_available_qty'] is None +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_projection.py -q -k part_available` +Expected: FAIL(KeyError) + +- [ ] **Step 3: 实现** + +`serialize_match_fact` 返回 dict 加(`'shortage_qty': row.shortage_qty,` 之后): + +```python + 'part_available_qty': getattr(row, 'part_available_qty', None), +``` + +`project_line_inventory_view`: + +1. 在 `qty = normalize_match_quantities(...)` 之后加: + +```python + # [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控); + # 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。 + part_total = _parse_qty(fact.get('part_available_qty')) + part_available_value = ( + str(part_total) if inventory_status == STATUS_READY and part_total is not None else None + ) +``` + +2. `has_formal_ot` 为 False 的早退 return 增加形状一致性键:`'part_available_qty': None,`。 +3. 主 return 增加:`'part_available_qty': part_available_value,` + +- [ ] **Step 4: 运行确认通过** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_projection.py tests/test_line_inventory_allowed_actions.py -q` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/line_inventory_match_projection.py backend/tests/test_line_inventory_match_projection.py +``` + +--- + +### Task 5: ui_state prep 行下发新字段 + +**Files:** +- Modify: `backend/app/services/shipping_notice/ui_state.py`(preparation_lines 组装 :966-997) +- Test: `backend/tests/test_shipping_notice_ui_state.py` + +**Interfaces:** +- Consumes: Task 4 的 `inv_view['part_available_qty']`。 +- Produces: `ui_state.stage_context.preparation.lines[i].part_available_qty: str | None`(前端 Task 9 新列消费;不加派生布尔——自动放行由 Task 7 服务判定,UI 只展示「已放行」结果状态)。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_shipping_notice_ui_state.py` 现有 preparation 投影用例(`test_stage_context_preparation_*` 系列旁)追加,夹具对齐同文件现有 prep 用例: + +```python +def test_preparation_lines_carry_part_available_qty(): + """prep 行必须下发料号兜底总量,供前端新增「可用数量」列。""" + # 复用文件内 prep stage_context 夹具;行 Match 事实 part_available_qty='9'、required '8'。 + line = state['stage_context']['preparation']['lines'][0] + # 断言意图:ui_state 单源直透投影值,前端不做二次推导。 + assert line['part_available_qty'] == '9' +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_notice_ui_state.py -q -k part_available` +Expected: FAIL(KeyError: 'part_available_qty') + +- [ ] **Step 3: 实现** + +`preparation_lines.append({...})` 在 `'shortage_qty': inv_view.get('shortage_qty'),` 之后加: + +```python + 'part_available_qty': inv_view.get('part_available_qty'), +``` + +- [ ] **Step 4: 运行确认通过** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_notice_ui_state.py -q` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_shipping_notice_ui_state.py +``` + +--- + +### Task 6: 放行补录字段按料号兜底带出 + +**Files:** +- Modify: `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py`(`_shortage_release_required_fields` :314-414;调用点:本文件 :918-922(Case 投影)、`decide_review_line_fulfillment` 内校验/落库区 :1117-1256;`backend/app/services/shipping_notice/ui_state.py:946-960` 的调用点) +- Test: `backend/tests/test_shipping_review_line_fulfillment_decision.py` + +**Interfaces:** +- Consumes: `ShippingInventoryField.field_code`(`'part_number'` / `'reservation_id'`)、`read_inventory_file_lines(snapshot)` 行 dict(含 field_id 键与 canonical 键)。 +- Produces: + - `_shortage_release_required_fields(...) -> tuple[list[dict[str, Any]], str]`——`(fields, evidence_scope)`,`evidence_scope ∈ {'inventory_snapshot', 'part_fallback'}`; + - `decide_review_line_fulfillment` 落库 `snapshot_json['release_field_values']` 从「仅人工补录项」扩展为「自动带出 + 人工补录」**全量**模板字段值字典(导出覆盖读取该字典,见需求假设 4);`snapshot_json['release_evidence_scope']` 记录证据范围。 + - 放行资格校验(`_is_shortage_match_fact` 409)**不变**;`_validate_inventory_shortage_release_fields` 的必填校验**不变**(人工必填项缺失仍 409),仅其返回值不再是落库字典的唯一来源。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_shipping_review_line_fulfillment_decision.py` 追加(夹具对齐该文件 `test_shortage_release_requires_template_inventory_field_when_snapshot_value_is_ambiguous`——同一套 source/template/profile/快照行构造,把快照行的预约号改为与订单行不同、料号相同): + +```python +def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses(): + """预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。""" + # 构造:profile.match_keys=[reservation_id, part_number];快照行预约号 'R-INV' ≠ 订单行 'R-ORDER', + # 料号相同;模板消费的库存字段在该行有唯一值。 + fields, scope = _shortage_release_required_fields( + task=task, line_index=line_index, + inventory_snapshot_id=snapshot.id, inventory_source_code='DSV', + ) + # 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual), + # 且证据范围显式标记为 part_fallback(审计可见)。 + assert scope == 'part_fallback' + assert all(not field['requires_manual'] for field in fields) + + +def test_shortage_release_part_fallback_still_manual_when_values_ambiguous(): + """料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。""" + # 构造同上,但两条同料号快照行在该模板字段上取值不同。 + fields, scope = _shortage_release_required_fields( + task=task, line_index=line_index, + inventory_snapshot_id=snapshot.id, inventory_source_code='DSV', + ) + # 断言意图:scope 仍标记 part_fallback,但分歧字段 requires_manual=True。 + assert scope == 'part_fallback' + assert any(field['requires_manual'] for field in fields) +``` + +再补一条 decide 集成断言(复用既有 `test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact` 的场景,把快照行预约号改不匹配): + +```python +def test_shortage_release_decision_records_part_fallback_scope(): + """放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。""" + # ...复用既有放行 decide 流程断言,另断言: + # 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」。 + assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback' + + +def test_shortage_release_persists_full_template_field_values(): + """落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。""" + # 复用上面预约不匹配场景(字段全部自动带出、无人工补录项),提交放行时 + # release_field_values 传空 dict: + # 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读 + # snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空。 + assert decision.snapshot_json['release_field_values'] == {'102': 'ODM-001'} # field_id→值,按夹具实际字段 +``` + +> ⚠ 既有用例若断言 `release_field_values` 只含人工提交项(如 `test_shortage_release_rejects_missing_template_inventory_override`),其「缺失仍 409」断言必须保留通过;仅「落库字典内容」断言按全量语义更新。 + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py -q -k part_fallback` +Expected: FAIL + +- [ ] **Step 3: 实现** + +1. `_shortage_release_required_fields` 改为返回 `tuple`。候选行筛选段(现 :388-391)替换为: + +```python + candidates = [ + dict(row) for row in inventory_lines + if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) + ] + evidence_scope = 'inventory_snapshot' + if not candidates: + # [STEP] 料号兜底(2026-10 需求):预约键在库存中无命中时,按料号键重筛证据行。 + # 仅识别 field_code='part_number' 的匹配键;识别不到则维持空候选(全人工补录,fail-closed)。 + part_field_ids = { + int(field_id) for field_id, _value in expected + if str(getattr(ShippingInventoryField.query.get(int(field_id)), 'field_code', '') or '') == 'part_number' + } + if part_field_ids: + candidates = [ + dict(row) for row in inventory_lines + if all(_match_text(row.get(str(field_id))) == value + for field_id, value in expected if int(field_id) in part_field_ids) + ] + if candidates: + evidence_scope = 'part_fallback' +``` + +函数末尾 `return _release_template_inventory_fields(...)` 改为 `return _release_template_inventory_fields(...), evidence_scope`(`snapshot is None` 的早退分支返回 `([...], 'inventory_snapshot')`)。 + +2. 更新两个调用点接收元组(**只取 fields,scope 不进投影契约**——前端本期不消费,避免死字段;scope 仅在 3 的决策快照落值): + - Case 投影(本文件 :918-922):`fields, _scope = _shortage_release_required_fields(...)`,行投影结构不变。 + - `ui_state.py:946-960`:同样 `fields, _scope = ...`,prep 行结构不变。 +3. `decide_review_line_fulfillment`:放行分支调用处解包,并把 `'release_evidence_scope': evidence_scope` 写入 `snapshot_json`(现 :1223-1256 的 dict 字面量)。 +4. `release_field_values` 落库改为**全量**模板字段值:`{field['field_id']: (人工提交值 if field_id in 人工必填 else field['value']) for field in fields}`——即以自动带出值为底、人工提交值覆盖;`_validate_inventory_shortage_release_fields` 的必填校验与白名单校验保持原样(人工必填缺失仍 409),仅落库字典不再经白名单裁剪。 + +- [ ] **Step 4: 运行确认通过** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py tests/test_shipping_notice_ui_state.py -q` +Expected: PASS(既有放行用例不回归——预约命中场景 scope 恒为 'inventory_snapshot') + +- [ ] **Step 5: 守护 Excel 不变** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py tests/test_shipping_stp_match_completed_gate.py -q` +Expected: 全绿(未改任何导出/波次/聚合代码的证明) + +- [ ] **Step 6: Stage** + +```bash +git add backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/app/services/shipping_notice/ui_state.py backend/tests/test_shipping_review_line_fulfillment_decision.py +``` + +--- + +### Task 7: 料号兜底自动放行服务 + +**Files:** +- Modify: `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py`(从 `decide_review_line_fulfillment` 放行分支提取共享内部函数;新增 `auto_release_part_fallback_shortages`) +- Modify: `backend/app/services/shipping_notice/fulfillment_workflow.py`(`match_inventory` :1775-1870 尾部、`match_inventory_line` :1272 附近落库后挂钩子) +- Test: `backend/tests/test_shipping_review_line_fulfillment_decision.py`、`backend/tests/test_shipping_stp_match_completed_gate.py` + +**Interfaces:** +- Consumes: Task 4 的行事实(`part_available_qty`,经 `load_current_match_facts_by_task`)、Task 6 的证据解析(`_shortage_release_required_fields` 全自动取值)。 +- Produces: + - `_apply_shortage_line_release(task, line_index, release_field_values, *, evidence_scope, actor_type, actor_id, auto_release: bool) -> ShippingOrderReviewLineDecision`——人工 decide 与自动放行共用的落库+审计+`_sync_confirmed_task_fulfillment_gates` 执行体(从现 :1117-1256 放行分支原样提取,行为不变); + - `auto_release_part_fallback_shortages(task, *, actor_id=None) -> list[int]`——返回自动放行的 line_index 列表;单行异常捕获记审计,不中断整批。 + +- [ ] **Step 1: 写失败测试** + +在 `backend/tests/test_shipping_review_line_fulfillment_decision.py` 追加(复用既有放行夹具 + Task 6 的预约不匹配快照行构造;匹配夹具对齐 `test_shipping_stp_match_completed_gate.py` 的 match 构造): + +```python +def test_auto_release_runs_after_match_when_part_total_satisfies(): + """料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。""" + # 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、 + # 模板字段全部可由料号命中的快照行唯一取值。执行 match_inventory(...)。 + decision = 活动放行决定(task) # 按文件内既有 helper 读取活动 release_inventory_shortage 决定 + # 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。 + assert decision is not None + assert decision.snapshot_json['auto_release'] is True + assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback' + + +def test_auto_release_skips_when_part_total_below_required(): + """料号兜底量不足时不得自动放行,行保持人工待处置。""" + # 同上构造,但料号总量改为 3(< 8)。 + # 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。 + assert 活动放行决定(task) is None + + +def test_auto_release_skips_when_evidence_field_ambiguous(): + """证据字段无法唯一取值(requires_manual 残留)时不得自动放行。""" + # 同上构造,但两条同料号快照行在模板字段上取值不同。 + # 断言意图:降级为人工放行(补录要求保留),不产生自动决定。 + assert 活动放行决定(task) is None + + +def test_auto_release_does_not_duplicate_existing_decision(): + """已有人工放行/结案决定(或已放行)的行不得重复自动放行。""" + # 先人工放行该行,再重跑 match_inventory。 + # 断言意图:幂等——不新建第二个活动决定,原决定保持不变。 + assert 活动决定数量(task, 'release_inventory_shortage') == 1 + + +def test_auto_release_counted_in_sufficiency_and_gate_releases(): + """自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。""" + # 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过, + # inventory_sufficiency 不再因该行 blocked_manual。 + assert match_completed(task) is True +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py -q -k auto_release` +Expected: FAIL(无自动放行行为) + +- [ ] **Step 3: 实现** + +1. **提取共享执行体**:把 `decide_review_line_fulfillment` 放行分支的落库段(创建/激活 `ShippingOrderReviewLineDecision`、`_validate_inventory_shortage_release_fields` 调用、`_sync_confirmed_task_fulfillment_gates`、审计)原样提取为 `_apply_shortage_line_release(...)`(签名见 Interfaces);decide 分支改为调用它(行为零变化,既有用例守护)。 +2. **自动放行服务**(同文件新增): + +```python +def auto_release_part_fallback_shortages( + task: ShippingNotice, + *, + actor_id: int | None = None, +) -> list[int]: + """ + 匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。 + + 核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可 + 自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工 + 路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动 + 履约入队与人工放行完全一致;幂等由「已放行行跳过」保证,不自动撤销既有放行。 + + Args: + task: 正式任务聚合根。 + actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。 + + Returns: + 自动放行的 line_index 列表。 + """ + released: list[int] = [] + facts = load_current_match_facts_by_task(getattr(task, 'id', None)) + decided_indexes = 活动决定行索引集合(task) # 复用既有查询:release/close 活动决定的 line_index + for line_index, fact in sorted(facts.items()): + try: + required = _parse_qty(fact.get('required_qty')) + part_total = _parse_qty(fact.get('part_available_qty')) + if line_index in decided_indexes: + continue + if not _is_shortage_match_fact(fact): + continue + if part_total is None or required is None or part_total < required: + continue + fields, evidence_scope = _shortage_release_required_fields( + task=task, line_index=line_index, + inventory_snapshot_id=fact.get('inventory_snapshot_id'), + inventory_source_code=fact.get('inventory_source_code'), + ) + if any(bool(field.get('requires_manual')) for field in fields): + continue + auto_values = { + str(field['field_id']): field.get('value') + for field in fields + } + _apply_shortage_line_release( + task, line_index, auto_values, + evidence_scope=evidence_scope, actor_type='system', actor_id=actor_id, + auto_release=True, + ) + released.append(line_index) + except ConflictError: + # 证据不可解析(无源/模板未发布/无快照)→ 维持人工路径,不中断其余行。 + continue + return released +``` + +(`_parse_qty` 从 `line_inventory_match_projection` 复用;`活动决定行索引集合`/`活动放行决定` 按文件内既有查询 helper 落地。) + +3. **匹配钩子**:`fulfillment_workflow.py` 的 `match_inventory`(持久化与聚合重算完成、return 之前)与 `match_inventory_line`(行持久化之后)加: + +```python + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + auto_release_part_fallback_shortages, + ) + + auto_released = auto_release_part_fallback_shortages(task) + if auto_released: + # 自动放行内部已重算聚合并同步门禁/自动履约;此处仅在审计上记录匹配触发的放行。 + ... +``` + +(`match_inventory` 末尾的 `match_completed` 判定放在钩子**之后**执行,使放行行计入满足、任务可直接落 `MATCHED_FULFILLABLE`;`match_inventory_line` 同理在其聚合重算前挂钩子。若提取后顺序约束冲突,以「先钩子后聚合判定」为准并加注释说明。) + +- [ ] **Step 4: 运行确认通过 + 守护不变** + +```bash +cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py tests/test_shipping_stp_match_completed_gate.py tests/test_shipping_line_scoped_inventory_retry.py tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py -q +``` + +Expected: 全绿。特别核对:`test_match_completed_rejects_partial`(未达兜底的 partial 行仍阻断)、波次用例(出单仍需人工勾选,自动放行只是让行获得可勾选资格)。 + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/app/services/shipping_notice/fulfillment_workflow.py backend/tests/test_shipping_review_line_fulfillment_decision.py +``` + +--- + +### Task 8: 前端 i18n 四语言新增键 + +**Files:** +- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json`(`shippingOrderReview.lifecycle.prepare` 块,zh-CN 约 :1721-1737;**该块为单行 JSON**,用 Edit 工具精确子串替换) + +**Interfaces:** +- Produces: `chat.shippingOrderReview.lifecycle.prepare.reservedQty`、`.partAvailableQty`,Task 9 模板消费。 + +- [ ] **Step 1: 四语言各加两键** + +在每语言 `lifecycle.prepare` 对象内 `"requiredQty"` 键旁插入(保持键序:`requiredQty` 之后): + +| 键 | zh-CN | zh-TW | en | th | +| --- | --- | --- | --- | --- | +| `reservedQty` | `预约数量` | `預約數量` | `Reserved qty` | `จำนวนตามใบจอง` | +| `partAvailableQty` | `可用数量` | `可用數量` | `Available qty` | `จำนวนที่ใช้ได้` | + +示例(zh-CN,`"requiredQty": "需求数量",` 后插入): + +```json +"reservedQty": "预约数量", "partAvailableQty": "可用数量", +``` + +- [ ] **Step 2: 校验 JSON 合法** + +```bash +cd frontend && node -e "['zh-CN','zh-TW','en','th'].forEach(l=>{JSON.parse(require('fs').readFileSync('src/locales/'+l+'/chat.json','utf8'));console.log(l+' ok')})" +``` + +Expected: 四行 ok + +- [ ] **Step 3: Stage** + +```bash +git add frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json +``` + +--- + +### Task 9: 前端类型 + 库存匹配表列改造 + spec + +**Files:** +- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`(prep 行匿名类型 :1522-1545) +- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(表头 :5332、单元格 :5333、`formalPreparationLines` :2565-2573、releaseBar colspan :5333 内 `colspan="12"`) +- Test: `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts` + +**Interfaces:** +- Consumes: 后端 prep 行 `part_available_qty`(Task 5)、i18n 键(Task 8)。 +- Produces: 表格列序 `… 需求数量 | 库存源 | 预约数量 | 可用数量 | 缺口 | 匹配状态 …`。 + +- [ ] **Step 1: 类型扩展** + +仅 prep 行匿名类型(:1531 `available_qty` 旁)加: + +```typescript + /** 料号维度总可用量(忽略预约号、行允许源内汇总);无快照/未就绪为 null。 */ + part_available_qty?: string | null; +``` + +(不动 `ShippingOrderReviewLineFulfillmentLine`——Case 行投影本期不下发该字段,不加备用字段。) + +- [ ] **Step 2: 更新 spec 断言(先写失败测试)** + +`ShippingOrderReviewView.spec.ts`: + +1. i18n mock(:648 附近 `fulfillmentDecision` 同级或 `prepare` mock 块)补 `reservedQty: '预约数量', partAvailableQty: '可用数量'`(对齐该 mock 的组织方式)。 +2. 在既有 prep workspace 用例(:2689 附近 prep line mock `available_qty: null` 处)给 prep 行加 `part_available_qty: '9'`,并新增断言: + +```typescript + // 断言意图:原可用数量列头改由 reservedQty 键渲染(预约数量), + // 新增料号总库存列紧随其后,值来自 part_available_qty。 + const headers = Array.from(workspace.querySelectorAll('thead th')).map((th) => th.textContent); + expect(headers).toContain('预约数量'); + expect(headers.indexOf('可用数量')).toBe(headers.indexOf('预约数量') + 1); + expect(workspace.textContent).toContain('9'); +``` + +(挂载/查询方式对齐该用例现有写法。) + +- [ ] **Step 3: 运行确认失败** + +Run: `cd frontend && npx vitest run src/features/chat/views/ShippingOrderReviewView.spec.ts`(若 vitest 环境仍损坏——node:crypto 问题——则跳过本步与 Step 6,以 `npm run build` + 人工核对代替,并在任务备注中说明) + +Expected: FAIL + +- [ ] **Step 4: 视图改造** + +1. `formalPreparationLines`(:2565-2573)的映射对象加: + +```typescript + part_available_qty: + line.part_available_qty == null ? null : displayDecimalQty(line.part_available_qty), +``` + +2. 表头(:5332)把 `{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}` 替换为: + +```html +{{ t('chat.shippingOrderReview.lifecycle.prepare.reservedQty') }}{{ t('chat.shippingOrderReview.lifecycle.prepare.partAvailableQty') }} +``` + +3. 单元格(:5333)把 `{{ line.available_qty ?? '—' }}` 替换为: + +```html +{{ line.available_qty ?? '—' }}{{ line.part_available_qty ?? '—' }} +``` + +(原绑定保留=预约数量列;新列取 `part_available_qty`。pending 态后端已下发 null,无需前端再判。) + +4. 同一单元格行内的 releaseBar 展开行 `0` 为准)、`preparationWaveSelectableLines`、`linesTableColumnCount`(那是订单明细表 colspan,明细表不动)。 + +- [ ] **Step 5: 构建 + 测试** + +```bash +cd frontend && npm run build +``` + +Expected: 构建通过(vitest 环境损坏期间的替代验收,见 docs 记忆「vitest 环境损坏」)。 + +- [ ] **Step 6: Stage** + +```bash +git add frontend/src/features/chat/types/shipping.api.types.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +``` + +--- + +### Task 10: 文档同步 + +**Files:** +- Modify: `docs/features/shipping-notice/technical.md`(文末追加章节) +- Modify: `docs/features/shipping-notice/business.md`(追加业务规则节) +- Modify: `docs/funclist.md`(shipping-notice 表追加 1-2 行) +- Modify: `docs/demand.md`(缺口放行规则变化说明) + +- [ ] **Step 1: technical.md 追加「料号兜底自动放行与数量列(2026-10-09)」** + +要点(只追加不改史):缺口判定仍按预约+料号;匹配器下发 `part_available_qty`(口径=行允许源内、忽略预约号、不限单位;跨源不合并;conflict/invalid/缺料号不下发);新列 `shipping_notice_line_inventory_matches.part_available_qty`(迁移),投影/ui_state 仅透出该数量;**自动放行**:匹配落库后对「缺口+料号总量≥需求+证据字段全部自动取值」的行由系统创建放行决定(`auto_release: true`、`release_evidence_scope` 审计;证据不可解析/字段分歧/总量不足时降级人工;不自动撤销);`release_field_values` 扩展为全量字段值(导出覆盖来源);Excel/波次条件不变(出单仍需人工勾选波次,放行行可勾选资格不变);存量行为 NULL 不回填。并注明:明细表/聊天匹配卡的「可用数量」仍是预约匹配语义,与 prep 表新「可用数量」(料号总量)同名不同义,是否统一待产品定。 + +- [ ] **Step 2: business.md / demand.md / funclist.md** + +- business.md:新增「缺口放行(料号兜底自动放行)」小节:料号总库存满足需求时系统自动放行(无需人工确认),放行证据带出优先级(预约匹配 → 料号兜底);证据无法自动取值或料号总量不足时降级为人工放行;Excel 出单条件表述不变(出单仍由用户勾选触发)。 +- demand.md:在库存缺口/放行相关需求条目下补充该规则变化。 +- funclist.md:shipping-notice 表加行「库存匹配料号兜底自动放行与料号维度可用数量展示(已实现)」。 + +- [ ] **Step 3: Stage** + +```bash +git add docs/features/shipping-notice/technical.md docs/features/shipping-notice/business.md docs/funclist.md docs/demand.md +``` + +--- + +### Task 11: 全量回归 + +- [ ] **Step 1: 后端定向回归** + +```bash +cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py tests/test_line_inventory_match_persistence.py tests/test_line_inventory_match_projection.py tests/test_line_inventory_allowed_actions.py tests/test_shipping_notice_ui_state.py tests/test_shipping_review_line_fulfillment_decision.py tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py tests/test_shipping_stp_match_completed_gate.py tests/test_shipping_line_scoped_inventory_retry.py -q +``` + +Expected: 全绿(既有 6 个已知 WIP 失败不在上述文件中;若出现需先比对 HEAD 判断归属)。 + +- [ ] **Step 2: 前端构建** + +```bash +cd frontend && npm run build +``` + +Expected: 通过。 + +- [ ] **Step 3: 人工冒烟清单(test 环境部署后)** + +1. 通知准备存在「预约不匹配但料号总量足够」的行:重取库存/重新匹配后**行自动变为「已放行」**(无需人工点击),表格显示 预约数量 0 / 可用数量(料号总量)≥需求。 +2. 自动放行行获得出单资格:勾选生成 Excel 行数计入;导出 Excel 中该行证据列有值(来自料号命中行)。 +3. 料号总量也不足的行:可用数量显示不足值,行保持「库存不足」,人工放行时补录字段按预约优先→料号兜底带出,剩余项人工必填。 +4. 证据字段存在分歧(同料号多行值不一致)的行:不自动放行,维持人工补录。 +5. 「重新匹配库存 / 重新获取库存」后历史 NULL 行回填新列;已自动放行的行重匹配后不重复建决定、不撤销。 + +--- + +## Self-Review 记录 + +- 规格覆盖:需求点 1(列改名)→ Task 8/9;需求点 2(新增料号可用数量列)→ Task 1-5/8/9;料号兜底**自动放行** → Task 6(证据全量带出+落库)+ Task 7(自动放行服务与匹配钩子);Excel/波次条件不变 → 全局不动清单 + Task 6/7 守护步骤;文档 → Task 10。 +- 占位符扫描:Task 3/5/6/7 的测试步骤要求执行者对齐既有夹具(夹具构造依赖运行时数据库对象,不适合在本计划内伪写完整代码),已给出断言语义注释与对齐用例名,属可执行指引而非 TODO;Task 7 服务实现中的 `活动决定行索引集合`/`活动放行决定` 为既有查询 helper 的语义占位,执行者按文件内现有决定查询落地。 +- 类型一致性:`part_available_qty` 链路 float(匹配器)→ String(32) 列(持久化)→ str(serialize/投影/ui_state)→ `string | null`(TS)一致;`evidence_scope` 在 Task 6/7 流转并在决策快照落值;自动放行复用 `_apply_shortage_line_release` 单一执行体,无平行落库路径。 diff --git a/frontend/src/features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue b/frontend/src/features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue index b3821fa1..23507efb 100644 --- a/frontend/src/features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue +++ b/frontend/src/features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue @@ -877,7 +877,6 @@ onMounted(() => { } .edit-card .input-field, .impact-dialog .input-field, .impact-dialog .select-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; } .actions, .impact-dialog footer { display: flex; flex-wrap: wrap; gap: 8px; } -.impact-dialog footer { justify-content: flex-end; } .link-list, .plain-list { margin: 0; padding-left: 1.1rem; color: #475569; font-size: 13px; } .adoption-link { color: #0369a1; text-decoration: underline; text-underline-offset: 2px; } .adoption-link:hover { color: #0c4a6e; } @@ -924,10 +923,12 @@ onMounted(() => { background: var(--overlay-soft); padding: 24px; } .impact-dialog { - display: grid; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow: auto; + display: grid; grid-auto-rows: max-content; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow-y: auto; border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); } .impact-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +/* footer 用 sticky 钉在对话框可视底部:内容超高时确认/取消始终可见,不随表单或影响列表滚动消失(负 margin 抵消对话框 padding 实现通栏) */ +.impact-dialog footer { position: sticky; bottom: -18px; justify-content: flex-end; margin: 4px -18px -18px; border-top: 1px solid var(--border-default); background: #fff; padding: 12px 18px; } .impact-dialog h2, .impact-dialog p { margin: 0; } .impact-summary { display: grid; gap: 8px; border: 1px solid #fecaca; border-radius: 8px; diff --git a/frontend/src/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue b/frontend/src/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue index cce2d013..384fe94f 100644 --- a/frontend/src/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue +++ b/frontend/src/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue @@ -316,14 +316,15 @@ onMounted(() => { void load(); }); .identity-hero h1 { margin: 0; } .identity-hero p { max-width: 760px; } .identity-hero__meta { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; justify-content: flex-end; } -.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bfe7f8; border-radius: 999px; background: #effaff; color: #087aaa; font-size: .78rem; font-weight: 700; white-space: nowrap; } -.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #18b17c; box-shadow: 0 0 0 4px #dff8ed; }.identity-pulse--draft { background: #e09b22; box-shadow: 0 0 0 4px #fff2d5; } +/* 状态/品牌色统一 Tailwind 标准语义值(brand=sky 系 #0284c7、启用=green、草稿=amber),不再使用自造蓝绿 */ +.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bae6fd; border-radius: 999px; background: #f0f9ff; color: #0369a1; font-size: .78rem; font-weight: 700; white-space: nowrap; } +.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #10b981; box-shadow: 0 0 0 4px #d1fae5; }.identity-pulse--draft { background: #f59e0b; box-shadow: 0 0 0 4px #fef3c7; } .identity-hero__link { display: inline-flex; align-items: center; gap: .35rem; white-space: nowrap; } .identity-flow { position: relative; display: grid; grid-template-columns: repeat(3, 1fr); gap: .6rem; padding: 1rem; overflow: hidden; border: 1px solid #dce9f2; border-radius: 1rem; background: linear-gradient(105deg, #f4fbff, #fff); } .identity-flow__rail { position: absolute; top: 1.84rem; left: 12%; right: 12%; height: 1px; background: #cce5f2; } .identity-flow__step { position: relative; z-index: 1; display: flex; gap: .75rem; align-items: flex-start; min-width: 0; } .identity-flow__step > span { display: grid; place-items: center; flex: 0 0 1.65rem; height: 1.65rem; border: 1px solid #b9d8e8; border-radius: 50%; background: #fff; color: #6b8298; font-size: .66rem; font-weight: 800; } -.identity-flow__step--active > span { border-color: #0d93cf; background: #0d93cf; color: #fff; box-shadow: 0 0 0 4px #dff4fc; } +.identity-flow__step--active > span { border-color: #0284c7; background: #0284c7; color: #fff; box-shadow: 0 0 0 4px #e0f2fe; } .identity-flow strong { display: block; color: #193652; font-size: .82rem; font-weight: 800; } .identity-flow small { display: -webkit-box; overflow: hidden; margin-top: .15rem; color: #7a8fa6; font-size: .72rem; line-height: 1.45; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .identity-loading { display: flex; align-items: center; gap: .5rem; padding: 2rem; color: #6f839b; font-size: .9rem; } @@ -336,12 +337,12 @@ onMounted(() => { void load(); }); .identity-definition-list { display: grid; } .identity-definition-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; gap: .75rem; align-items: center; padding: .78rem 1.35rem; border-bottom: 1px solid #edf3f7; transition: background .18s ease; } .identity-definition-row:hover { background: #f7fbfd; } -.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #e9f7fd; color: #0b90cc; } +.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #f0f9ff; color: #0284c7; } .identity-definition-row strong { color: #1a3856; font-size: .86rem; font-weight: 750; } .identity-definition-row p { overflow: hidden; margin-top: .18rem; color: #8194a8; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; } .identity-target, .identity-automation { padding: .32rem .52rem; border-radius: 999px; background: #f1f5f8; color: #677f98; font-size: .7rem; white-space: nowrap; } .identity-automation-select { border: 1px solid #dce8ef; cursor: pointer; } -.identity-automation--enabled { background: #e4f8ef; color: #12865c; } +.identity-automation--enabled { background: #dcfce7; color: #15803d; } .identity-empty { display: flex; align-items: center; gap: .55rem; min-height: 5.5rem; padding: 1.2rem 1.35rem; color: #7c91a7; font-size: .82rem; } .identity-definition-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .85rem; padding: 1.1rem 1.35rem 1.35rem; background: linear-gradient(135deg, #f7fbfd 0%, #f3f9fc 100%); } .identity-form-title { grid-column: 1 / -1; display: flex; align-items: center; gap: .42rem; color: #173857; font-size: .85rem; } @@ -349,13 +350,13 @@ onMounted(() => { void load(); }); .identity-definition-form label { display: grid; gap: .35rem; color: #667f99; font-size: .72rem; font-weight: 700; } .identity-label-with-tip { display: inline-flex; align-items: center; gap: .28rem; } .identity-label-tip { width: .9rem; height: .9rem; color: #7d93a8; cursor: help; } -.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7cc7eb; outline-offset: 2px; } +.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7dd3fc; outline-offset: 2px; } .identity-definition-form label small { color: #8295a8; font-size: .67rem; font-weight: 500; line-height: 1.35; } .identity-definition-form .input-field, .identity-static-field { box-sizing: border-box; min-width: 0; height: 2.75rem; padding: 0 .8rem; border-color: #d9e7ef; background: #fff; font-size: .83rem; line-height: 1.25; } .identity-definition-form select.input-field { padding-top: 0; padding-bottom: 0; line-height: 2.75rem; } .identity-static-field { display: flex; align-items: center; padding: 0 .8rem; border: 1px solid #d9e7ef; border-radius: .65rem; color: #5f7893; } .identity-source-help { display: grid; align-content: center; gap: .12rem; min-height: 2.75rem; padding: .48rem .7rem; border: 1px solid #d6eaf5; border-radius: .65rem; background: #edf8fe; color: #537189; font-size: .69rem; line-height: 1.35; } -.identity-source-help strong { color: #187eae; font-size: .72rem; }.identity-source-help small { color: #2e9068; font-size: .68rem; } +.identity-source-help strong { color: #0369a1; font-size: .72rem; }.identity-source-help small { color: #16a34a; font-size: .68rem; } .identity-definition-form__submit { display: inline-flex; align-items: center; justify-content: center; gap: .4rem; align-self: end; min-height: 2.5rem; } .identity-panel--publication { position: sticky; top: 1rem; padding: 1.25rem; } .identity-publication__header { display: flex; align-items: center; justify-content: space-between; gap: .75rem; } @@ -363,7 +364,7 @@ onMounted(() => { void load(); }); .identity-publication__hint { margin: .75rem 0 1rem; color: #75899f; font-size: .78rem; line-height: 1.6; } .identity-version-list { display: flex; flex-wrap: wrap; gap: .5rem; padding-bottom: 1rem; border-bottom: 1px solid #e9f0f4; } .identity-version { display: inline-flex; align-items: center; gap: .35rem; padding: .46rem .6rem; border: 1px solid #dbe7ee; border-radius: .6rem; background: #fff; color: #668099; font-size: .73rem; transition: all .18s ease; } -.identity-version:hover, .identity-version--selected { border-color: #0b91cd; background: #eefaff; color: #087cae; } +.identity-version:hover, .identity-version--selected { border-color: #0284c7; background: #f0f9ff; color: #0369a1; } .identity-version span { font-weight: 800; }.identity-version small { font-size: .68rem; } .identity-selection { margin: 1rem 0; } .identity-published-definitions { margin: 1rem 0; } @@ -374,12 +375,13 @@ onMounted(() => { void load(); }); .identity-published-definition small { margin-top: .15rem; color: #8194a8; font-size: .68rem; } .identity-published-empty { margin: 0; color: #8194a8; font-size: .76rem; } .identity-selection__heading { display: flex; justify-content: space-between; margin-bottom: .6rem; color: #274563; font-size: .78rem; font-weight: 750; } -.identity-selection__heading strong { color: #0a8bc4; } +.identity-selection__heading strong { color: #0284c7; } .identity-check-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: .5rem; padding: .54rem 0; border-bottom: 1px dashed #e2ebf1; color: #37516c; font-size: .78rem; } -.identity-check-row input { accent-color: #0c94ce; }.identity-check-row small { color: #8496a8; font-size: .68rem; } +/* @tailwindcss/forms 接管原生 checkbox 后 accent-color 无效:勾选填充取 currentColor,用 color 指定选中蓝 */ +.identity-check-row input { color: #0284c7; }.identity-check-row small { color: #8496a8; font-size: .68rem; } .identity-publication__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .65rem; padding-top: 1rem; } .identity-publication__actions .btn-primary, .identity-publication__actions .btn-ghost { min-width: 0; font-size: .79rem; } -.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #eaf9f0; color: #16895e; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #56826f; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; } +.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #dcfce7; color: #15803d; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #16a34a; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; } @media (max-width: 980px) { .identity-workbench { grid-template-columns: 1fr; }.identity-panel--publication { position: static; }.identity-hero { align-items: flex-start; flex-direction: column; gap: .85rem; }.identity-hero__meta { justify-content: flex-start; }.identity-flow__rail { display: none; } } @media (max-width: 700px) { .identity-rules-page { gap: 1rem; }.identity-flow { grid-template-columns: 1fr; }.identity-definition-form { grid-template-columns: 1fr; }.identity-definition-row { grid-template-columns: auto minmax(0, 1fr); }.identity-target, .identity-automation { justify-self: start; }.identity-panel__heading { align-items: flex-start; flex-direction: column; }.identity-panel__heading > p { text-align: left; }.identity-definition-row__icon { grid-row: span 2; }.identity-publication__actions { grid-template-columns: 1fr; } } @media (prefers-reduced-motion: reduce) { .identity-definition-row, .identity-version { transition: none; } } diff --git a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue index c29e9ed6..281eeb7c 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -146,8 +146,8 @@ - - + + @@ -172,8 +172,8 @@ - - + + @@ -356,7 +356,8 @@
{{ t('admin.shippingInventory.enabled') }}
-
+ +
- + @@ -399,7 +400,6 @@
-
@@ -1653,23 +1653,28 @@ onMounted(load); .row-secondary { color: #94a3b8; font-size: 11px; } .status-dot { position: absolute; top: 18px; right: 12px; width: 7px; height: 7px; border-radius: 50%; } .status-dot.on { background: #22c55e; } -.status-dot.off { background: #b2bdc9; } +.status-dot.off { background: #94a3b8; } .drawer-mask { position: fixed; z-index: 40; inset: 0; display: flex; justify-content: flex-end; background: var(--overlay-soft); } .workbench-actions { display: flex; flex-wrap: wrap; gap: 10px; } .clone-template-mask { z-index: 80; align-items: center; justify-content: center; padding: 20px; } .clone-template-dialog { width: min(480px, 100%); border-radius: 10px; background: #fff; box-shadow: 0 18px 48px rgb(15 23 42 / 25%); } .clone-template-header { display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid #e2e8f0; padding: 18px 20px; }.clone-template-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.clone-template-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; } .clone-template-form { display: grid; gap: 14px; padding: 20px; }.clone-template-form label { display: grid; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.clone-template-form .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.clone-template-form small { color: #94a3b8; font-size: 11px; line-height: 1.45; }.clone-template-actions { display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #edf2f7; padding-top: 14px; } -.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }.batch-source-option input { margin: 3px 0 0; accent-color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; } -.editor-drawer { width: min(760px, 100vw); height: 100%; overflow-y: auto; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); } -.drawer-header { position: sticky; z-index: 1; top: 0; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; } -.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #f2d3cd; border-radius: 999px; background: #fff4f1; padding: 3px 7px; color: #a53f30; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #c7e7d0; background: #eefaf1; color: #247442; } +.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }/* accent-color 在 @tailwindcss/forms 接管的原生 checkbox 上无效:勾选填充取 currentColor,用 color 指定选中蓝色 */ +.batch-source-option input { margin: 3px 0 0; color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; } +/* 抽屉为 flex 三段式:头部/底部操作栏固定,.editor-form 独占剩余高度并内部滚动,操作栏位置不受内容增减影响 */ +.editor-drawer { display: flex; flex-direction: column; width: min(760px, 100vw); height: 100%; overflow: hidden; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); } +.drawer-header { flex: 0 0 auto; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; } +/* 状态徽标统一 Tailwind 标准语义色:未启用=rose(与 components-ds 危险态一致)、启用=green(与 .status-switch 一致),不再用自造色值 */ +.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #fecdd3; border-radius: 999px; background: #fff1f2; padding: 3px 7px; color: #be123c; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; } .drawer-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; } .drawer-close { width: 30px; height: 30px; border: 0; border-radius: 6px; background: transparent; color: #64748b; font-size: 24px; line-height: 1; cursor: pointer; } .drawer-close:hover { background: #f1f5f9; color: #334155; } -.editor-form { display: grid; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; } +/* grid-auto-rows 必须 max-content:本表单是受限高度的滚动网格,Chrome 会把包含 overflow:hidden 子项(.path-card)的隐式 auto 行压缩到远小于内容的高度,裁掉查询条件/按钮;显式 max-content 强制行高按内容 sizing */ +.editor-form { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; } .editor-form label { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; } -.editor-form input, .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; } +/* checkbox/radio 必须排除:此处的 color 与 background 简写优先级更高,会覆盖 @tailwindcss/forms 的 :checked 样式(填充取 currentColor + 白色对钩背景图),导致勾选态与未勾选态渲染完全一致、无法分辨 */ +.editor-form input:not([type='checkbox']):not([type='radio']), .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; } .editor-form small { color: #94a3b8; font-size: 11px; font-weight: 400; line-height: 1.45; } .inventory-mapping-tabs { display: flex; gap: 4px; margin: 0 0 14px; border-bottom: 1px solid #e2e8f0; } .inventory-mapping-tabs button { border: 0; border-bottom: 2px solid transparent; background: transparent; padding: 8px 12px; color: #64748b; font: inherit; font-size: 13px; cursor: pointer; } @@ -1698,7 +1703,7 @@ onMounted(load); .path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; } .path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; } .path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; } -.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; } +.path-badge { flex: 0 0 auto; border-radius: 999px; background: #f1f5f9; padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #dcfce7; color: #15803d; } .path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; } .path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; } .condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; } @@ -1727,7 +1732,8 @@ onMounted(load); .condition-empty { color: #8190a0; font-size: 12px; } .inline-check { flex-direction: row !important; align-items: center; gap: 4px !important; white-space: nowrap; font-size: 11px !important; } .switch-field { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.status-switch { display: inline-flex; width: fit-content; align-items: center; gap: 7px; border: 0; background: transparent; padding: 2px 0; color: #94a3b8; font: inherit; font-size: 12px; cursor: pointer; }.status-switch i { position: relative; width: 34px; height: 20px; border-radius: 999px; background: #cbd5e1; transition: background .18s; }.status-switch i::after { position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 25%); content: ''; transition: transform .18s; }.status-switch.on { color: #15803d; }.status-switch.on i { background: #22c55e; }.status-switch.on i::after { transform: translateX(14px); }.status-switch b { font-weight: 500; } -.form-actions { position: sticky; z-index: 2; bottom: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; grid-column: 1 / -1; margin: 6px -20px -20px; border-top: 1px solid #dce6ef; background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); } +/* 底部操作栏是抽屉 flex 布局的独立层级:固定在抽屉底部,不随表单内容滚动/折叠区展开移动。模板中该栏位于 之后(不在 form 内),保存按钮为 type=button 显式 click 调用 saveCurrent,输入框回车提交仍走 form @submit */ +.form-actions { flex: 0 0 auto; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; border-top: 1px solid var(--border-default); background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); } .source-enabled-footer { display: flex; margin-right: auto; min-width: 0; align-items: center; gap: 10px; } .source-enabled-label { flex: 0 0 auto; color: #475569; font-size: 13px; font-weight: 600; } .source-enabled-hint { overflow: hidden; color: #94a3b8; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; } @@ -1741,7 +1747,7 @@ onMounted(load); .audit-table td strong, .audit-table td small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.audit-table td strong { color: #263850; font-weight: 600; }.audit-table td small { margin-top: 4px; color: #94a3b8; } .audit-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .audit-status { display: inline-flex; border-radius: 999px; padding: 3px 8px; font-size: 11px; white-space: nowrap; }.audit-status.ready { background: #dcfce7; color: #15803d; }.audit-status.failed { background: #fef2f2; color: #b91c1c; }.audit-status.neutral { background: #f1f5f9; color: #64748b; } -.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; } +.audit-detail dl { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; } .object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; } .empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; } @media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue index 442a59eb..c4daf3d3 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue @@ -206,8 +206,8 @@ onBeforeUnmount(stopSampleRefresh); .wizard-page { min-height: 100%; padding: 24px; background: #f6f8fc; } .wizard-shell { width: 100%; } .wizard-heading { margin-bottom: 28px; }.wizard-heading h1, .wizard-heading p { margin: 0; } -.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }.stepper li.active { color: #1677d2; }.stepper li.complete { color: #0f8a65; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #0f8a65; background: #0f8a65; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; } -.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #1677d2; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; } +.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }/* 步骤状态色统一 Tailwind 标准值:激活=brand-600、完成=green-600 */.stepper li.active { color: #0284c7; }.stepper li.complete { color: #16a34a; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #16a34a; background: #16a34a; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; } +.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #0284c7; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; } .wizard-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }.wizard-actions__spacer { flex: 1; } @media (max-width: 640px) { .wizard-page { padding: 24px 16px; }.stepper { grid-template-columns: 1fr; gap: 10px; }.stepper li:not(:last-child)::after { display: none; }.wizard-card { min-height: 300px; border-radius: 14px; }.wizard-actions { flex-wrap: wrap; }.wizard-actions__spacer { display: none; }.btn-secondary:first-child { margin-right: auto; } } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue index 0838f38a..604911a3 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue @@ -353,7 +353,7 @@ ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; } .metrics div { display: grid; gap: 4px; } .metrics dt { color: #64748b; font-size: 12px; } .metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; } -.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; } +.conflict-card { border: 1px solid #fecaca; background: #fef2f2; border-radius: 8px; padding: 12px; margin-top: 10px; } .conflict-card strong { color: #991b1b; font-size: 13px; } .conflict-card .reasons { color: #b45309; font-size: 12px; } @media (max-width: 767px) { diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue index 9c52f075..2c64d7db 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue @@ -688,8 +688,9 @@ watch( } .migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); } -.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); } -.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; } +.migration-dialog { display: grid; grid-auto-rows: max-content; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow-y: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); } +.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }/* footer 用 sticky 钉在对话框可视底部:breaking changes 列表长时取消/确认迁移按钮始终可见,不需滚回底部 */ +.migration-dialog footer { position: sticky; bottom: -1.5rem; display: flex; justify-content: flex-end; gap: .5rem; margin: 0 -1.5rem -1.5rem; border-top: 1px solid var(--border-default); background: var(--bg-surface); padding: 1rem 1.5rem 1.25rem; } @media (max-width: 960px) { .header-main, diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue index 1eafe116..cecf185e 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue @@ -127,5 +127,5 @@ onBeforeUnmount(stopPolling); diff --git a/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue b/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue index 3b7ba8b2..7ddaaf22 100644 --- a/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue @@ -1419,8 +1419,10 @@ onMounted(async () => { + + +
+

设备验收预警

+
+ 停留情况 + 发送记录 + 预警配置 +
+

四轮天数须逐轮增大。保存后只影响以后新产生的预警。发送时刻在排程里改。

+ +
+
+
+

升级轮次

+

左边改超过多少天。右边是这一轮的主送和抄送。COO、采购经副理、总经理各选一次,用到的轮次都显示同一个人。

+
+
+
+
+
+ 第 1 轮 + +
+
+
主送当前节点处理人
+
抄送其直接主管、采购担当
+ 随当前单据变化,这里不选人 +
+
+ +
+
+ 第 2 轮 + +
+
+
主送当前节点处理人的经副理
+
+ 抄送 +
+
+ S + sophie26030025 · COO + + +
+
+ S + sophie26030025 · 采购经副理 + + +
+
+
+
+
+ +
+
+ 第 3 轮 + +
+
+
+ 主送 +
+ S + sophie26030025 · COO + + +
+
+
+ 抄送 +
+ S + sophie26030025 · 采购经副理 + + +
+
+
+
+ +
+
+ 第 4 轮 + +
+
+
+ 主送 +
+ S + sophie26030025 · 总经理 + + +
+
+
+ 抄送 +
+
+ S + sophie26030025 · COO + +
+
+ S + sophie26030025 · 采购经副理 + +
+
+
+
+
+
+
+ 已发送记录保持不变 + +
+
+

效果图,尚未接到现有页面。

+
+ + diff --git a/docs/features/equipment-acceptance-warning/demand.md b/docs/features/equipment-acceptance-warning/demand.md index 5e5136fd..bcb4c1f7 100644 --- a/docs/features/equipment-acceptance-warning/demand.md +++ b/docs/features/equipment-acceptance-warning/demand.md @@ -1,8 +1,8 @@ # 设备验收预警需求说明 > **版本**:V1.0 -> **更新日期**:2026-10-07 -> **状态**:规则已冻结。验收单主表已明确为 E10 `ecology10.dbo.ft_gdzcysdv2`,当前节点表未提供。节点表到位前不写同步、计时和推送。数据设计见 [technical.md](technical.md)。 +> **更新日期**:2026-10-08 +> **状态**:规则已冻结。只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。发送时刻不在配置页,默认排程每天 06:00 扫描、每周五 18:00 发送。数据设计见 [technical.md](technical.md)。 > **适用范围**:OA 资产验收单停留预警、企业微信通知、固定岗位配置 ## 1. 背景与目标 @@ -17,14 +17,15 @@ - 监控对象、计时起点、自然日累计、停表与再进入规则。 - 四档升级的主送、抄送,以及当前节点处理人、上级、申请人的取人规则。 -- 采购经副理、COO、廖总三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。 +- 采购经副理、COO、总经理三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。 - 企业微信为唯一通知渠道。每日扫描只生成待发送记录;发送时刻可配置,初始为每周五 18:00,按收件人汇总一条。 - 数据来源见第 7 节。缺字段的单据跳过并留下原因。 +停留列表已接到对话页:内置 Chat Agent `equipment_acceptance`,与合同付款预警一样替换消息列表和输入框。 + ### 2.2 本期不做 -- 不写同步、计时、推送、配置界面和数据表。当前节点表到位后再开。 -- 不做聊天工作台,不接 Dify。 +- 不接 Dify 对话。 - 不撤回已发送的企业微信。停表只取消尚未发出的预警。 - 「使用部门担当」之前的节点(ERP 触发、申请人确认、直属上级)不参与计时。 @@ -44,9 +45,9 @@ - 归档 - 退回、撤回、作废 -- 验收单上为无法验收(无法验收说明从验收单抓取,只作留痕,不单独触发通知) +- 验收单上为无法验收(说明正文是 `ycsm`,只作留痕,不单独触发通知) -已确认:同一流程因退回或无法验收退出监控后,若再次进入「使用部门担当」且重新满足「未归档、有效、可以验收」,按**新周期从 0 计时**。上一周期已发过的档位不占用新周期,四档可以再各发一次。撤回、作废、归档后的同一请求不再恢复旧周期。 +已确认:退回或无法验收后再进入,「使用部门担当」的计时起点 `sbsyrjssj` 不会改写,签核天数仍按第一次写入的时间计算,不从 0 重计,也不另找起点。四档按这一段累计天数各发一次,不因再进入而重发。`sfzfth` 不考虑从退回(`0`)改回正常(`1` 或空);不靠这个变化恢复计时。撤回、作废、归档后的同一请求不再恢复。 ## 5. 升级与收件人 @@ -57,13 +58,13 @@ | 超过 30 天 | 当前节点处理人(担当) | 其直接主管、采购担当 | | 超过 37 天 | 当前节点处理人的经副理 | COO、采购经副理 | | 超过 44 天 | COO | 采购经副理 | -| 超过 51 天 | 廖总对应岗位 | COO、采购经副理 | +| 超过 51 天 | 总经理 | COO、采购经副理 | 人员解析: - 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。 - 采购担当取该流程的**申请人**。 -- 采购经副理、COO、廖总是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。 +- 采购经副理、COO、总经理是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。 - 当前节点有多名处理人时,主送这些处理人;直接主管、经副理按各处理人展开后去重。 - 收件人解析失败(无上级、未绑定企业微信)时,该条保持失败可追查,不改发给别人。 @@ -75,22 +76,24 @@ 权威设计见 [technical.md](technical.md)。摘要如下: -- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,库为 `ecology10`。 +- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`。验收单在 `ecology10`,流程实例字典库为 `weaver_wfc`,节点定义字典库为 `weaver_wfp`。 - 验收单主表是 `ecology10.dbo.ft_gdzcysdv2`。验收单单号 `ysddh`,采购单号 `cgdh`。计时起点 `sbsyrjssj` 只在第一次进入「使用部门担当」时写入,之后不改。 - `sybmdd`(使用部门担当)、`sbglry`(设备管理人员)存人员 ID,关联 `eteams.dbo.employee.ID`,用工号 `JOB_NUM` 匹配 HXOPS 用户。 -- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。 -- 当前节点和当前处理人在另一张表,表名与字段后续补充。未归档、归档仍依赖该表。表未到之前不实现。 +- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。无法验收说明正文是 `ycsm`,只留痕,不单独触发停表。 +- `sfzfth`:**0 是退回,1 和空都是流程正常。** 空值不当成退回。作废不看这一列。 +- 未归档、归档、作废、撤销看 `wfc_requestbase.flowstatus`(`1` 审批中,`3` 正常归档,`5` 已作废)。`7`、`8`、`99`、`-99` 都按撤销处理,停表且不再提醒。当前节点看 `weaver_wfc.dbo.wfc_currentnode.nodeid`,名称关联 `weaver_wfp.dbo.wfp_node`。`lastnodeid` 是最后操作节点,不当作当前节点。申请人 `sqr` 已确认是人员 ID。 +- 当前处理人在 `weaver_wfc.dbo.wfc_operate`。`userid` 是操作人,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一人只留一行。每日扫描按这些人展开四档收件人。 -直接主管、经副理按当前处理人查上级,不从主表取。采购经副理、COO、廖总不从单据取,只读界面配置。 +直接主管取当前处理人的 `employee.SUPERIOR`。经副理用该人的 `employee.DEPARTMENT` 查 `eteams.dbo.hrm_matrix_condition_data`,人在 `eteams.dbo.hrm_matrix_value_data.relate_id`。不查 E8 矩阵。采购经副理、COO、总经理不从矩阵取,只读界面配置。 ## 8. 验收标准(视图到位后的实现对照) | 编号 | 条件 | 期望 | | --- | --- | --- | | AC-01 | 尚未进入「使用部门担当」 | 不计时、不产生预警 | -| AC-02 | 进入该节点后第 30/37/44/51 个自然日 | 各档只产生一次待发送,收件人符合第 5 节 | +| AC-02 | 签核天数超过 30/37/44/51 | 各档只产生一次待发送,刚好等于还不发。收件人符合第 5 节 | | AC-03 | 进入后更换后续节点 | 累计天数不重置 | | AC-04 | 归档、退回、撤回、作废或无法验收 | 立即停表,取消未发送预警,已发送消息保留 | -| AC-05 | 退回或无法验收后再次进入「使用部门担当」且重新可以验收 | 新周期从 0 计时,四档可再各发一次 | +| AC-05 | 退回或无法验收后再次进入 | 签核天数仍从原 `sbsyrjssj` 计算。不把 `sfzfth` 从 `0` 改回正常当作恢复 | | AC-06 | 发送时刻 | 默认每周五 18:00 按收件人汇总;时刻可配置 | -| AC-07 | 修改采购经副理、COO、廖总配置 | 此后新产生的预警使用新人员,不改历史已发送记录 | +| AC-07 | 修改采购经副理、COO、总经理配置 | 此后新产生的预警使用新人员,不改历史已发送记录 | diff --git a/docs/features/equipment-acceptance-warning/equipment-acceptance-warning-prototype.html b/docs/features/equipment-acceptance-warning/equipment-acceptance-warning-prototype.html index 07d43cb3..3c91d8ce 100644 --- a/docs/features/equipment-acceptance-warning/equipment-acceptance-warning-prototype.html +++ b/docs/features/equipment-acceptance-warning/equipment-acceptance-warning-prototype.html @@ -178,7 +178,7 @@ - +
@@ -186,7 +186,7 @@
- +
已发送记录保持不变
@@ -223,9 +223,9 @@ { id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点两名处理人,直接主管相同,抄送去重为钱伟。' }, { id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析直接主管,保持失败,不改发。' }, { id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' }, - { id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-26', days:4, cycle:2, state:'watching', sent:[], fail:'', stop:'', note:'上一周期因无法验收停表。再次进入后从 0 计时,四档可再发。' }, + { id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' }, { id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' }, - { id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。若再次进入使用部门担当,按新周期从 0 计。' }, + { id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' }, { id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' } ]; diff --git a/docs/features/equipment-acceptance-warning/technical.md b/docs/features/equipment-acceptance-warning/technical.md index 68453925..bbda39fe 100644 --- a/docs/features/equipment-acceptance-warning/technical.md +++ b/docs/features/equipment-acceptance-warning/technical.md @@ -1,13 +1,13 @@ # 设备验收预警设计 -> **版本**:V1.0 -> **更新日期**:2026-10-07 -> **状态**:主数据表已明确;当前节点表未提供。节点表到位前不写同步、计时和推送。 +> **版本**:V1.19 +> **更新日期**:2026-10-12 +> **状态**:只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同:内置 Agent `equipment_acceptance`。当前处理人取当前节点上的 `wfc_operate.userid`,不查询、不保存 `isremark`。发送时刻不在配置表,默认排程是每天 06:00 扫描、每周五 18:00 发送,可在排程页改 Cron。 > **业务规则**:[demand.md](demand.md)。本文只说明数据从哪读、人员怎么对上、哪些事实还缺。 ## 1. 结论 -验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程现在停在哪个节点、当前处理人是谁,来自另一张表,表名和字段以后补充。那张表没到之前,不能判断未归档、当前节点和当前处理人,因此仍不实现扫描和推送。 +验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程是否归档、作废、撤销,读 `wfc_requestbase.flowstatus`。当前节点读 `wfc_currentnode.nodeid`,再关联 `wfp_node.nodename`。`lastnodeid` 是最后操作节点,不拿来当当前节点。当前处理人读 `wfc_operate.userid`,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一节点同一人只留一行。每日扫描按这些处理人展开四档收件人。 ## 2. 连接 @@ -19,7 +19,7 @@ | `OA_E10_SQLSERVER_USERNAME` | 只读账号 | | `OA_E10_SQLSERVER_PASSWORD` | 只读密码 | -库名固定为 `ecology10`。人员表在同一实例的 `eteams` 库。本功能要求上述三个变量已配置,不回退到 E9 的 `OA_SQLSERVER_*`。 +验收单在 `ecology10`,人员表在同一实例的 `eteams`。流程字典写明:`wfc_requestbase`、`wfc_currentnode`、`wfc_operate` 所属库 `weaver_wfc`,`wfp_node` 所属库 `weaver_wfp`。现场曾在 `ecology10` 的 `INFORMATION_SCHEMA` 查出 `wfc_requestbase` 的列,查询时先按字典库名,账号看不到 `weaver_wfc` / `weaver_wfp` 时再改用 `ecology10` 里的同名表。本功能要求上述三个变量已配置,不回退到 E8 的 `OA_SQLSERVER_*`。 ## 3. 验收单主表 @@ -27,36 +27,36 @@ | 字段 | 含义 | 在预警里的用法 | | ------------- | -------------------- | -------------------------------------------------------------------------------------------- | -| `lcbh` | 流程编号 | 流程标识。和后续节点表关联时优先用它。 | | `ysddh` | 验收单单号 | 台账、详情、企业微信上的验收单单号。 | | `cgdh` | 采购单号 | 台账上的采购单号。 | -| `htbh` | 合同编号 | 合同编号。与 `htbh1` 的分工未说明,两列都保留,不合并。 | -| `htbh1` | 合同编号 | 同上。 | -| `ysrq` | 验收日期 | 单据上的验收日期,不是计时起点。 | +| `htbh` | 合同编号 | 只保存这一列。表上没有第二合同编号。 | | `sbsyrjssj` | 设备使用人员计时时间 | 计时起点。第一次进入「使用部门担当」时写入,之后不改。为空表示还没开始计时。 | | `sybmdd` | 使用部门担当 | 人员 ID,关联 `eteams.dbo.employee.ID`。 | | `sbglry` | 设备管理人员 | 人员 ID,关联方式同 `sybmdd`。 | -| `sqr` | 申请人 | 预警规则里的采购担当。样例中是与 `sybmdd` 相同形态的长整型,按 `employee.ID` 关联。 | +| `sqr` | 申请人 | 预警规则里的采购担当。已确认是人员 ID,关联 `eteams.dbo.employee.ID`。 | | `syry` | 使用人员 | 样例中同样是长整型 ID,按 `employee.ID` 关联。 | | `gzglry` | 固资管理人员 | 人员字段。样例多为空;非空时按同一 ID 关联。 | | `dx` | 使用人员1 | 同上。 | | `agent` | 资管经办人 | 同上。 | -| `sfzfth` | 是否作废退回 | 作废或退回时停表。样例里见过空值和 `0`,枚举含义未给出,实现前要确认哪个值表示作废或退回。 | -| `sfkyzcys` | 是否可以正常验收 | **0 表示可以,1 表示不可以。** 与常见的 0=否、1=是相反。空值不当成可以验收。 | +| `sfzfth` | 是否作废退回 | OA 上 **0 是退回,1 和空都是流程正常。** 落库 `is_returned` 翻转成 0 否、1 是,空收成 0。作废不看这一列,作废看 `flowstatus = 5`。 | +| `sfkyzcys` | 是否可以正常验收 | OA 上 **0 表示可以,1 表示不可以。** 落库 `can_accept` 翻转成 0 否、1 是。空值保持空,不当成可以验收。 | +| `ycsm` | 无法验收说明 | 说明正文。落库 `cannot_accept_note`。只留痕,不单独触发停表。停表仍看 `sfkyzcys = 1`。 | -`sfkyzcys` 只表达能不能正常验收,不是无法验收说明正文。说明原文仍未出现在已给字段里。 +`sfkyzcys` 只表达能不能正常验收。说明正文是 `ycsm`。 -已确认按 ID 关联人员的是 `sybmdd`、`sbglry`。`sqr`、`syry` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。 +已确认按 ID 关联人员的是 `sybmdd`、`sbglry`、`sqr`。`syry`、`gzglry`、`dx`、`agent` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。 ## 4. 人员怎么对上系统用户 -`eteams.dbo.employee` 至少使用这三列: +`eteams.dbo.employee` 使用这些列: | 字段 | 含义 | | ------------ | ----------------------------------------------------- | -| `ID` | 与验收单人员字段关联 | -| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 | -| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 | +| `ID` | 与验收单人员字段、操作人 `userid` 关联 | +| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 | +| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 | +| `DEPARTMENT` | 部门 ID。只用来查经副理 | +| `SUPERIOR` | 直接主管的人员 ID。再关联本表 `ID` | 关联顺序: @@ -67,33 +67,172 @@ 对不上时该条保持失败,可追查,不改发给别人。失败包括:人员 ID 为空、`employee` 无此 ID、`JOB_NUM` 为空、工号在 HXOPS 无用户、用户未绑定企业微信。 -直接主管、经副理不在这两张表里。仍按需求:取当前节点处理人的上级。上级来源等节点表补充后再定,不从 `ft_gdzcysdv2` 臆造。 +直接主管取当前处理人在 `employee.SUPERIOR` 上的人员 ID,不查矩阵。经副理才查 E10 矩阵,见第 4.1 节。不从 `ft_gdzcysdv2` 臆造,也不查 E8 的 `Matrixtable_3`。 -采购经副理、COO、廖总只读界面配置,不从这两张表取。 +采购经副理、COO、总经理只读界面配置,不从矩阵表取。 + +## 4.1 直接主管与经副理 + +按当前处理人查,不按申请人查,也不查 E8。 + +1. 当前处理人是 `wfc_operate.userid`,等于 `eteams.dbo.employee.ID`。 +2. 直接主管是该员工的 `SUPERIOR`。这是人员 ID,再关联 `employee.ID` 取姓名和工号。空或关联不上就记失败,不改发给别人。 +3. 经副理用该员工的 `DEPARTMENT`(部门 ID)查 E10 部门矩阵。人员在 `hrm_matrix_value_data.relate_id`,再同样关联 `employee`。不要把这个 ID 当成企微 userid,也不要对 `HrmResource.id`。 + +多名当前处理人时,各自取 `SUPERIOR` 和经副理,然后去重。 + +三个固定值已确认。`tenant_key` 为 `temkc46eme`。矩阵 `id` `1115770797884751874` 是苏州和信的「HXJM-审批矩阵」,取自 `eteams.dbo.hrm_matrix.id`。经副理取值配置 `id` `1115771897387991041` 取自 `eteams.dbo.hrm_matrix_value_config`:`config_name` 为「经副理」,且 `matrix_id` 为上面这个矩阵。该配置 `config_type` 是 `resource`,`single_type = 1`(单选)。查人仍用 `hrm_matrix_value_data.relate_id`,不要把配置表的 `id` 当成人员 ID。`delete_type = 0` 为正常。同一矩阵下还有总经理等其他取值配置,不拿来当经副理。 + +矩阵 id 和经副理配置 id 按下面两条查出,不在代码里另找别的矩阵: + +```sql +-- 苏州和信「HXJM-审批矩阵」的 id。 +SELECT id +FROM eteams.dbo.hrm_matrix +WHERE tenant_key = 'temkc46eme' + AND matrix_name = N'HXJM-审批矩阵' + AND delete_type = 0 + AND enable_status = 1; +-- 结果:1115770797884751874 + +-- 该矩阵下 config_name 为「经副理」的取值配置 id。 +SELECT id +FROM eteams.dbo.hrm_matrix_value_config +WHERE tenant_key = 'temkc46eme' + AND matrix_id = 1115770797884751874 + AND config_name = N'经副理' + AND delete_type = 0; +-- 结果:1115771897387991041 +``` + +已用 `employee.DEPARTMENT = 1115763045510725632` 核对:`hrm_matrix_value_data.matrix_data_id` 没有这个值。因此这张矩阵不能把 `matrix_data_id` 直接当成部门 ID。部门 ID 改到条件表 `hrm_matrix_condition_data.relate_id` 里按字符串匹配,先取出矩阵数据行,再取值: + +```sql +-- 经副理。表都在 eteams.dbo,不能省库名。 +-- 返回的 relate_id 是人员 ID,再关联 eteams.dbo.employee.ID,不要当成企微 userid。 +-- :department_id 取当前处理人的 employee.DEPARTMENT,必须按字符串比较。 +-- 已用部门 1115763045510725632 跑通,返回一名经副理。 +SELECT v.relate_id +FROM eteams.dbo.hrm_matrix_value_data AS v +WHERE v.tenant_key = 'temkc46eme' -- 租户 + AND v.matrix_id = 1115770797884751874 -- hrm_matrix:苏州和信「HXJM-审批矩阵」的 id + AND v.matrix_value_config_id = 1115771897387991041 -- hrm_matrix_value_config:该矩阵下 config_name 为「经副理」的 id,不是人员 ID + AND v.delete_type = 0 -- 0 正常,1/2/3 都是删除 + AND v.matrix_data_id IN ( + -- 部门 ID 不在 matrix_data_id 上。先从条件表找出矩阵数据行。 + SELECT c.matrix_data_id + FROM eteams.dbo.hrm_matrix_condition_data AS c + WHERE c.tenant_key = 'temkc46eme' + AND c.matrix_id = 1115770797884751874 + AND c.delete_type = 0 + AND c.relate_id = :department_id -- 字符串,例如 '1115763045510725632' + ) +``` + +条件配置 id 还没限定。若同一部门对出多行,再按 `matrix_condition_config_id` 收窄。 ## 5. 计时与停表在现有字段上怎么落 计时起点用 `sbsyrjssj`。已确认它只在第一次进入「使用部门担当」时写入一次,之后不改写。从该时间起到当前按自然日累计,换节点不重置。字段为空的单据视为尚未开始计时,不产生预警。 -`sfzfth` 表示作废或退回,命中后停表并取消未发送预警。具体取值等枚举确认。 +退回只看 `sfzfth`。OA 取值是 0=是、1=否。落库列 `is_returned` 先翻转成标准布尔:0 否,1 是。已确认取值: -是否可以正常验收看 `sfkyzcys`,取值与常见布尔相反: +| OA `sfzfth` | 本地 `is_returned` | 含义 | 预警 | +| --- | --- | --- | --- | +| `0` | `1` | 是,退回 | 立即停表,取消尚未发出的预警。不考虑从 `0` 改回 `1` 或空。 | +| `1` | `0` | 否,流程正常 | 不因本字段停表 | +| 空 | `0` | 否,流程正常 | 与 OA `1` 相同,不当成退回 | -| 值 | 含义 | 预警 | +字段中文名是「是否作废退回」,已确认的取值只区分退回和正常。作废、撤销仍看下一节的 `flowstatus`,不用 `sfzfth` 代替。出现 `0`、`1`、空以外的值时,不判退回,也不当正常,先记下来待确认。 + +不考虑 `sfzfth` 从 `0` 改回 `1` 或空。不把这种改写当作恢复计时或新周期。 + +是否可以正常验收看 `sfkyzcys`。OA 取值与常见布尔相反:0=是、1=否。落库列 `can_accept` 翻转成 0 否、1 是。空值不翻转成否。 + +| OA `sfkyzcys` | 本地 `can_accept` | 含义 | 预警 | +| --- | --- | --- | --- | +| `0` | `1` | 是,可以正常验收 | 其他条件也满足时继续计时 | +| `1` | `0` | 否,不可以正常验收 | 立即停表,取消尚未发出的预警 | +| 空 | 空 | 未标明 | 不纳入监控,不按「可以验收」处理 | + +退回或无法验收后再进入,`sbsyrjssj` 仍是第一次写入的时间,签核天数就按它计算,不从 0 重计。不读取、不保存 `wfc_operate.operateround`。 + +## 5.1 流程实例与节点定义 + +OA 数据字典: + +| 表 | 中文名 | 字典所属库 | 用途 | +| --- | --- | --- | --- | +| `wfc_requestbase` | 流程实例基本信息表 | `weaver_wfc` | 一条流程一行。状态、编号、最后操作节点。 | +| `wfc_currentnode` | 流程当前节点表 | `weaver_wfc` | 流程当前停在哪个节点。没有处理人。 | +| `wfp_node` | 工作流节点基础信息表 | `weaver_wfp` | 节点定义。用 `id` 取出节点名称和节点类型。 | + +`wfc_currentnode` 字段: + +| 字段 | 字典含义 | 用法 | | --- | --- | --- | -| `0` | 可以正常验收 | 其他条件也满足时继续计时 | -| `1` | 不可以正常验收 | 立即停表,取消尚未发出的预警 | -| 空 | 未标明 | 不纳入监控,不按「可以验收」处理 | +| `requestid` | 流程实例 id。来源说明写着 `wfc_operate` | 等于 `wfc_requestbase.requestid` | +| `nodeid` | 数据所在节点 ID。来源说明写着 `wfc_operate` | 等于 `wfp_node.id`,这是当前节点 | +| `nodetype` | 节点类型 | 本表字典没有 0–9。类型以 `wfp_node.nodetype` 为准 | +| `delete_type` | 是否删除 | 只取 `0` | +| `operate_log_id` | 批次号 | 不查询、不保存 | +| `creator` | 数据插入人 | 不是当前处理人 | -下面几件事这张主表给不了,都等节点表: +关联: -- 当前节点名称 -- 当前节点处理人(担当、直接主管、经副理都从这里取,不固定成 `sybmdd`) -- 是否未归档、是否已归档 -- 无法验收说明正文 -- 撤回与归档的发生时间 +1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`,且 `wfc_form_data.delete_type = 0`。验收单上没有流程编号列,不读 `requestmark`。 +2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`。本地快照按这个 `requestid` 唯一。归档看 `flowstatus = 3`,不看验收日期。 +3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`,且 `wfc_currentnode.delete_type = 0`。 +4. `wfc_currentnode.nodeid` = `wfp_node.id`。展示名称用 `wfp_node.nodename`。 +5. 分流时一条流程可以有多行当前节点。这些行都保留,节点名称分别列出。计时仍按整单累计,不按节点重置。 -退回或无法验收后再次进入,仍按需求从 0 重计一个新周期。`sbsyrjssj` 不会被改写,所以新周期不能靠这个字段变空或变新时间来识别,需要节点表上的再次进入标记。 +`wfc_requestbase.lastnodeid` 仍是「最后操作节点 ID」,只表示刚办过的节点。当前节点以 `wfc_currentnode.nodeid` 为准。 + +`wfp_node.nodetype`:0 发起,1 审批,2 确认,3 结束,4 子流程节点,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅。`nodeattr`:0 一般节点,1 分流点,2 分流中间点,3 合流点。`wfc_requestbase.lastnodetype` 只标了「最后操作流程节点类型」,字典没有给出 0–9。不把 `nodetype` 的枚举直接套到 `lastnodetype`。 + +流程状态以 `flowstatus` 为准。同表的 `status` 是最长 1000 的文本,没有枚举,不拿来判断停表。 + +| `flowstatus` | 字典含义 | 预警 | +| --- | --- | --- | +| `0` | 草稿 | 不监控 | +| `1` | 审批中 | 其他条件也满足时可以计时 | +| `3` | 正常归档 | 停表,不恢复旧周期 | +| `4` | 强制结束 | 流程已结束。业务未单列这一项,先按停表、不恢复处理 | +| `5` | 已作废 | 停表,不恢复旧周期 | +| `6` | 待提交 | 不按审批中处理 | +| `7` | 暂停 | 已确认与撤销相同:停表,不再提醒,不恢复旧周期 | +| `8` | 撤销 | 停表,不再提醒,不恢复旧周期 | +| `99`、`-99` | `99` 为业务确认值;`-99` 是字典截断处 | 与撤销相同:停表,不再提醒 | + +字典没有值为「退回」的流程状态。退回后 `flowstatus` 仍可能是 `1`(审批中)。退回以验收单 `sfzfth = 0` 为准,不从 `flowstatus` 推断。 + +`finishdatetime` 是流程归档时间。字典另有拼写 `finshdatetime`(少一个 i),含义写成「流程归档时间、作废时间」。现场列清单里是 `finishdatetime`。查询只用 `finishdatetime`,不查 `finshdatetime`。 + +`lastoperator` 是最后操作人,`wfc_currentnode.creator` 是插行的人,都不是当前待办人。`delete_type` 是记录是否删除,不是作废。作废看 `flowstatus = 5`。 + +## 5.2 流程操作人 + +表:`weaver_wfc.dbo.wfc_operate`,中文名「流程操作人表」。当前处理人在这张表。 + +| 字段 | 字典含义 | 用法 | +| --- | --- | --- | +| `requestid` | 流程实例 id | 等于 `wfc_currentnode.requestid` | +| `nodeid` | 数据所在节点 ID | 等于 `wfc_currentnode.nodeid`。只取当前节点上的操作人 | +| `userid` | 操作人 id | 当前处理人。关联 `eteams.dbo.employee.ID` | +| `processuser` | 实际操作人 ID | 已经代办或实际点过的人。待办人取 `userid`,不取这一列 | +| `usertype` | 人员类型 | 字典没有取值。先按 `userid` 关联员工,关联不上记失败 | +| `isremark` | 操作状态 | 不查询、不保存。当前处理人就是当前节点上的 `userid` | +| `preisremark` | 插入时的操作状态,插入后不变更 | 不查询、不保存 | +| `operatedatetime` | 操作日期时间 | 已办才会有操作时间。不能单靠它为空就把抄送、转发都算成待办 | +| `showorder` | 未操作者的显示顺序 | 说明表里包含未操作的人 | +| `operateround` | 节点第几次到达 | 不查询、不保存 | +| `isbereject` | 是否退回操作 | 字典没有 0/1。退回仍以 `sfzfth = 0` 为准 | +| `isprocessing` | 执行中时,流程不出现在待办、已办 | 字典没有哪个值表示执行中。该状态的行不发预警 | +| `delete_type` | 是否删除 | 只取 `0` | +| `optgroupid` | 操作者批次 | 不查询、不保存 | +| `batch_number` | 批次号 | 不查询、不保存。与 `wfc_currentnode.operate_log_id` 一样不参与预警 | + +当前节点上的 `userid` 都是当前处理人。同一人只留一行。直接主管、经副理按各人展开后去重。会签关系 `signorder` 的取值未给,不改变「这些人都要通知」。 ## 6. 查询形态 @@ -101,13 +240,13 @@ ```sql SELECT - f.lcbh, f.ysddh, f.cgdh, - f.ysrq, + f.htbh, f.sbsyrjssj, f.sfzfth, f.sfkyzcys, + f.ycsm, f.sybmdd, owner.USERNAME AS owner_name, owner.JOB_NUM AS owner_job_num, @@ -116,14 +255,40 @@ SELECT equip.JOB_NUM AS equip_job_num, f.sqr, applicant.USERNAME AS applicant_name, - applicant.JOB_NUM AS applicant_job_num + applicant.JOB_NUM AS applicant_job_num, + r.requestid, + r.flowstatus, + r.finishdatetime, + c.nodeid, + n.nodename, + n.nodetype, + op.userid, + handler.USERNAME AS handler_name, + handler.JOB_NUM AS handler_job_num FROM ecology10.dbo.ft_gdzcysdv2 AS f LEFT JOIN eteams.dbo.employee AS owner ON owner.ID = f.sybmdd LEFT JOIN eteams.dbo.employee AS equip ON equip.ID = f.sbglry -LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr; +LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr +LEFT JOIN weaver_wfc.dbo.wfc_form_data AS d + ON d.dataid = f.FORM_DATA_ID + AND d.delete_type = 0 +LEFT JOIN weaver_wfc.dbo.wfc_requestbase AS r + ON r.requestid = d.requestid + AND r.delete_type = 0 +LEFT JOIN weaver_wfc.dbo.wfc_currentnode AS c + ON c.requestid = r.requestid + AND c.delete_type = 0 +LEFT JOIN weaver_wfp.dbo.wfp_node AS n + ON n.id = c.nodeid + AND n.delete_type = 0 +LEFT JOIN weaver_wfc.dbo.wfc_operate AS op + ON op.requestid = c.requestid + AND op.nodeid = c.nodeid + AND op.delete_type = 0 +LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid; ``` -`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。当前节点表补充后,用 `lcbh` 与主表拼接,不在应用里先全量拉人再在内存里对 ID。 +验收单上没有流程编号、第二合同编号和验收日期,这三列不查询、也不写入本地表。归档只看 `flowstatus = 3`。不查询 `isremark`。当前节点上的 `userid` 就是当前处理人,同一人只留一行。一条流程有多个当前节点、每个节点有多名操作人时,这个查询会返回多行。库名按第 2 节:看不到 `weaver_wfc` / `weaver_wfp` 时改为 `ecology10`。`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。不在应用里先全量拉人再在内存里对 ID。 ## 7. 和需求规则的对照 @@ -131,17 +296,143 @@ LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr; | ---------------------- | -------------------------- | --------------------------- | | 验收单单号 | `ysddh` | 无 | | 采购单号 | `cgdh` | 无 | -| 流程编号 | `lcbh` | 无 | -| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 无。再次进入的新周期另要标记。 | +| 一张流程的身份 | `wfc_requestbase.requestid` | 不保存流程编号。验收日期不参与归档。 | +| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 再进入也用这个时间,不从 0 重计。 | | 使用部门担当 | `sybmdd` → `employee` | 无 | -| 申请人(采购担当) | `sqr` → `employee` | 关联方式按样例采用,待核对 | -| 作废、退回 | `sfzfth` | 枚举未给 | -| 当前节点、当前处理人 | 另一张表 | 表名和字段未给 | -| 未归档、归档 | 另一张表 | 同上 | -| 可以正常验收 | `sfkyzcys`:`0` 可以,`1` 不可以 | 空值不监控。说明正文仍缺。 | -| 直接主管、经副理 | 当前处理人的上级 | 节点表到位后再定来源 | -| 固定岗位三人 | 界面配置 | 不读 OA | +| 申请人(采购担当) | `sqr` → `employee` | 已确认是人员 ID | +| 作废 | `flowstatus = 5` | 不看 `sfzfth` | +| 撤销 | `flowstatus` 为 `7`、`8`、`99`、`-99` | 都停表且不再提醒。本地状态 `stopped_revoked` | +| 退回 | OA `sfzfth = 0`,本地 `is_returned = 1` | `1` 和空都是未退回,本地写成 `0`。 | +| 归档、未归档 | `flowstatus`:`3` 正常归档,`1` 审批中 | `4` 强制结束先按结束。 | +| 当前节点名称 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | 分流时可能多行,都保留。`lastnodeid` 不是当前节点 | +| 当前处理人 | `wfc_operate.userid`,对齐当前 `requestid` + `nodeid` | 不使用 `isremark`。同一人只留一行 | +| 可以正常验收 | OA `sfkyzcys`:`0` 可以,`1` 不可以。本地 `can_accept` 为 `1` 可以、`0` 不可以 | 空值不监控,也不写成 0。说明正文是 `ycsm`。 | +| 直接主管 | 当前处理人的 `employee.SUPERIOR` | 人员 ID,再关联 `employee` | +| 经副理 | `eteams.dbo.hrm_matrix_value_data.relate_id`。部门 ID 在 `eteams.dbo.hrm_matrix_condition_data.relate_id` | 查询已用部门 `1115763045510725632` 跑通。`matrix_data_id` 不是部门 ID | +| 再次进入 | 仍用第一次的 `sbsyrjssj` | 不从 0 重计。不看 `sfzfth` 是否从 `0` 改回正常。不用 `operateround`。 | +| 固定岗位三人 | 界面配置 | 不读 OA | -## 8. 仍不实现的部分 +## 8. 已实现的同步 -节点表、`sfzfth` 枚举、无法验收说明正文未齐之前,不写同步、计时引擎、企业微信发送、配置落库和数据表。原型继续用样例数据,不接这张表。实现 `sfkyzcys` 时禁止按「1 为是」处理。 +平台管理员调用 `POST /api/equipment-acceptance/sync`。连接只用 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,不回退 E8 的 `OA_SQLSERVER_*`。库名先按字典;实例里没有 `weaver_wfc` 或 `weaver_wfp` 时,流程表和节点表改用 `ecology10`。人员库只认 `eteams`。 + +本地表保存 OA 同步快照,另有一张发送记录表。一张验收单在 `equipment_acceptance_orders` 里一行,当前节点和操作人在另外两张表。每次同步按 `request_id` 更新主表,并整批替换该单的节点和操作人。主表删除时,节点和操作人随外键级联删除,发送记录只把 `order_id` 置空并保留单号快照。不保存流程编号、第二合同编号和验收日期。归档看 `flow_status_raw = 3`,不看验收日期。每日扫描写入发送记录;停表时取消还没发出的行。 + +### 8.1 `equipment_acceptance_orders` + +一张验收单的最近一次同步结果。`request_id` 唯一。 + +| 字段 | 含义 | +| --- | --- | +| `id` | 本地主键 | +| `request_id` | OA 流程实例 ID,来自 `wfc_requestbase.requestid`。一张流程一行 | +| `acceptance_no` | 验收单单号,来自 `ysddh` | +| `purchase_order_no` | 采购单号,来自 `cgdh` | +| `contract_no` | 合同编号,来自 `htbh` | +| `timer_started_at` | 计时起点,来自 `sbsyrjssj`。空表示还没开始计时 | +| `dwell_days` | 签核天数。归档、强制结束、作废且有 `finished_at` 时停在结束日,否则算到同步日 | +| `can_accept` | 是否可以正常验收。**0 否,1 是,空表示未标明。** 由 OA `sfkyzcys` 翻转而来,OA 是 0 是、1 否。空不写成 0 | +| `cannot_accept_note` | 无法验收说明正文,来自 `ycsm`。空表示没有说明。不参与停表判断 | +| `is_returned` | 是否退回。**0 否,1 是。** 由 OA `sfzfth` 翻转而来,OA 是 0 是、1 否。OA 的 1 和空都收成 0 | +| `flow_status_raw` | `wfc_requestbase.flowstatus` 原值。1 审批中,3 正常归档,4 强制结束,5 已作废 | +| `finished_at` | 流程结束时间,来自 `finishdatetime`。不拿它判断是否归档 | +| `request_match_count` | 这一行对应的流程实例数,现在固定为 1 | +| `owner_oa_id` / `owner_name` / `owner_job_num` | 使用部门担当。人员 ID 来自 `sybmdd`,姓名和工号来自 `employee` | +| `equip_oa_id` / `equip_name` / `equip_job_num` | 设备管理人员,来自 `sbglry` | +| `applicant_oa_id` / `applicant_name` / `applicant_job_num` | 申请人(采购担当),来自 `sqr` | +| `monitor_status` | 监控状态,取值见下表 | +| `present_in_source` | 这次同步是否还能在 OA 里看到这张单。看不到时保留上次内容,只把本列改成否 | +| `synced_at` | 最近一次同步时间 | +| `created_at` / `updated_at` | 本地创建、更新时间 | + +`monitor_status`: + +| 值 | 含义 | +| --- | --- | +| `watching` | 进行中。审批中、可以验收、未退回、已有计时起点 | +| `not_started` | 未开始。没有计时起点,且没有更优先的停表原因 | +| `stopped_returned` | 已退回。`is_returned = 1` | +| `stopped_cannot_accept` | 无法验收。`can_accept = 0` | +| `stopped_archived` | 已归档。`flow_status_raw = 3`,之后不再追踪预警 | +| `stopped_force_finished` | 已强制结束。`flow_status_raw = 4` | +| `stopped_voided` | 已作废。`flow_status_raw = 5` | +| `stopped_revoked` | 已撤销,不再提醒。`flow_status_raw` 为 `7`、`8`、`99` 或 `-99` | +| `excluded` | 不在监控范围。不含上面的撤销取值 | + +退回、无法验收先于作废、归档、强制结束和撤销。撤销即使没有计时起点也记为 `stopped_revoked`,不记成未开始。归档、强制结束、作废、撤销且有 `finished_at` 时,签核天数截止到该日。`optgroupid`、`batch_number`、`operate_log_id` 不查询、不保存。 + +### 8.2 `equipment_acceptance_nodes` + +这张单当前停在哪些节点。同一张单可以有多行,分流时每个当前节点一行。同一张单里 `order_id` + `node_id` 不重复。 + +| 字段 | 含义 | +| --- | --- | +| `id` | 本地主键 | +| `order_id` | 对应 `equipment_acceptance_orders.id` | +| `node_id` | OA 当前节点 ID,来自 `wfc_currentnode.nodeid` | +| `node_name` | 节点名称,来自 `wfp_node.nodename` | +| `node_type` | 节点类型原值,来自 `wfp_node.nodetype`。0 发起,1 审批,2 确认,3 结束,4 子流程,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅 | + +`lastnodeid` 不写入本表。 + +### 8.3 `equipment_acceptance_operators` + +当前节点上的操作人。同一节点同一人只留一行。不保存 `isremark`。 + +| 字段 | 含义 | +| --- | --- | +| `id` | 本地主键 | +| `order_id` | 对应 `equipment_acceptance_orders.id` | +| `node_id` | 这个人所属的当前节点 | +| `user_id` | OA 操作人 ID,来自 `wfc_operate.userid` | +| `handler_name` | 操作人姓名 | +| `handler_job_num` | 操作人工号 | + +扫描按这张表的当前处理人展开直接主管和经副理。直接主管、经副理不在本表,查询时再读 E10。 + +`GET /api/equipment-acceptance/orders` 分页列表。`focus` 取 `watching`、`overdue`、`stopped`、`not_started`;`overdue` 是计时中且签核天数超过配置里的第 1 档,默认 30。响应里的 `summary` 始终统计全部单据。`GET /api/equipment-acceptance/orders/` 含当前节点操作人。人员主键以字符串返回。平台管理员,或被授予启用中 Agent 的用户,可以打开列表和详情。同步仍只给平台管理员。停留列表四张汇总卡是进行中、已逾期、不再提醒、未开始。计时中且超过 30 天显示已逾期,未超过显示未超时。停留列表不显示第几档。 + +### 8.4 `equipment_acceptance_send_records` + +一张验收单某一档的发送记录。同一张单同一档只有一行。待发送和解析失败的行每次扫描按当前处理人和当前岗位重算;已发送、已取消的姓名不再改写。Chat 页签「发送记录」读 `GET /api/equipment-acceptance/sends`。 + +| 字段 | 含义 | +| --- | --- | +| `id` | 本地主键 | +| `order_id` | 对应 `equipment_acceptance_orders.id`。验收单被删时置空 | +| `acceptance_no` / `purchase_order_no` | 写入时的验收单单号、采购单号 | +| `tier` | 第几档,1 到 4 | +| `threshold_days` | 这一档当时的天数,例如 30 | +| `to_text` / `cc_text` | 解析成功的主送、抄送姓名,用顿号拼接 | +| `recipients_json` | 每个席位的角色、姓名、系统用户、企微 userid、OA 人员 ID 和失败原因 | +| `status` | `pending` 待发送,`sent` 已发送,`failed` 解析或发送失败,`cancelled` 已取消 | +| `sent_at` | 发出时间。只有 `sent` 才有 | +| `error_message` | 解析失败或企业微信发送失败的原因。能发出的人仍会发送 | +| `created_at` | 记录生成时间 | + +页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。 + +`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。 + +## 9. 扫描与发送 + +每天 06:00(Asia/Shanghai)排程 `equipment-acceptance-alert-scan` 先同步 E10,再按签核天数生成待发送。超过配置天数才进档,刚好等于还不发。默认 30/37/44/51。同一张单每一档只生成一次;已发送和已取消不重算、不重发。 + +收件人: + +- 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。 +- 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。 +- 超过第 3 档:主送 COO,抄送采购经副理。 +- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。 + +人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。 + +每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号合并成一条文本卡片,标题「设备验收停留提醒」,事件 `equipment_acceptance_warning`。卡片过长时先留 12 行,其余写成「另有 N 条」。发送成功改为已发送。有人失败则整档改为失败,并附上「企业微信发送失败」;下次扫描会按当前处理人重算并回到待发送。已发出的企业微信不撤回。 + +停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。 + +管理员在发送记录页可以立即「扫描预警」和「发送预警」,对应 `POST /api/equipment-acceptance/alerts/scan` 和 `POST /api/equipment-acceptance/alerts/send`。两个排程启动时写入,已有同编号时不覆盖。Cron 在排程页改,不在预警配置页。 + +不查询、不保存 `isremark`。不接 Dify。不给「使用部门担当」之前的节点单独计时。读 OA `sfkyzcys`、`sfzfth` 时仍是 0 表示是、1 表示否,禁止把 OA 原值直接写进 `can_accept`、`is_returned`。`ycsm` 只保存说明,不拿它判断能不能验收。 + +数据库升到迁移 `ea8c0a1b2c3d` 后,快照、配置和带收件人明细的发送记录一次建好,扫描才能落库。 diff --git a/docs/funclist.md b/docs/funclist.md index 04324707..eda7ce57 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -45,8 +45,12 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | -| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。退回或无法验收后再次进入且重新可以验收时,按新周期从 0 计时。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 | -| 四档企业微信升级 | 待当前节点表 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、廖总为可配置固定岗位。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。主表已明确为 E10 `ft_gdzcysdv2`,当前节点表未提供,到位前不写同步、计时和推送。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | +| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 | +| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 | +| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 | +| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,采购经副理、COO、总经理选择系统用户。发送时刻不在此页,以后由排程 Cron 配置,默认每周五 18:00。 | +| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果和发送时间。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 | +| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人汇总一条企业微信。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | ## 知识库同步状态校验 diff --git a/frontend/src/features/chat/components/ChatViewContent.vue b/frontend/src/features/chat/components/ChatViewContent.vue index 9c16de35..09f29800 100644 --- a/frontend/src/features/chat/components/ChatViewContent.vue +++ b/frontend/src/features/chat/components/ChatViewContent.vue @@ -4,12 +4,12 @@ * 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。 - * 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。 + * 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、EquipmentAcceptanceChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。 * 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页; * 货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框;会话标题取自侧栏历史并传给中心; * 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰; - * 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框。 + * 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、设备验收预警、立账凭证 Agent 用作业面替换消息列表与输入框。 */ @@ -47,7 +47,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context'; import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils'; -import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils'; +import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isEquipmentAcceptanceAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils'; import { SHIPPING_WORKFLOW_KEY, @@ -79,6 +79,10 @@ const ContractPaymentChatPanel = defineRecoverableAsyncComponent( () => import('@/features/contract-payment/components/ContractPaymentChatPanel.vue'), ); +const EquipmentAcceptanceChatPanel = defineRecoverableAsyncComponent( + () => import('@/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue'), +); + const VoucherCheckChatPanel = defineRecoverableAsyncComponent( () => import('@/features/voucher-check/components/VoucherCheckChatPanel.vue'), ); @@ -130,11 +134,14 @@ const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAge /** 合同付款预警 Agent:主区嵌台账 Tab,隐藏对话输入与历史。 */ const isContractPaymentAgentPage = computed(() => isContractPaymentAgent(page.currentAgent)); +/** 设备验收预警 Agent:主区嵌停留列表,隐藏对话输入与历史。 */ +const isEquipmentAcceptanceAgentPage = computed(() => isEquipmentAcceptanceAgent(page.currentAgent)); + /** 立账凭证 Agent:主区嵌检核任务 / 企微发送记录 Tab,隐藏对话输入与历史。 */ const isVoucherCheckAgentPage = computed(() => isVoucherCheckAgent(page.currentAgent)); /** builtin 作业面 Agent 共用:隐藏新会话、历史列表与输入框。 */ -const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isVoucherCheckAgentPage.value); +const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isEquipmentAcceptanceAgentPage.value || isVoucherCheckAgentPage.value); /** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */ const transferFlowActive = ref(false); @@ -489,6 +496,8 @@ watch(() => page.currentAgentId, () => { + +
diff --git a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts new file mode 100644 index 00000000..41ad0442 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts @@ -0,0 +1,227 @@ +/** + * features/equipment-acceptance/api/equipment-acceptance.api.ts + * 用途:设备验收预警同步列表、详情和手动同步。 + * 依赖:统一 requestJson;后端 /api/equipment-acceptance。 + * 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。 + * 发送记录只读已落库的行,扫描尚未写入时列表为空。 + */ +import { requestJson } from '@/shared/api/client'; + +export interface EquipmentAcceptanceNode { + node_id?: string | null; + node_name?: string | null; + node_type?: number | null; +} + +export interface EquipmentAcceptanceOperator { + node_id?: string | null; + user_id?: string | null; + handler_name?: string | null; + handler_job_num?: string | null; +} + +export interface EquipmentAcceptanceOrder { + id: number; + acceptance_no?: string | null; + purchase_order_no?: string | null; + contract_no?: string | null; + timer_started_at?: string | null; + dwell_days?: number | null; + can_accept?: number | null; + cannot_accept_note?: string | null; + is_returned?: number | null; + flow_status_raw?: number | null; + finished_at?: string | null; + request_id?: string | null; + request_match_count: number; + owner_name?: string | null; + owner_job_num?: string | null; + applicant_name?: string | null; + applicant_job_num?: string | null; + monitor_status: string; + overdue?: boolean; + present_in_source: boolean; + synced_at?: string | null; + nodes: EquipmentAcceptanceNode[]; + operators: EquipmentAcceptanceOperator[]; +} + +export interface EquipmentAcceptanceSummary { + watching: number; + overdue: number; + stopped: number; + not_started: number; +} + +export interface EquipmentAcceptanceListResponse { + items: EquipmentAcceptanceOrder[]; + total: number; + page: number; + page_size: number; + pages: number; + summary?: EquipmentAcceptanceSummary; +} + +export interface EquipmentAcceptanceSyncResult { + upserted: number; + skipped_without_request_id: number; + absent: number; + by_status: Record; +} + +/** + * 分页查询已同步的验收单。 + * 核心逻辑:focus 对应原型分组。空或 all 不过滤。 + * @param params.focus - watching、overdue、stopped、not_started + * @param params.page - 页码,从 1 开始 + * @param params.pageSize - 每页条数 + * @returns 分页快照和全部单据汇总 + */ +export function listEquipmentAcceptanceOrders(params?: { + focus?: string; + page?: number; + pageSize?: number; +}) { + const query = new URLSearchParams(); + if (params?.focus && params.focus !== 'all') query.set('focus', params.focus); + if (params?.page) query.set('page', String(params.page)); + if (params?.pageSize) query.set('page_size', String(params.pageSize)); + const suffix = query.toString() ? `?${query.toString()}` : ''; + return requestJson(`/api/equipment-acceptance/orders${suffix}`); +} + +/** + * 读取一张验收单的节点和操作人。 + * @param orderId - 本地快照主键 + * @returns 快照详情 + */ +export function getEquipmentAcceptanceOrder(orderId: number) { + return requestJson(`/api/equipment-acceptance/orders/${orderId}`); +} + +/** + * 从 E10 拉取验收单并更新本地快照。仅平台管理员可调用。 + * @returns 本次写入、跳过和未见条数 + */ +export function syncEquipmentAcceptance() { + return requestJson('/api/equipment-acceptance/sync', { method: 'POST' }); +} + +export interface EquipmentAcceptanceScanResult { + created: number; + updated: number; + cancelled: number; +} + +export interface EquipmentAcceptanceSendResult { + sent: number; + failed: number; + records_sent: number; + records_failed: number; +} + +/** + * 管理员立即同步 E10 并生成待发送记录。 + * @returns 新增、更新和取消条数 + */ +export function scanEquipmentAcceptanceAlerts() { + return requestJson('/api/equipment-acceptance/alerts/scan', { method: 'POST' }); +} + +/** + * 管理员立即把待发送记录按收件人发到企业微信。 + * @returns 成功和失败的收件人数 + */ +export function sendEquipmentAcceptanceAlerts() { + return requestJson('/api/equipment-acceptance/alerts/send', { method: 'POST' }); +} + +export interface EquipmentAcceptanceSendRecord { + id: number; + order_id?: number | null; + acceptance_no?: string | null; + purchase_order_no?: string | null; + tier: number; + threshold_days: number; + to_text?: string | null; + cc_text?: string | null; + status: string; + sent_at?: string | null; + error_message?: string | null; + created_at?: string | null; +} + +export interface EquipmentAcceptanceSendListResponse { + items: EquipmentAcceptanceSendRecord[]; + total: number; + page: number; + page_size: number; +} + +/** + * 分页读取发送记录。 + * 核心逻辑:按创建时间倒序。还没有扫描写入时 items 为空。 + * @param params.page - 从 1 开始 + * @param params.pageSize - 每页条数 + * @returns 当前页记录和总数 + */ +export function listEquipmentAcceptanceSends(params?: { page?: number; pageSize?: number }) { + const search = new URLSearchParams(); + if (params?.page) search.set('page', String(params.page)); + if (params?.pageSize) search.set('page_size', String(params.pageSize)); + const suffix = search.toString() ? `?${search.toString()}` : ''; + return requestJson(`/api/equipment-acceptance/sends${suffix}`); +} + +export interface EquipmentAcceptanceConfigUser { + id: number; + username: string; + real_name?: string | null; + employee_id?: string | null; + department?: string | null; + wecom_bound?: boolean; +} + +export interface EquipmentAcceptanceConfig { + days: number[]; + buyer_manager_user_id?: number | null; + coo_user_id?: number | null; + executive_user_id?: number | null; + selected_users: EquipmentAcceptanceConfigUser[]; + users: EquipmentAcceptanceConfigUser[]; + updated_at?: string | null; +} + +/** + * 读取四档天数和三个固定岗位。管理员响应里带候选人。 + * @returns 当前配置 + */ +export function getEquipmentAcceptanceConfig() { + return requestJson('/api/equipment-acceptance/config'); +} + +/** + * 保存四档天数和三个岗位的系统用户。仅平台管理员。 + * 核心逻辑:岗位传用户主键或 null,不传姓名。 + * @param payload.days - 四个逐档增大的天数 + * @param payload.buyerManagerUserId - 采购经副理 + * @param payload.cooUserId - COO + * @param payload.executiveUserId - 廖总对应岗位 + * @returns 保存后的配置 + */ +export function saveEquipmentAcceptanceConfig(payload: { + days: number[]; + buyerManagerUserId: number | null; + cooUserId: number | null; + executiveUserId: number | null; +}) { + return requestJson('/api/equipment-acceptance/config', { + method: 'PUT', + body: JSON.stringify({ + days: payload.days, + buyer_manager_user_id: payload.buyerManagerUserId, + coo_user_id: payload.cooUserId, + executive_user_id: payload.executiveUserId, + }), + }); +} diff --git a/frontend/src/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue b/frontend/src/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue new file mode 100644 index 00000000..0d299a41 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/components/EquipmentAcceptanceChatPanel.vue @@ -0,0 +1,225 @@ + + + + diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue new file mode 100644 index 00000000..3dc5e222 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue @@ -0,0 +1,272 @@ + + + + diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceDetailPage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceDetailPage.vue new file mode 100644 index 00000000..86171269 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceDetailPage.vue @@ -0,0 +1,314 @@ + + + + diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptancePage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptancePage.vue new file mode 100644 index 00000000..8eb25a06 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptancePage.vue @@ -0,0 +1,264 @@ + + + + diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceSendsPage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceSendsPage.vue new file mode 100644 index 00000000..11cdeb51 --- /dev/null +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceSendsPage.vue @@ -0,0 +1,137 @@ + + + + diff --git a/frontend/src/locales/en/admin.json b/frontend/src/locales/en/admin.json index 08c9149f..1d99a35f 100644 --- a/frontend/src/locales/en/admin.json +++ b/frontend/src/locales/en/admin.json @@ -5731,5 +5731,131 @@ "prevPage": "Previous page", "nextPage": "Next page" } + }, + "equipmentAcceptance": { + "title": "Equipment acceptance warning", + "sync": "Sync OA data", + "syncDone": "Synced {upserted}, skipped {skipped}, missing this time {absent}", + "syncFailed": "Failed to sync equipment acceptance data", + "tabLedger": "Waiting orders", + "tabSends": "Send records", + "tabConfig": "Alert settings", + "sendsLead": "The daily scan creates records waiting to be sent. They appear here after the Friday 18:00 summary goes out to each recipient. Names stay as they were at send time.", + "sendsEmpty": "No send records yet", + "sendsFailed": "Failed to load send records", + "scanAlerts": "Scan alerts", + "sendAlerts": "Send alerts", + "scanConfirm": "This syncs from E10 and creates records waiting to be sent.", + "sendConfirm": "This sends the waiting records to WeCom, one message per recipient.", + "scanDone": "Added {created}, updated {updated}, cancelled {cancelled}", + "sendDone": "Sent to {sent} people, {failed} failed", + "sendResult": "Result", + "sentAt": "Sent at", + "sendStatus": { + "pending": "Waiting to send", + "sent": "Sent", + "failed": "Failed", + "cancelled": "Cancelled" + }, + "configLead": "Each tier must be longer than the one before it. Saving affects only alerts created later. The send time is set on the schedule.", + "tier1": "Tier 1", + "tier2": "Tier 2", + "tier3": "Tier 3", + "tier4": "Tier 4", + "tierWho1": "Current handler", + "tierWho2": "Deputy manager", + "tierWho3": "COO", + "tierWho4": "General manager", + "dayUnit": "days", + "fixedRoles": "Fixed roles", + "role": { + "buyer_manager": "Procurement deputy manager", + "coo": "COO", + "executive": "General manager" + }, + "roleEmpty": "Not selected", + "selectUser": "Select", + "clearUser": "Clear", + "configPickOne": "Each role keeps one person. The name is for display; the saved value is the system user.", + "rulesTitle": "Recipient rules", + "rulesLead": "Who receives each tier stays fixed. Only the day thresholds change.", + "ruleTier": "Round", + "ruleTo": "To", + "ruleCc": "Cc", + "ruleOver": "Over {days} days", + "ruleTo1": "Current handler", + "ruleCc1": "Their supervisor and the applicant", + "ruleTo2": "The handler's deputy manager", + "ruleCc2": "COO and procurement deputy manager", + "ruleTo3": "COO", + "ruleCc3": "Procurement deputy manager", + "ruleTo4": "General manager", + "ruleCc4": "COO and procurement deputy manager", + "saveConfig": "Save settings", + "configSaveHint": "Sent alerts stay unchanged", + "configSaved": "Alert settings saved", + "configLoadFailed": "Failed to load alert settings", + "configSaveFailed": "Failed to save alert settings", + "configDaysInvalid": "Each tier must be longer than the previous one", + "configReadOnly": "Only an administrator can change these settings", + "loadFailed": "Failed to load acceptance orders", + "detailLoadFailed": "Failed to load the acceptance order", + "loading": "Loading", + "empty": "No acceptance orders have been synced yet", + "kpiWatching": "In progress", + "kpiOverdue": "Overdue", + "kpiStopped": "No further reminders", + "filterAll": "All", + "filterWatching": "In progress", + "filterOverdue": "Overdue", + "filterStopped": "No further reminders", + "filterNotStarted": "Not started", + "badgeOverdue": "Overdue", + "badgeOnTime": "Not yet due", + "currentHandlers": "Current handlers", + "daysValue": "{days} days", + "statusAll": "All statuses", + "status": "Status", + "acceptanceNo": "Acceptance no.", + "purchaseOrderNo": "Purchase order no.", + "applicant": "Applicant", + "currentNodes": "Current nodes", + "operators": "Operators", + "operatorsNote": "Operators on the current node. Each person is listed once.", + "timerStart": "Timer start", + "dwellDays": "Days in approval", + "actions": "Actions", + "detail": "View details", + "back": "Back to dwell list", + "canAccept": "Can accept", + "cannotAcceptNote": "Reason it cannot be accepted", + "cannotAcceptNote": "Reason it cannot be accepted", + "returnFlag": "Returned", + "unspecified": "Not specified", + "flowStatus": "Flow status", + "finishedAt": "Finished at", + "operatorName": "Name", + "jobNum": "Employee no.", + "flowStatusName": { + "draft": "Draft", + "approving": "Approving", + "archived": "Archived", + "forceFinished": "Force-finished", + "voided": "Voided", + "pendingSubmit": "Pending submit", + "paused": "Paused", + "withdrawn": "Withdrawn" + }, + "statusLabel": { + "watching": "In progress", + "not_started": "Not started", + "stopped_returned": "Returned, no further reminders", + "stopped_cannot_accept": "Cannot accept, no further reminders", + "stopped_archived": "Archived, no further reminders", + "stopped_force_finished": "Force-finished, no further reminders", + "stopped_voided": "Voided, no further reminders", + "stopped_revoked": "Revoked, no further reminders", + "excluded": "Outside monitoring" + } } } diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index 2398e3a7..2456d889 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -564,6 +564,13 @@ "VOUCHER_CHECK_PO_UPLOAD_FAILED": "Failed to upload the purchase-order PDF to the DMS PO-order folder.", "VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI authorization or token refresh failed.", "VOUCHER_CHECK_OA_E10_SQL_FAILED": "Failed to query the E10 sales-release table.", + "EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "E10 database settings for equipment-acceptance sync are incomplete.", + "EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "Failed to query E10 equipment-acceptance data.", + "EQUIPMENT_ACCEPTANCE_NOT_FOUND": "The equipment-acceptance sync record does not exist.", + "EQUIPMENT_ACCEPTANCE_FORBIDDEN": "You do not have access to the equipment acceptance warning.", + "EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "Only an administrator can sync equipment acceptance data.", + "EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "Each tier must be longer than the previous one, and each role must be an existing system user.", + "EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "Only an administrator can change equipment acceptance alert settings.", "VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "Failed to download the sales-release PDF from E10.", "VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "Sales-release data is invalid. Provide a valid invoice number and delivery number.", "VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "Some sales-release PDFs failed to fetch.", diff --git a/frontend/src/locales/th/admin.json b/frontend/src/locales/th/admin.json index 24655f76..694de97f 100644 --- a/frontend/src/locales/th/admin.json +++ b/frontend/src/locales/th/admin.json @@ -5731,5 +5731,131 @@ "prevPage": "หน้าก่อนหน้า", "nextPage": "หน้าถัดไป" } + }, + "equipmentAcceptance": { + "title": "การเตือนตรวจรับอุปกรณ์", + "sync": "ซิงก์ข้อมูล OA", + "syncDone": "ซิงก์แล้ว {upserted} รายการ ข้าม {skipped} รายการ ไม่พบในรอบนี้ {absent} รายการ", + "syncFailed": "ซิงก์ข้อมูลตรวจรับอุปกรณ์ไม่สำเร็จ", + "tabLedger": "รายการค้าง", + "tabSends": "บันทึกการส่ง", + "tabConfig": "ตั้งค่าการเตือน", + "sendsLead": "การสแกนรายวันสร้างรายการที่รอส่ง หลังสรุปส่งทุกวันศุกร์ 18:00 ตามผู้รับแล้ว จะแสดงที่นี่ ชื่อคงตามตอนที่ส่ง", + "sendsEmpty": "ยังไม่มีบันทึกการส่ง", + "sendsFailed": "โหลดบันทึกการส่งไม่สำเร็จ", + "scanAlerts": "สแกนการเตือน", + "sendAlerts": "ส่งการเตือน", + "scanConfirm": "ระบบจะซิงก์จาก E10 และสร้างรายการที่รอส่ง", + "sendConfirm": "ระบบจะส่งรายการที่รอส่งไป WeCom คนละหนึ่งข้อความ", + "scanDone": "เพิ่ม {created} รายการ อัปเดต {updated} รายการ ยกเลิก {cancelled} รายการ", + "sendDone": "ส่งถึง {sent} คน ไม่สำเร็จ {failed} คน", + "sendResult": "ผลลัพธ์", + "sentAt": "เวลาที่ส่ง", + "sendStatus": { + "pending": "รอส่ง", + "sent": "ส่งแล้ว", + "failed": "ส่งไม่สำเร็จ", + "cancelled": "ยกเลิกแล้ว" + }, + "configLead": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ การบันทึกมีผลเฉพาะการเตือนที่เกิดภายหลัง เวลาส่งตั้งในตารางงาน", + "tier1": "ขั้นที่ 1", + "tier2": "ขั้นที่ 2", + "tier3": "ขั้นที่ 3", + "tier4": "ขั้นที่ 4", + "tierWho1": "ผู้ดำเนินการปัจจุบัน", + "tierWho2": "รองผู้จัดการ", + "tierWho3": "COO", + "tierWho4": "ผู้จัดการทั่วไป", + "dayUnit": "วัน", + "fixedRoles": "ตำแหน่งคงที่", + "role": { + "buyer_manager": "รองผู้จัดการจัดซื้อ", + "coo": "COO", + "executive": "ผู้จัดการทั่วไป" + }, + "roleEmpty": "ยังไม่ได้เลือก", + "selectUser": "เลือก", + "clearUser": "ล้าง", + "configPickOne": "แต่ละตำแหน่งเก็บไว้คนเดียว ชื่อใช้แสดงผล ค่าที่บันทึกคือผู้ใช้ระบบ", + "rulesTitle": "กฎผู้รับ", + "rulesLead": "ผู้รับแต่ละขั้นไม่เปลี่ยนตามจำนวนวัน เปลี่ยนได้เฉพาะเกณฑ์วัน", + "ruleTier": "รอบ", + "ruleTo": "ผู้รับหลัก", + "ruleCc": "สำเนา", + "ruleOver": "เกิน {days} วัน", + "ruleTo1": "ผู้ดำเนินการปัจจุบัน", + "ruleCc1": "หัวหน้าตรงและผู้ขอ", + "ruleTo2": "รองผู้จัดการของผู้ดำเนินการ", + "ruleCc2": "COO และรองผู้จัดการจัดซื้อ", + "ruleTo3": "COO", + "ruleCc3": "รองผู้จัดการจัดซื้อ", + "ruleTo4": "ผู้จัดการทั่วไป", + "ruleCc4": "COO และรองผู้จัดการจัดซื้อ", + "saveConfig": "บันทึกการตั้งค่า", + "configSaveHint": "รายการที่ส่งแล้วไม่เปลี่ยน", + "configSaved": "บันทึกการตั้งค่าแล้ว", + "configLoadFailed": "โหลดการตั้งค่าไม่สำเร็จ", + "configSaveFailed": "บันทึกการตั้งค่าไม่สำเร็จ", + "configDaysInvalid": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ", + "configReadOnly": "เฉพาะผู้ดูแลระบบที่แก้ไขการตั้งค่าได้", + "loadFailed": "โหลดรายการใบตรวจรับไม่สำเร็จ", + "detailLoadFailed": "โหลดรายละเอียดใบตรวจรับไม่สำเร็จ", + "loading": "กำลังโหลด", + "empty": "ยังไม่มีใบตรวจรับที่ซิงก์มา", + "kpiWatching": "กำลังดำเนินการ", + "kpiOverdue": "เกินกำหนด", + "kpiStopped": "ไม่แจ้งเตือนอีก", + "filterAll": "ทั้งหมด", + "filterWatching": "กำลังดำเนินการ", + "filterOverdue": "เกินกำหนด", + "filterStopped": "ไม่แจ้งเตือนอีก", + "filterNotStarted": "ยังไม่เริ่ม", + "badgeOverdue": "เกินกำหนด", + "badgeOnTime": "ยังไม่เกินกำหนด", + "currentHandlers": "ผู้ดำเนินการปัจจุบัน", + "daysValue": "{days} วัน", + "statusAll": "ทุกสถานะ", + "status": "สถานะ", + "acceptanceNo": "เลขที่ใบตรวจรับ", + "purchaseOrderNo": "เลขที่ใบสั่งซื้อ", + "applicant": "ผู้ขอ", + "currentNodes": "โหนดปัจจุบัน", + "operators": "ผู้ดำเนินการ", + "operatorsNote": "ผู้ดำเนินการบนโหนดปัจจุบัน แต่ละคนแสดงหนึ่งแถว", + "timerStart": "จุดเริ่มนับเวลา", + "dwellDays": "จำนวนวันอนุมัติ", + "actions": "การทำงาน", + "detail": "ดูรายละเอียด", + "back": "กลับไปรายการค้าง", + "canAccept": "ตรวจรับได้", + "cannotAcceptNote": "เหตุผลที่ตรวจรับไม่ได้", + "cannotAcceptNote": "คำอธิบายที่ตรวจรับไม่ได้", + "returnFlag": "ถูกส่งกลับ", + "unspecified": "ยังไม่ระบุ", + "flowStatus": "สถานะกระบวนการ", + "finishedAt": "เวลาสิ้นสุด", + "operatorName": "ชื่อ", + "jobNum": "รหัสพนักงาน", + "flowStatusName": { + "draft": "ร่าง", + "approving": "กำลังอนุมัติ", + "archived": "จัดเก็บแล้ว", + "forceFinished": "บังคับจบ", + "voided": "ยกเลิกเอกสารแล้ว", + "pendingSubmit": "รอส่ง", + "paused": "หยุดชั่วคราว", + "withdrawn": "ถอนกลับ" + }, + "statusLabel": { + "watching": "กำลังดำเนินการ", + "not_started": "ยังไม่เริ่ม", + "stopped_returned": "ส่งกลับแล้ว ไม่แจ้งเตือนอีก", + "stopped_cannot_accept": "ตรวจรับไม่ได้ ไม่แจ้งเตือนอีก", + "stopped_archived": "จัดเก็บแล้ว ไม่แจ้งเตือนอีก", + "stopped_force_finished": "บังคับจบแล้ว ไม่แจ้งเตือนอีก", + "stopped_voided": "ยกเลิกแล้ว ไม่แจ้งเตือนอีก", + "stopped_revoked": "เพิกถอนแล้ว ไม่แจ้งเตือนอีก", + "excluded": "อยู่นอกขอบเขตติดตาม" + } } } diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index 53f14a38..b9b32bfc 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -564,6 +564,13 @@ "VOUCHER_CHECK_PO_UPLOAD_FAILED": "อัปโหลดไฟล์ PDF ใบสั่งซื้อไปยังโฟลเดอร์ PO订单 ในคลังเอกสารไม่สำเร็จ", "VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "การอนุญาตหรือรีเฟรชโทเค็น E10 OpenAPI ล้มเหลว", "VOUCHER_CHECK_OA_E10_SQL_FAILED": "ค้นตารางใบอนุญาตปล่อยสินค้าใน E10 ไม่สำเร็จ", + "EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "การตั้งค่าฐานข้อมูล E10 สำหรับซิงก์การตรวจรับอุปกรณ์ไม่ครบ", + "EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "ค้นข้อมูลการตรวจรับอุปกรณ์ใน E10 ไม่สำเร็จ", + "EQUIPMENT_ACCEPTANCE_NOT_FOUND": "ไม่พบรายการซิงก์การตรวจรับอุปกรณ์", + "EQUIPMENT_ACCEPTANCE_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการเตือนตรวจรับอุปกรณ์", + "EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ข้อมูลตรวจรับอุปกรณ์ได้", + "EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "จำนวนวันแต่ละขั้นต้องมากขึ้นตามลำดับ และตำแหน่งต้องเป็นผู้ใช้ระบบที่มีอยู่", + "EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบที่แก้ไขการตั้งค่าการเตือนตรวจรับอุปกรณ์ได้", "VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "ดาวน์โหลด PDF ใบอนุญาตปล่อยสินค้าจาก E10 ไม่สำเร็จ", "VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "ข้อมูลใบอนุญาตปล่อยสินค้าไม่ถูกต้อง กรุณาระบุเลขที่ใบแจ้งหนี้และเลขที่ใบส่งที่ถูกต้อง", "VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "ดึง PDF ใบอนุญาตปล่อยสินค้าบางไฟล์ไม่สำเร็จ", diff --git a/frontend/src/locales/zh-CN/admin.json b/frontend/src/locales/zh-CN/admin.json index 23798dc6..e65f2baf 100644 --- a/frontend/src/locales/zh-CN/admin.json +++ b/frontend/src/locales/zh-CN/admin.json @@ -5764,5 +5764,131 @@ "prevPage": "上一页", "nextPage": "下一页" } + }, + "equipmentAcceptance": { + "title": "设备验收预警", + "sync": "同步 OA 数据", + "syncDone": "已同步 {upserted} 张,跳过 {skipped} 张,本次未见 {absent} 张", + "syncFailed": "同步设备验收数据失败", + "tabLedger": "停留情况", + "tabSends": "发送记录", + "tabConfig": "预警配置", + "sendsLead": "每日扫描生成待发送。默认每周五 18:00 按收件人汇总发出后记在这里。已发送的姓名保持发送当时的人。", + "sendsEmpty": "还没有发送记录", + "sendsFailed": "读取发送记录失败", + "scanAlerts": "扫描预警", + "sendAlerts": "发送预警", + "scanConfirm": "将从 E10 同步,并生成待发送记录。", + "sendConfirm": "将把待发送记录按收件人发到企业微信。", + "scanDone": "新增 {created} 条,更新 {updated} 条,取消 {cancelled} 条", + "sendDone": "已向 {sent} 人发送,{failed} 人失败", + "sendResult": "结果", + "sentAt": "发送时间", + "sendStatus": { + "pending": "待发送", + "sent": "已发送", + "failed": "发送失败", + "cancelled": "已取消" + }, + "configLead": "四档天数须逐档增大。保存后只影响以后新产生的预警。发送时刻在排程里配置。", + "tier1": "第 1 档", + "tier2": "第 2 档", + "tier3": "第 3 档", + "tier4": "第 4 档", + "tierWho1": "当前处理人", + "tierWho2": "经副理", + "tierWho3": "COO", + "tierWho4": "总经理", + "dayUnit": "天", + "fixedRoles": "固定岗位", + "role": { + "buyer_manager": "采购经副理", + "coo": "COO", + "executive": "总经理" + }, + "roleEmpty": "未选择", + "selectUser": "选择", + "clearUser": "清除", + "configPickOne": "每个岗位只保留一人。姓名用于显示,保存的是系统用户。", + "rulesTitle": "取人规则", + "rulesLead": "主送对象不随天数改,只改超过多少天才触发。", + "ruleTier": "轮次", + "ruleTo": "主送", + "ruleCc": "抄送", + "ruleOver": "超过 {days} 天", + "ruleTo1": "当前节点处理人", + "ruleCc1": "其直接主管、采购担当", + "ruleTo2": "当前节点处理人的经副理", + "ruleCc2": "COO、采购经副理", + "ruleTo3": "COO", + "ruleCc3": "采购经副理", + "ruleTo4": "总经理", + "ruleCc4": "COO、采购经副理", + "saveConfig": "保存配置", + "configSaveHint": "已发送记录保持不变", + "configSaved": "预警配置已保存", + "configLoadFailed": "预警配置加载失败", + "configSaveFailed": "预警配置保存失败", + "configDaysInvalid": "四档天数须逐档增大", + "configReadOnly": "只有管理员可以修改配置", + "loadFailed": "验收单列表加载失败", + "detailLoadFailed": "验收单详情加载失败", + "loading": "正在加载", + "empty": "还没有同步到验收单", + "kpiWatching": "进行中", + "kpiOverdue": "已逾期", + "kpiStopped": "不再提醒", + "filterAll": "全部", + "filterWatching": "进行中", + "filterOverdue": "已逾期", + "filterStopped": "不再提醒", + "filterNotStarted": "未开始", + "badgeOverdue": "已逾期", + "badgeOnTime": "未超时", + "currentHandlers": "当前处理人", + "daysValue": "{days} 天", + "statusAll": "全部状态", + "status": "状态", + "acceptanceNo": "验收单单号", + "purchaseOrderNo": "采购单号", + "applicant": "申请人", + "currentNodes": "当前节点", + "operators": "操作人", + "operatorsNote": "当前节点上的操作人。同一人只保留一行。", + "timerStart": "计时起点", + "dwellDays": "签核天数", + "actions": "操作", + "detail": "查看详情", + "back": "返回停留情况", + "canAccept": "是否可以验收", + "cannotAcceptNote": "无法验收说明", + "cannotAcceptNote": "无法验收说明", + "returnFlag": "是否退回", + "unspecified": "未标明", + "flowStatus": "流程状态", + "finishedAt": "结束时间", + "operatorName": "姓名", + "jobNum": "工号", + "flowStatusName": { + "draft": "草稿", + "approving": "审批中", + "archived": "正常归档", + "forceFinished": "强制结束", + "voided": "已作废", + "pendingSubmit": "待提交", + "paused": "暂停", + "withdrawn": "撤销" + }, + "statusLabel": { + "watching": "进行中", + "not_started": "未开始", + "stopped_returned": "已退回,不再提醒", + "stopped_cannot_accept": "无法验收,不再提醒", + "stopped_archived": "已归档,不再提醒", + "stopped_force_finished": "已强制结束,不再提醒", + "stopped_voided": "已作废,不再提醒", + "stopped_revoked": "已撤销,不再提醒", + "excluded": "不在监控范围" + } } } diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index e02b51e9..43584c7b 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -564,6 +564,13 @@ "VOUCHER_CHECK_PO_UPLOAD_FAILED": "采购单 PDF 上传到文档库「PO订单」目录失败。", "VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI 授权或刷新 token 失败。", "VOUCHER_CHECK_OA_E10_SQL_FAILED": "查询 E10 销货放行单库表失败。", + "EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "设备验收同步的 E10 数据库配置不完整。", + "EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "查询 E10 设备验收数据失败。", + "EQUIPMENT_ACCEPTANCE_NOT_FOUND": "设备验收同步记录不存在。", + "EQUIPMENT_ACCEPTANCE_FORBIDDEN": "你没有设备验收预警的访问权限。", + "EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "仅管理员可同步设备验收数据。", + "EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "四档天数须逐档增大,岗位必须选择已有的系统用户。", + "EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "仅管理员可修改设备验收预警配置。", "VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "从 E10 下载销货放行单 PDF 失败。", "VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "销货放行单数据无效:请提供合法的发票号和销货单号。", "VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "销货放行单拉取部分失败。", diff --git a/frontend/src/locales/zh-TW/admin.json b/frontend/src/locales/zh-TW/admin.json index 2d117c34..6e915087 100644 --- a/frontend/src/locales/zh-TW/admin.json +++ b/frontend/src/locales/zh-TW/admin.json @@ -5731,5 +5731,131 @@ "prevPage": "上一頁", "nextPage": "下一頁" } + }, + "equipmentAcceptance": { + "title": "設備驗收預警", + "sync": "同步 OA 資料", + "syncDone": "已同步 {upserted} 張,略過 {skipped} 張,本次未見 {absent} 張", + "syncFailed": "同步設備驗收資料失敗", + "tabLedger": "停留情況", + "tabSends": "發送記錄", + "tabConfig": "預警配置", + "sendsLead": "每日掃描產生待發送。預設每週五 18:00 按收件人彙總發出後記在這裡。已發送的姓名保持發送當時的人。", + "sendsEmpty": "還沒有發送記錄", + "sendsFailed": "讀取發送記錄失敗", + "scanAlerts": "掃描預警", + "sendAlerts": "發送預警", + "scanConfirm": "將從 E10 同步,並產生待發送記錄。", + "sendConfirm": "將把待發送記錄按收件人發到企業微信。", + "scanDone": "新增 {created} 條,更新 {updated} 條,取消 {cancelled} 條", + "sendDone": "已向 {sent} 人發送,{failed} 人失敗", + "sendResult": "結果", + "sentAt": "發送時間", + "sendStatus": { + "pending": "待發送", + "sent": "已發送", + "failed": "發送失敗", + "cancelled": "已取消" + }, + "configLead": "四檔天數須逐檔增大。儲存後只影響以後新產生的預警。發送時刻在排程裡配置。", + "tier1": "第 1 檔", + "tier2": "第 2 檔", + "tier3": "第 3 檔", + "tier4": "第 4 檔", + "tierWho1": "目前處理人", + "tierWho2": "經副理", + "tierWho3": "COO", + "tierWho4": "總經理", + "dayUnit": "天", + "fixedRoles": "固定崗位", + "role": { + "buyer_manager": "採購經副理", + "coo": "COO", + "executive": "總經理" + }, + "roleEmpty": "未選擇", + "selectUser": "選擇", + "clearUser": "清除", + "configPickOne": "每個崗位只保留一人。姓名用來顯示,儲存的是系統使用者。", + "rulesTitle": "取人規則", + "rulesLead": "主送對象不隨天數改,只改超過多少天才觸發。", + "ruleTier": "輪次", + "ruleTo": "主送", + "ruleCc": "抄送", + "ruleOver": "超過 {days} 天", + "ruleTo1": "目前節點處理人", + "ruleCc1": "其直接主管、採購擔當", + "ruleTo2": "目前節點處理人的經副理", + "ruleCc2": "COO、採購經副理", + "ruleTo3": "COO", + "ruleCc3": "採購經副理", + "ruleTo4": "總經理", + "ruleCc4": "COO、採購經副理", + "saveConfig": "儲存配置", + "configSaveHint": "已發送紀錄保持不變", + "configSaved": "預警配置已儲存", + "configLoadFailed": "預警配置載入失敗", + "configSaveFailed": "預警配置儲存失敗", + "configDaysInvalid": "四檔天數須逐檔增大", + "configReadOnly": "只有管理員可以修改配置", + "loadFailed": "驗收單列表載入失敗", + "detailLoadFailed": "驗收單詳情載入失敗", + "loading": "正在載入", + "empty": "還沒有同步到驗收單", + "kpiWatching": "進行中", + "kpiOverdue": "已逾期", + "kpiStopped": "不再提醒", + "filterAll": "全部", + "filterWatching": "進行中", + "filterOverdue": "已逾期", + "filterStopped": "不再提醒", + "filterNotStarted": "未開始", + "badgeOverdue": "已逾期", + "badgeOnTime": "未超時", + "currentHandlers": "目前處理人", + "daysValue": "{days} 天", + "statusAll": "全部狀態", + "status": "狀態", + "acceptanceNo": "驗收單單號", + "purchaseOrderNo": "採購單號", + "applicant": "申請人", + "currentNodes": "目前節點", + "operators": "操作人", + "operatorsNote": "目前節點上的操作人。同一人只保留一行。", + "timerStart": "計時起點", + "dwellDays": "簽核天數", + "actions": "操作", + "detail": "查看詳情", + "back": "返回停留情況", + "canAccept": "是否可以驗收", + "cannotAcceptNote": "無法驗收說明", + "cannotAcceptNote": "無法驗收說明", + "returnFlag": "是否退回", + "unspecified": "未標明", + "flowStatus": "流程狀態", + "finishedAt": "結束時間", + "operatorName": "姓名", + "jobNum": "工號", + "flowStatusName": { + "draft": "草稿", + "approving": "審批中", + "archived": "正常歸檔", + "forceFinished": "強制結束", + "voided": "已作廢", + "pendingSubmit": "待提交", + "paused": "暫停", + "withdrawn": "撤銷" + }, + "statusLabel": { + "watching": "進行中", + "not_started": "未開始", + "stopped_returned": "已退回,不再提醒", + "stopped_cannot_accept": "無法驗收,不再提醒", + "stopped_archived": "已歸檔,不再提醒", + "stopped_force_finished": "已強制結束,不再提醒", + "stopped_voided": "已作廢,不再提醒", + "stopped_revoked": "已撤銷,不再提醒", + "excluded": "不在監控範圍" + } } } diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index f022607a..b6f3745b 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -564,6 +564,13 @@ "VOUCHER_CHECK_PO_UPLOAD_FAILED": "採購單 PDF 上傳到文件庫「PO訂單」目錄失敗。", "VOUCHER_CHECK_OA_E10_TOKEN_FAILED": "E10 OpenAPI 授權或刷新 token 失敗。", "VOUCHER_CHECK_OA_E10_SQL_FAILED": "查詢 E10 銷貨放行單庫表失敗。", + "EQUIPMENT_ACCEPTANCE_CONFIG_INVALID": "設備驗收同步的 E10 資料庫設定不完整。", + "EQUIPMENT_ACCEPTANCE_OA_SQL_FAILED": "查詢 E10 設備驗收資料失敗。", + "EQUIPMENT_ACCEPTANCE_NOT_FOUND": "設備驗收同步記錄不存在。", + "EQUIPMENT_ACCEPTANCE_FORBIDDEN": "你沒有設備驗收預警的存取權限。", + "EQUIPMENT_ACCEPTANCE_ADMIN_REQUIRED": "僅管理員可同步設備驗收資料。", + "EQUIPMENT_ACCEPTANCE_SETTINGS_INVALID": "四檔天數須逐檔增大,崗位必須選擇已有的系統使用者。", + "EQUIPMENT_ACCEPTANCE_SETTINGS_ADMIN_REQUIRED": "僅管理員可修改設備驗收預警配置。", "VOUCHER_CHECK_OA_E10_DOWNLOAD_FAILED": "從 E10 下載銷貨放行單 PDF 失敗。", "VOUCHER_CHECK_OA_SALES_RELEASE_INVALID": "銷貨放行單資料無效:請提供合法的發票號和銷貨單號。", "VOUCHER_CHECK_OA_SALES_RELEASE_PARTIAL": "銷貨放行單拉取部分失敗。", diff --git a/frontend/src/shared/utils/agent-registry.utils.ts b/frontend/src/shared/utils/agent-registry.utils.ts index 2f197915..013ab927 100644 --- a/frontend/src/shared/utils/agent-registry.utils.ts +++ b/frontend/src/shared/utils/agent-registry.utils.ts @@ -11,6 +11,7 @@ export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice'; export const AGENT_CODE_FILE_CHECK = 'file_check'; export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review'; export const AGENT_CODE_CONTRACT_PAYMENT = 'contract_payment'; +export const AGENT_CODE_EQUIPMENT_ACCEPTANCE = 'equipment_acceptance'; export const AGENT_CODE_VOUCHER_CHECK = 'voucher_check'; export const AGENT_CODE_IN_TRANSIT_TRANSFER = 'in_transit_transfer'; @@ -244,6 +245,11 @@ export function isContractPaymentAgent(agent: AgentLike): boolean { return resolveAgentCode(agent) === AGENT_CODE_CONTRACT_PAYMENT; } +/** 是否为设备验收预警 Agent(agent_code=equipment_acceptance)。 */ +export function isEquipmentAcceptanceAgent(agent: AgentLike): boolean { + return resolveAgentCode(agent) === AGENT_CODE_EQUIPMENT_ACCEPTANCE; +} + /** 是否为立账凭证检核 Agent(agent_code=voucher_check)。 */ export function isVoucherCheckAgent(agent: AgentLike): boolean { return resolveAgentCode(agent) === AGENT_CODE_VOUCHER_CHECK; From 02af2c959925b0b300a9280397e5dea204f54086 Mon Sep 17 00:00:00 2001 From: sophie Date: Mon, 12 Oct 2026 13:28:42 +0800 Subject: [PATCH 09/32] =?UTF-8?q?fix:=20=E6=81=A2=E5=A4=8Dcasdoor=E5=9F=9F?= =?UTF-8?q?=E5=90=8D=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.prod | 7 ++-- .env.test | 4 +- backend/app/services/auth/casdoor/client.py | 43 +-------------------- backend/tests/test_auth_common.py | 27 ------------- 4 files changed, 5 insertions(+), 76 deletions(-) diff --git a/.env.prod b/.env.prod index 21c3a04a..946b9e29 100644 --- a/.env.prod +++ b/.env.prod @@ -28,12 +28,11 @@ AUTH_LOGIN_MODE=casdoor # 是否启用 JWT 认证 AUTH_JWT_REQUIRED=true -# 令牌 iss 仍是公网域名,不能改成 IP。证书恢复后把下面两个 HTTP 地址改回 https://auth.well-trust.com。 AUTH_JWT_ISSUER=https://auth.well-trust.com AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 -AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks -# 临时绕开 auth.well-trust.com 过期证书。Casdoor 直连 8870,不经过 443。 -CASDOOR_BASE_URL=http://192.168.100.230:8870 +AUTH_JWT_JWKS_URL=https://auth.well-trust.com/.well-known/jwks +# Casdoor OIDC 服务入口 +CASDOOR_BASE_URL=https://auth.well-trust.com # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab diff --git a/.env.test b/.env.test index 64dda6a0..2b64a2d9 100644 --- a/.env.test +++ b/.env.test @@ -26,13 +26,11 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com AUTH_LOGIN_MODE=casdoor # 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。 -# 令牌 iss 仍是公网域名,不能改成 IP。证书恢复后把 CASDOOR_BASE_URL 改回 https://autht.well-trust.com。 AUTH_JWT_ISSUER=https://autht.well-trust.com AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks # Casdoor -# 临时绕开 autht.well-trust.com 过期证书。Casdoor 直连 8870,不经过 443。 -CASDOOR_BASE_URL=http://192.168.100.192:8870 +CASDOOR_BASE_URL=https://autht.well-trust.com # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab diff --git a/backend/app/services/auth/casdoor/client.py b/backend/app/services/auth/casdoor/client.py index d9da8425..d39f704b 100644 --- a/backend/app/services/auth/casdoor/client.py +++ b/backend/app/services/auth/casdoor/client.py @@ -4,7 +4,6 @@ backend/app/services/auth/casdoor/client.py 用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。 依赖:requests、CasdoorConfig、Casdoor 错误映射。 逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。 -discovery 仍可能广告 HTTPS 域名,服务端换票和 userinfo 会改写到 CASDOOR_BASE_URL。 """ from __future__ import annotations @@ -41,15 +40,6 @@ class CasdoorTokenResult: return dict(self.raw) -# 仅改写后端自己调用的端点。authorization_endpoint 留给浏览器,避免把用户重定向到内网地址。 -_SERVER_ENDPOINT_KEYS = ( - 'token_endpoint', - 'userinfo_endpoint', - 'jwks_uri', - 'introspection_endpoint', -) - - class CasdoorClient: """无业务模型依赖的 Casdoor OAuth/OIDC 客户端。""" @@ -68,13 +58,7 @@ class CasdoorClient: self._metadata_lock = Lock() def oidc_metadata(self) -> dict[str, Any]: - """ - 读取并缓存 OIDC discovery 文档 10 分钟。 - - 核心逻辑:先请求 CASDOOR_BASE_URL 上的 discovery。若换票、userinfo、JWKS - 仍指向 AUTH_JWT_ISSUER 的 HTTPS 源,改写到 CASDOOR_BASE_URL,避开过期证书。 - 浏览器使用的 authorization_endpoint 保持 discovery 原值。 - """ + """读取并缓存 OIDC discovery 文档 10 分钟。""" now = datetime.now(timezone.utc) if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now: return dict(self._metadata) @@ -90,35 +74,10 @@ class CasdoorClient: data = response.json() or {} if not isinstance(data, dict): raise RuntimeError('Casdoor OIDC metadata is invalid') - # [STEP 1] 公网证书过期时,Casdoor 仍在 discovery 里广告 HTTPS 域名。 - # 后端改走已配置的 HTTP 入口,令牌 iss 仍按 AUTH_JWT_ISSUER 校验。 - data = self._rewrite_server_endpoints(data) self._metadata = data self._metadata_expires_at = now + timedelta(minutes=10) return dict(data) - def _rewrite_server_endpoints(self, data: dict[str, Any]) -> dict[str, Any]: - """ - 把 discovery 中指向签发方源站的服务端地址改写到 CASDOOR_BASE_URL。 - - Args: - data: Casdoor openid-configuration JSON。 - - Returns: - 改写 token、userinfo、jwks 后的文档。签发方与 base URL 相同时原样返回。 - """ - issuer = self.config.issuer.rstrip('/') - base_url = self.config.base_url.rstrip('/') - if not issuer or not base_url or issuer == base_url: - return data - prefix = f'{issuer}/' - rewritten = dict(data) - for key in _SERVER_ENDPOINT_KEYS: - value = str(rewritten.get(key) or '').strip() - if value == issuer or value.startswith(prefix): - rewritten[key] = f'{base_url}{value[len(issuer):]}' - return rewritten - def _token_endpoint(self) -> str: """从 discovery 文档读取 token endpoint,缺失时安全失败。""" endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip() diff --git a/backend/tests/test_auth_common.py b/backend/tests/test_auth_common.py index d145b871..ab31a6e0 100644 --- a/backend/tests/test_auth_common.py +++ b/backend/tests/test_auth_common.py @@ -135,33 +135,6 @@ def test_casdoor_config_repr_does_not_expose_secret(app): assert 'top-secret-value' not in repr(config) -def test_casdoor_server_endpoints_follow_base_url_when_issuer_uses_expired_https(): - """公网 HTTPS 证书不可用时,换票和 userinfo 改走 CASDOOR_BASE_URL,浏览器授权地址保持原域名。""" - http = FakeHttp() - http.get = lambda url, **kwargs: FakeResponse({ - 'issuer': 'https://auth.example.com', - 'authorization_endpoint': 'https://auth.example.com/login/oauth/authorize', - 'token_endpoint': 'https://auth.example.com/api/login/oauth/access_token', - 'userinfo_endpoint': 'https://auth.example.com/api/userinfo', - 'jwks_uri': 'https://auth.example.com/.well-known/jwks', - }) if url.endswith('/.well-known/openid-configuration') else FakeResponse({}) - client = CasdoorClient(CasdoorConfig( - base_url='http://192.168.100.230:8870', - client_id='peer-client', - client_secret='peer-secret', - issuer='https://auth.example.com', - ), http_session=http) - metadata = client.oidc_metadata() - # 后端换票不能再访问过期证书上的 HTTPS 域名。 - assert metadata['token_endpoint'] == 'http://192.168.100.230:8870/api/login/oauth/access_token' - assert metadata['userinfo_endpoint'] == 'http://192.168.100.230:8870/api/userinfo' - assert metadata['jwks_uri'] == 'http://192.168.100.230:8870/.well-known/jwks' - # 浏览器授权仍使用 discovery 原地址。 - assert metadata['authorization_endpoint'] == 'https://auth.example.com/login/oauth/authorize' - client.password_login('alice', 'user-password') - assert http.posts[0][0] == 'http://192.168.100.230:8870/api/login/oauth/access_token' - - def test_casdoor_password_client_request_is_framework_independent(): """公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。""" http = FakeHttp() From a8d721e793d02d65c06592152db48b5ef94851e7 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 12 Oct 2026 21:25:35 +0800 Subject: [PATCH 10/32] =?UTF-8?q?feat(in-transit-transfer):=20=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E8=B0=83=E6=8B=A8=E6=94=AF=E6=8C=81=E6=94=B6=E6=96=99?= =?UTF-8?q?=E6=97=A5=E6=9C=9F=E8=8C=83=E5=9B=B4=E5=B9=B6=E6=94=B6=E5=BD=92?= =?UTF-8?q?=E6=8E=92=E7=A8=8B=E9=80=9A=E7=94=A8=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 自动调拨任务新增收料日期范围动态参数(receipt_date_from/to):缩小匹配面便于测试与排障,非法范围由匹配层校验拒绝 - 排程动态参数表单支持占位文案 key 与空值归 null,日期筛选直达任务配置 - 执行结果通知统一走排程「启用通知」通用企微通知,任务不再自建领域通知 - 门禁契约澄清 retry_inventory_matching 语义:复用已抓库存重匹配不重抓;STP 多候选无匹配时阶段能力禁用、不隐式触发 RPA - 同步匹配/自动调拨/排程测试、四语言文案与文档 --- .../in_transit_transfer/auto_transfer.py | 6 + .../services/in_transit_transfer/contracts.py | 15 +- .../in_transit_transfer/matching_service.py | 30 +++- .../in_transit_transfer/serializers.py | 3 + backend/app/services/schedule/__init__.py | 2 + .../schedule/freight_receipt_rpa_finalize.py | 109 +++++++++++++- .../schedule/in_transit_transfer_job.py | 92 ++++++++---- backend/app/services/schedule/job_registry.py | 27 ++-- .../schedule/shipping_receipt_rpa_archive.py | 5 + .../shipping_notice/process_gate_contract.py | 11 +- .../tests/api/test_in_transit_transfer_api.py | 3 +- .../in_transit_transfer/test_auto_transfer.py | 26 ++++ .../in_transit_transfer/test_chat_actions.py | 3 +- .../test_matching_service.py | 59 +++++++- .../in_transit_transfer/test_schedule_jobs.py | 121 ++++++++++----- .../test_freight_receipt_rpa_notifications.py | 58 +++++++- .../features/in-transit-transfer/technical.md | 3 +- docs/features/shipping-notice/technical.md | 2 +- docs/funclist.md | 2 +- .../components/DynamicTaskParamsForm.vue | 4 +- .../messages/TransferBacklogSummaryCard.vue | 14 +- .../messages/TransferMatchCard.spec.ts | 80 +++++++++- .../components/messages/TransferMatchCard.vue | 44 +++++- .../ReviewCurrentProcessingCard.vue | 51 ++++++- .../src/features/chat/types/transfer.types.ts | 3 + .../views/ShippingOrderReviewView.spec.ts | 139 ++++++++++++++++++ .../chat/views/ShippingOrderReviewView.vue | 57 +++++-- frontend/src/locales/en/admin.json | 5 +- frontend/src/locales/en/chat.json | 3 +- frontend/src/locales/th/admin.json | 5 +- frontend/src/locales/th/chat.json | 3 +- frontend/src/locales/zh-CN/admin.json | 5 +- frontend/src/locales/zh-CN/chat.json | 3 +- frontend/src/locales/zh-TW/admin.json | 5 +- frontend/src/locales/zh-TW/chat.json | 3 +- 35 files changed, 863 insertions(+), 138 deletions(-) diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py index 605db83d..e7e65974 100644 --- a/backend/app/services/in_transit_transfer/auto_transfer.py +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -32,6 +32,8 @@ class AutoTransferOutcome: def run_auto_transfer(*, business_date: str, deps: TransferDeps, source_codes: list[str] | None = None, recover_history: bool = True, + receipt_date_from: str | None = None, + receipt_date_to: str | None = None, sender: WeComSender | None = None, recipients: list[str] | None = None) -> AutoTransferOutcome: """执行一次自动调拨排程。 @@ -44,6 +46,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, deps: 注入依赖。 source_codes: 来源实例列表(缺省全部启用来源)。 recover_history: 是否执行历史恢复。 + receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小 + 匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。 sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。 Returns: AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。 @@ -59,6 +63,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, source_codes=source_codes or [], business_date=business_date, deps=deps, + receipt_date_from=receipt_date_from, + receipt_date_to=receipt_date_to, ) # [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、 # 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。 diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py index 33f7f75e..34e36ea5 100644 --- a/backend/app/services/in_transit_transfer/contracts.py +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -112,17 +112,26 @@ class MatchingItemDTO: # 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。 unit: str = "" # 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省): - # item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at); - # stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。 + # item_id=行主键(批量操作/待处理池回链);checked_at=行库存查得时刻(见 _item_dto); + # stale=距库存取数超过展示阈值;file_current=行评估版本戳仍是该来源当前可用文件。 item_id: int = 0 checked_at: str | None = None stale: bool = False file_current: bool = False + # [2026-10-12 单据数口径修正] 执行建单五元组首键:路由解析所得外部组织 + # (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐, + # 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。 + external_org: str = "" @dataclass(frozen=True) class MatchingSummaryDTO: - """匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。""" + """匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。 + + estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单 + 五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse) + 去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。 + """ matching_id: str status: str diff --git a/backend/app/services/in_transit_transfer/matching_service.py b/backend/app/services/in_transit_transfer/matching_service.py index 2dd903be..6b7e3ace 100644 --- a/backend/app/services/in_transit_transfer/matching_service.py +++ b/backend/app/services/in_transit_transfer/matching_service.py @@ -389,6 +389,23 @@ def run_matching( estimated_quantity = sum( (item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0") ) + # [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组 + # (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组, + # 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip() + # 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由 + # 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」 + # 口径在多行同组时高估单据数,误导用户。 + estimated_document_keys = { + ( + item.external_org, + str(item.source_code or "").strip(), + str(item.receipt_date or "").strip(), + str(item.from_warehouse or "").strip(), + str(item.to_warehouse or "").strip(), + ) + for item in items + if item.result == RESULT_EXECUTABLE + } snapshot = { "scope": sorted(set(source_codes)), "business_date": business_date, @@ -433,7 +450,7 @@ def run_matching( expires_at="", counts=counts, estimated_transfer_quantity=str(estimated_quantity), - estimated_external_write_count=counts.executable_count, + estimated_external_write_count=len(estimated_document_keys), matching_hash=matching_hash, ) return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple) @@ -621,8 +638,11 @@ def _matching_rows( row.result_code = match row.result_message = "strict quantity mismatch" row.updated_at = now + # 本行已完成路由解析:external_org 随行透出(执行建单五元组首键, + # 2026-10-12 单据数口径修正——预计单据数按五元组去重依赖本字段)。 output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.inventory_stale_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds), + external_org=str(route.external_org or "").strip())) return output, pending_count @@ -944,6 +964,7 @@ def _item_dto( latest: dict, moment: datetime, inventory_stale_ttl_seconds: int, + external_org: str = "", ) -> MatchingItemDTO: """把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。 @@ -953,8 +974,10 @@ def _item_dto( moment: 新鲜度判定基准时间。 inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds; 仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。 + external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数 + 口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。 Returns: - MatchingItemDTO(含 item_id / checked_at / stale / file_current)。 + MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。 """ evaluated_sha = _item_evaluated_sha(item) inventory_checked_at = item.inventory_checked_at @@ -1002,6 +1025,7 @@ def _item_dto( stale=bool(inventory_checked_at) and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds, file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"), + external_org=external_org, ) diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py index eccc6ddc..4d7286f2 100644 --- a/backend/app/services/in_transit_transfer/serializers.py +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -81,6 +81,9 @@ def serialize_item(item) -> dict[str, Any]: "to_quantity": str(item.to_quantity), # 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。 "unit": item.unit, + # [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行 + # 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。 + "external_org": item.external_org, "result": item.result, "reason": item.reason, "raw_lines": [ diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index acfe0645..5e2330ab 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -344,8 +344,10 @@ def _register_headers_from_config() -> None: if cfg.alias_order and cfg.header_labels: register_schedule_header(name, cfg.alias_order, cfg.header_labels) from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers + from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers register_inventory_rpa_excel_headers() + register_receipt_rpa_excel_headers() def reload_config() -> dict[str, Any]: diff --git a/backend/app/services/schedule/freight_receipt_rpa_finalize.py b/backend/app/services/schedule/freight_receipt_rpa_finalize.py index 817037f8..6dc04d8d 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_finalize.py +++ b/backend/app/services/schedule/freight_receipt_rpa_finalize.py @@ -9,16 +9,83 @@ backend/app/services/schedule/freight_receipt_rpa_finalize.py from __future__ import annotations from datetime import datetime, timedelta +from typing import Any from flask import current_app from app import db from app.models import ScheduleRun, ScheduleTask from app.models import ShippingReceiptRpaUnitRun -from app.services.schedule import normalize_platform_api_path +from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header +from app.services.schedule.excel_service import export_schedule_result_excel from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY from app.services.shipping_notice.audit_service import append_shipping_audit_event +_RECEIPT_RPA_HEADER_ORDER = [ + "source_code", + "warehouse_id", + "connector_type", + "receipt_file_count", + "export_status", + "skip_reason", + "error_message", +] +_RECEIPT_RPA_HEADER_LABELS = { + "source_code": "收料源", + "warehouse_id": "仓库", + "connector_type": "连接器", + "receipt_file_count": "归档文件数", + "export_status": "导出状态", + "skip_reason": "跳过原因", + "error_message": "错误原因", +} + + +def register_receipt_rpa_excel_headers() -> None: + """ + 注册货代收料 RPA 排程 Excel 列头(幂等)。 + 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 + """ + register_schedule_header( + RECEIPT_RPA_JOB_KEY, + _RECEIPT_RPA_HEADER_ORDER, + _RECEIPT_RPA_HEADER_LABELS, + ) + + +def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]: + """ + 收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 + + 核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致; + 归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。 + + Args: + units: 该 run 的全部收料单元(已全部终态)。 + + Returns: + list[dict]: 按 unit.id 升序的明细行。 + """ + rows: list[dict[str, Any]] = [] + for unit in sorted(units, key=lambda item: item.id): + status = unit.status + if status == 'empty': + export_status = 'skipped' + elif status == 'cancelled': + export_status = 'failed' + else: + export_status = status + rows.append({ + 'source_code': unit.source_code, + 'warehouse_id': unit.warehouse_id or '', + 'connector_type': unit.connector_type or '', + 'receipt_file_count': len(unit.files or []), + 'export_status': export_status, + 'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '', + 'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '', + }) + return rows + def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: """仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。""" @@ -213,6 +280,44 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed' run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None + # [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 + register_receipt_rpa_excel_headers() + header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY) + excel_export_ok = True + excel_data, excel_name, excel_size = None, None, 0 + try: + excel_data, _excel_name, excel_size = export_schedule_result_excel( + run_no=run.run_no, + summary={ + 'status': run.status, + 'total_count': len(units), + 'success_count': success_count, + 'skipped_count': skipped_count, + 'failed_count': failed_count, + 'duration_ms': run.duration_ms, + }, + details=_build_receipt_finalize_details(units), + header_order=header_order, + header_labels=header_labels, + ) + except Exception as excel_exc: + excel_export_ok = False + current_app.logger.error( + '[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc, + ) + # 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。 + if run.status == 'success': + run.status = 'partial_failed' + run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000] + else: + # 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 + from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name + + excel_name = receipt_rpa_result_excel_name(run) + run.excel_file_data = excel_data + run.excel_file_name = excel_name if excel_data else None + run.excel_file_size = excel_size or 0 + # [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。 archive_summary = { 'raw_receipt_zip_available': False, @@ -237,6 +342,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count, + 'excel_export_status': 'ok' if excel_export_ok else 'failed', + 'excel_failed': not excel_export_ok, **archive_summary, } db.session.commit() diff --git a/backend/app/services/schedule/in_transit_transfer_job.py b/backend/app/services/schedule/in_transit_transfer_job.py index ec2fb621..04cd90c3 100644 --- a/backend/app/services/schedule/in_transit_transfer_job.py +++ b/backend/app/services/schedule/in_transit_transfer_job.py @@ -1,24 +1,27 @@ """自动调拨排程。 -用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。 -依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、 - receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。 +用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走 + 排程「启用通知」通用企微通知,本任务不自建领域通知。 +依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、 + receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、 + date_policy(业务日与日期解析)。 逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA), - 不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造 - sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed - 抑制框架卡;硬失败不置标记以便框架兜底。 + 不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围 + 以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层; + 空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持 + 静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。 """ from __future__ import annotations +from datetime import timedelta from typing import Any from app.models import ScheduleRun, ScheduleTask from app.services.in_transit_transfer import deps as transfer_deps from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer -from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.date_policy import business_date_now, parse_date from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes -from app.services.in_transit_transfer.wecom_sender import WecomSummarySender from app.services.schedule.job_registry import ScheduleExecuteResult @@ -45,41 +48,77 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]: return codes -def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - """自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。 - - 核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer; - 仅在返回后按结果决定是否置 domain_notification_managed——有 run_no - (成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡; - 硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。 +def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None: + """把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。 Args: - task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。 - run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。 + business_date: 业务日期 T(YYYY-MM-DD)。 + offset_days: 偏移天数(须为非负整数;None/空视为未配置)。 + label: 参数中文名(写错误信息用)。 + errors: 错误累积列表(非法配置写入后返回 None,由调用方快速失败)。 + Returns: + 'YYYY-MM-DD';未配置或非法时为 None(非法同时落错误)。 + """ + if offset_days is None or offset_days == "": + return None + try: + days = int(offset_days) + except (TypeError, ValueError): + errors.append(f"{label}须为非负整数(当前值 {offset_days!r})") + return None + if days < 0 or float(offset_days) != days: + errors.append(f"{label}须为非负整数(当前值 {offset_days!r})") + return None + return (parse_date(business_date) - timedelta(days=days)).isoformat() + + +def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。 + + 核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单 + 底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置 + domain_notification_managed 抑制框架完成卡(C5 空数据日静默); + 有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。 + 可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days), + 执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面; + 偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层 + ValidationError 落 errors 走硬失败路径。 + + Args: + task: 排程任务(job_params: source_codes/recover_history/ + receipt_from_offset_days/receipt_to_offset_days)。 + run: 排程执行批次(空数据日写入 response_summary_json 标记)。 Returns: ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。 """ params = _task_params(task) source_codes = _wanted_source_codes(task) recover_history = bool(params.get("recover_history", True)) - recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()] + business_date = str(business_date_now()) - # 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。 - sender = WecomSummarySender() if recipients else None + # [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知), + # 防止坏参数被静默忽略后退化成全量积压处理。 + param_errors: list[str] = [] + receipt_date_from = _offset_to_date( + business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors) + receipt_date_to = _offset_to_date( + business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors) + if param_errors: + return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors) deps = transfer_deps.get_transfer_dependencies() outcome = run_auto_transfer( - business_date=str(business_date_now()), + business_date=business_date, deps=deps, source_codes=source_codes, recover_history=recover_history, - sender=sender, - recipients=recipients, + receipt_date_from=receipt_date_from, + receipt_date_to=receipt_date_to, ) - # [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日 - # (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。 - if recipients and (outcome.run_no or not outcome.errors): + # [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置 + # 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。 + if not outcome.run_no and not outcome.errors: run.response_summary_json = { **(run.response_summary_json or {}), "domain_notification_managed": True, @@ -94,7 +133,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc results.append({ "run_no": outcome.run_no, "status": outcome.run_status, - "notification_status": outcome.notification_status, }) elif not outcome.errors: # 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。 diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index c3bbe733..53538d8a 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -566,10 +566,8 @@ def _register_builtin_platform_jobs() -> None: label="在途自动调拨", handler=run_in_transit_transfer_schedule, description=( - "自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪" - "(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;" - "每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。" - "执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。" + "自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;" + "缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。" ), category="platform", params_schema=( @@ -591,16 +589,23 @@ def _register_builtin_platform_jobs() -> None: "default": True, }, { - "key": "notify_user_ids", - "type": "multi_select", - "label": "通知人", - "label_key": "admin.schedule.form.transferNotifyUsers", + "key": "receipt_from_offset_days", + "type": "number", + "label": "收料日期起(T-N)", + "label_key": "admin.schedule.form.transferReceiptDateFrom", "required": False, - "default": [], - "options_source": "users", + "help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。", + }, + { + "key": "receipt_to_offset_days", + "type": "number", + "label": "收料日期止(T-N)", + "label_key": "admin.schedule.form.transferReceiptDateTo", + "required": False, + "help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。", }, ), - defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []}, + defaults={"source_codes": [], "recover_history": True}, )) diff --git a/backend/app/services/schedule/shipping_receipt_rpa_archive.py b/backend/app/services/schedule/shipping_receipt_rpa_archive.py index 19b7f726..b43ea9c9 100644 --- a/backend/app/services/schedule/shipping_receipt_rpa_archive.py +++ b/backend/app/services/schedule/shipping_receipt_rpa_archive.py @@ -110,6 +110,11 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str: return f'{receipt_rpa_attachment_stem(run)}-收料.zip' +def receipt_rpa_result_excel_name(run: ScheduleRun) -> str: + """收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。""" + return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx' + + def _receipt_raw_zip_archive_path(run_no: str) -> Path: """磁盘归档路径:/.zip。""" return Path(get_receipt_archive_dir()) / f'{run_no}.zip' diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index d02ba303..81c210aa 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -478,17 +478,22 @@ def inventory_preparation_primary_action( """裁决库存准备 Gate 面向业务用户的主动作。 单源合并(用户拍板):库存失败只保留 2 个按钮 —— - ``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching`` - (优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。 + ``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching`` + (复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。 已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 ``retry_inventory_matching``。 + 边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。 + 因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用 + (disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task), + 重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。 """ normalized_status = str(status or '').strip().lower() normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': return 'poll_inventory_preparation' if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: - # [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。 + # [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力 + # 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。 return 'retry_inventory_matching' if normalized_status in {'blocked_manual', 'blocked_retryable'}: return 'retry_inventory_preparation' diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index b6ed3b11..e0543465 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -122,7 +122,8 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he data = body["data"] assert data["matching_id"].startswith("MTG-") assert data["matching_hash"].startswith("sha256:") - assert data["estimated_external_write_count"] == 2 + # [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。 + assert data["estimated_external_write_count"] == 1 assert body.get("request_id") diff --git a/backend/tests/services/in_transit_transfer/test_auto_transfer.py b/backend/tests/services/in_transit_transfer/test_auto_transfer.py index a4f4c105..a406a047 100644 --- a/backend/tests/services/in_transit_transfer/test_auto_transfer.py +++ b/backend/tests/services/in_transit_transfer/test_auto_transfer.py @@ -64,3 +64,29 @@ def test_executes_and_propagates_result_when_executable(monkeypatch): assert outcome.run_no == "RUN-20260928-XYZ789" assert outcome.run_status == "success" assert outcome.errors == [] + + +def test_passes_receipt_date_range_to_matching(monkeypatch): + """可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。""" + captured = {} + + def _fake_create(**kwargs): + captured.update(kwargs) + return _summary(0) + + monkeypatch.setattr(at, "create_matching", _fake_create) + + at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + receipt_date_from="2026-09-01", receipt_date_to="2026-09-05", + ) + # 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。 + assert captured["receipt_date_from"] == "2026-09-01" + assert captured["receipt_date_to"] == "2026-09-05" + + at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + ) + # 断言:缺省(留空)不缩小匹配面,范围参数为 None。 + assert captured["receipt_date_from"] is None + assert captured["receipt_date_to"] is None diff --git a/backend/tests/services/in_transit_transfer/test_chat_actions.py b/backend/tests/services/in_transit_transfer/test_chat_actions.py index 96751589..7574fee4 100644 --- a/backend/tests/services/in_transit_transfer/test_chat_actions.py +++ b/backend/tests/services/in_transit_transfer/test_chat_actions.py @@ -85,7 +85,8 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): assert event.data["message_type"] == "transfer-match" payload = event.data["payload"] assert payload["kind"] == "match" - assert payload["summary"]["estimated_external_write_count"] == 2 + # [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。 + assert payload["summary"]["estimated_external_write_count"] == 1 assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"} assert payload["sources"][0]["source_code"] == "DBS-AWSBI" diff --git a/backend/tests/services/in_transit_transfer/test_matching_service.py b/backend/tests/services/in_transit_transfer/test_matching_service.py index 66da2204..88d70c02 100644 --- a/backend/tests/services/in_transit_transfer/test_matching_service.py +++ b/backend/tests/services/in_transit_transfer/test_matching_service.py @@ -57,7 +57,9 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) assert summary.counts.blocked_count == 0 assert summary.status == "ready_to_execute" assert summary.matching_hash.startswith("sha256:") - assert summary.estimated_external_write_count == 3 + # [2026-10-12 单据数口径修正] 3 行可执行按执行建单五元组去重:DBS 两行 + # 同(org,source,date,from,to)合并 1 张 + CRANE 1 行 1 张 = 2(原口径=行数 3)。 + assert summary.estimated_external_write_count == 2 # 明细 DTO 决策 6/7:拨出/拨入仓库与数量对 items = {item.invoice_no: item for item in result.items} assert items["HOM-001"].from_warehouse == "DBS-TRANSIT" @@ -66,6 +68,61 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行 +def test_estimated_document_count_merges_same_group(dbs_ready_file): + """[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。 + + 场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to) + 全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2; + 并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。 + """ + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + result = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result.summary.counts.executable_count == 2 + # HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。 + assert result.summary.estimated_external_write_count == 1 + items = {item.invoice_no: item for item in result.items} + assert items["HOM-001"].external_org == "HX-CN01" + assert items["HOX-002"].external_org == "HX-CN01" + + +def test_estimated_document_count_splits_by_receipt_date(): + """[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。 + + 锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键, + 跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。 + """ + deps, erp, _ = _deps({ + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-009", + "file_version": "v9", + "checksum": "e" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A", + "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", + "movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, + {"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B", + "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", + "movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, + ], + }) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600") + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + result = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result.summary.counts.executable_count == 2 + assert result.summary.estimated_external_write_count == 2 + + def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file): """当天收料 → not_matured,外部系统 调用次数为 0。""" deps, erp, _ = _deps(same_day_receipt_file) diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py index 68e20a2e..d8a30f8e 100644 --- a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -29,7 +29,9 @@ def test_transfer_job_registered_with_schedule_defaults(): assert job is not None assert job.enabled keys = {field.get("key") for field in job.params_schema} - assert {"source_codes", "recover_history"} <= keys + assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys + # 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。 + assert "notify_user_ids" not in keys assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻" @@ -123,17 +125,8 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch): assert _wanted_source_codes(string_param) == ["DBS_HUB"] -class _FakeSender: - """记录实例化的发送器替身(断言 handler 接线,不发真实消息)。""" - - instantiated = 0 - - def __init__(self): - type(self).instantiated += 1 - - -def test_handler_wires_sender_and_domain_notification(monkeypatch): - """配了通知人:构造 sender、置领域自管标记、recipients 透传。""" +def test_handler_empty_data_day_stays_silent(monkeypatch): + """空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。""" import app.services.schedule.in_transit_transfer_job as job_mod from app.models import ScheduleRun, ScheduleTask @@ -147,28 +140,32 @@ def test_handler_wires_sender_and_domain_notification(monkeypatch): monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) - class _FakeSenderInner: - pass - - monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner) - - task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]}) + task = ScheduleTask(job_params={"source_codes": [], "recover_history": True}) run = ScheduleRun(run_no="RUNR-1", status="running") total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run) + # 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。 + assert "sender" not in captured + assert "recipients" not in captured + assert captured["receipt_date_from"] is None + assert captured["receipt_date_to"] is None assert captured["source_codes"] == ["CRANE_SGP"] - assert captured["recipients"] == ["7"] - assert isinstance(captured["sender"], _FakeSenderInner) + assert captured["recover_history"] is True assert run.response_summary_json["domain_notification_managed"] is True assert (total, success, failed, skipped) == (0, 0, 0, 0) + assert results == [] + assert any("no executable items" in w for w in warnings) -def test_handler_without_recipients_skips_domain_notification(monkeypatch): - """未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。""" +def test_handler_converts_t_minus_offsets(monkeypatch): + """T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。""" + from datetime import date + import app.services.schedule.in_transit_transfer_job as job_mod from app.models import ScheduleRun, ScheduleTask monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12)) captured = {} def _fake_auto_transfer(**kwargs): @@ -178,43 +175,91 @@ def test_handler_without_recipients_skips_domain_notification(monkeypatch): monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2}) + run = ScheduleRun(run_no="RUNR-4", status="running") + job_mod.run_in_transit_transfer_schedule(task, run) + + # 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。 + assert captured["business_date"] == "2026-10-12" + assert captured["receipt_date_from"] == "2026-10-08" + assert captured["receipt_date_to"] == "2026-10-10" + + +def test_handler_rejects_invalid_offset_without_execution(monkeypatch): + """偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + + def _must_not_run(**kwargs): + raise AssertionError("run_auto_transfer must not run with invalid offsets") + + monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + run = ScheduleRun(run_no="RUNR-5", status="running") + task = ScheduleTask(job_params={"receipt_from_offset_days": -1}) + _total, _success, _failed, _skipped, results, _warnings, errors = ( + job_mod.run_in_transit_transfer_schedule(task, run) + ) + # 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。 + assert results == [] + assert any("收料日期起点" in e for e in errors) + assert not (run.response_summary_json or {}).get("domain_notification_managed") + + task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5}) + _total, _success, _failed, _skipped, _results, _warnings, errors = ( + job_mod.run_in_transit_transfer_schedule(task, run) + ) + # 断言:小数偏移同样快速失败。 + assert any("收料日期终点" in e for e in errors) + + +def test_handler_run_day_uses_framework_notification(monkeypatch): + """有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + + def _fake_auto_transfer(**kwargs): + return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success") + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + task = ScheduleTask(job_params={}) run = ScheduleRun(run_no="RUNR-2", status="running") - job_mod.run_in_transit_transfer_schedule(task, run) + total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run) - assert captured["sender"] is None - assert captured["recipients"] == [] + # 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。 assert not (run.response_summary_json or {}).get("domain_notification_managed") + assert results and results[0]["run_no"] == "TR-1" + assert (total, success, failed, skipped) == (1, 1, 0, 0) + assert errors == [] def test_handler_hard_failure_keeps_framework_notification(monkeypatch): - """硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。""" + """硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。""" import app.services.schedule.in_transit_transfer_job as job_mod from app.models import ScheduleRun, ScheduleTask monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) - captured = {} def _fake_auto_transfer(**kwargs): - captured.update(kwargs) return job_mod.AutoTransferOutcome(errors=["match pipeline boom"]) monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) - class _FakeSenderInner: - pass - - monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner) - - task = ScheduleTask(job_params={"notify_user_ids": ["7"]}) + task = ScheduleTask(job_params={}) run = ScheduleRun(run_no="RUNR-3", status="running") - _total, _success, _failed, _skipped, _results, _warnings, errors = ( + _total, _success, _failed, _skipped, results, _warnings, errors = ( job_mod.run_in_transit_transfer_schedule(task, run) ) - # 断言:sender 已构造并透传;硬失败不抑制框架完成卡。 - assert isinstance(captured["sender"], _FakeSenderInner) - assert captured["recipients"] == ["7"] + # 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。 assert not (run.response_summary_json or {}).get("domain_notification_managed") + assert results == [] assert errors == ["match pipeline boom"] diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index 677f5e8a..db5b5f59 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -132,20 +132,68 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_ outcome = finalize_receipt_schedule_run_if_complete(run.id) - # [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。 + # [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。 assert outcome == {'finalized': True, 'status': 'success'} assert len(textcards) == 1 assert '原始收料包:已随本通知发送' in textcards[0][1] - assert len(media_uploads) == 1 - assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip') - assert file_sends == ['media-1'] + assert len(media_uploads) == 2 + assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx') + assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip') + assert file_sends == ['media-1', 'media-2'] assert run.wecom_notified is True assert run.response_summary_json.get('raw_receipt_zip_available') is True # [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。 outcome_again = finalize_receipt_schedule_run_if_complete(run.id) assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} - assert len(textcards) == 1 and len(file_sends) == 1 + assert len(textcards) == 1 and len(file_sends) == 2 + + +def test_receipt_finalize_generates_summary_excel(app, tmp_path): + """收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。""" + from io import BytesIO + + from openpyxl import load_workbook + + from app import db + from app.models import ( + ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, + ShippingReceiptRpaUnitRun, + ) + from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + + with app.app_context(): + app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel') + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + db.session.add(task); db.session.flush() + run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True}) + db.session.add(run); db.session.flush() + unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={}) + unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={}) + unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={}) + db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush() + db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64)) + db.session.commit() + + outcome = finalize_receipt_schedule_run_if_complete(run.id) + + # [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。 + assert outcome == {'finalized': True, 'status': 'partial_failed'} + assert run.excel_file_data + assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx') + assert run.response_summary_json['excel_export_status'] == 'ok' + assert run.response_summary_json['excel_failed'] is False + + # [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。 + workbook = load_workbook(BytesIO(run.excel_file_data)) + sheet = workbook.active + header = [cell.value for cell in sheet[1]] + assert header[:2] == ['收料源', '仓库'] + rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)} + assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success' + assert rows['DSV360_AWSCV'][4] == 'skipped' + assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout' def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch): diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 896501c0..51b38080 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -50,7 +50,7 @@ | --- | --- | --- | | POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) | | GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→数据源→Invoice→created_at,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 | -| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) | +| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`/`external_org`(执行建单五元组首键,2026-10-12 起),counts 实时聚合) | | POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——圈行口径=匹配 scope(与匹配卡实时视图同源谓词,行归属 matching_id 不参与;2026-09-24 修复:旧按 matching_id 圈行致历史行重查不可达);body 可选 `invoice_nos` 限定范围;库存查询按组织批量(2026-09-29:每组织一次 `query_stock`,N 行=N 组织内 1 次调用,行级评估/Attempt/审计保持单行粒度) | | POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) | | GET | `/runs/{run_no}` | Run 结果(`orders` 调拨单清单=进度=结果,逐单八键/行六键含 reason;+ 按 ERP 单号聚合 external_documents + 未落单异常 exceptions) | @@ -189,6 +189,7 @@ cd backend && flask db upgrade - 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。 - 本期功能验收项(2026-09-24 ERP 建单写路径,配置见 §10): - **五元组建单**:按五元组(external_org / source_code / 收料日期 / 拨出库位 / 拨入库位,全 .strip() 规范化)聚合明细建一张单,单号 `HX--OR-*`;同组失败单复用单号/时间戳全量重跑、result_unknown/executing 单阻断新行(group_ticket_unresolved)。 + - **预计 ERP 单据数口径(2026-10-12 修正)**:匹配摘要 `estimated_external_write_count` = 可执行行按同款五元组去重后的组数(同组多行合并一张,原「=可执行行数」口径高估);匹配卡上该数(计数卡=全部可执行行、生成按钮旁=勾选可执行行,随勾选联动)由前端按行上 `external_org` 实时分组计算,历史快照中旧口径持久值不再上屏。 - **融合卡**:`GET /runs/{run_no}` orders 逐单亮态(成功/失败/未知三态+ERP 单号回显),202 提交后 4s 轮询至严格终态;retrigger 受理窗口不误停轮询。 - **retrigger**:result_unknown 单复用 doc_no/submit_timestamp 只触发末步,ERP 幂等回原单号;非 result_unknown 400。 - **关闭单**:business_failed/technical_failed 人工关闭(原因必填),单 cancelled、行脱离回可执行、组锁释放可另开新单;result_unknown 无关闭入口(SOP 红线 §10.8)。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 22ed7a49..b307d7a1 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -3064,7 +3064,7 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 - 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 -- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 +- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **汇总结果 Excel** `收料RPA-{yyyyMMdd}-{HHmm}-结果.xlsx`(2026-10-12 对齐库存补齐;列头 收料源/仓库/连接器/归档文件数/导出状态/跳过原因/错误原因,`empty→skipped`、`cancelled→failed` 与卡片计数同口径,导出失败降级 success→partial_failed 并记 `excel_export_status/excel_failed`)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_receipt_rpa_worker_ready`:心跳 TTL + 收料 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。 diff --git a/docs/funclist.md b/docs/funclist.md index 5e3bb703..b0ab0fc5 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -799,7 +799,7 @@ | 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) | | 收料文件准备与只读匹配(原"预检") | 后端已实现 | 收料文件落地即同步待办行(RPA 回调桥 → evidence_sync 三分类写入:新行待查/证据变化刷新重置/缺席行存续只换戳);匹配=证据对齐兜底(align_scope_rows,sha 一致直通零解析)+ 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T+lag 成熟(默认 T+2)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 | | 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) | -| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | +| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;任务参数=来源实例/历史可恢复异常复核/可选收料日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,越界由匹配层卡控成熟上限);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) | | 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | | 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) | diff --git a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue index 34b6fa3d..3e03e89a 100644 --- a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue +++ b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue @@ -261,7 +261,7 @@ watch( type="date" :value="params[field.key] ?? ''" class="input-field w-full !text-sm !leading-5" - @input="setField(field.key, ($event.target as HTMLInputElement).value)" + @input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : ($event.target as HTMLInputElement).value)" />

{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }} diff --git a/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue b/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue index 76a059f9..26c192e7 100644 --- a/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue +++ b/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue @@ -1,12 +1,14 @@ diff --git a/frontend/src/locales/en/workspace.json b/frontend/src/locales/en/workspace.json index fa73bcff..6348c1e1 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -999,7 +999,7 @@ "syncSkipped": "A sync is already running; try again later", "syncFailedTitle": "Sync failed; last snapshot kept", "filterKeyword": "Keyword (order / product / customer / salesperson / replier)", - "filterKeywordPh": "Search by order no., part no., name, customer part no., customer, salesperson, or reply person", + "filterKeywordPh": "Order / product / customer / salesperson / reply person", "filterOrderDate": "Order Date", "filterStatus": "Reply Status", "statusAll": "All", @@ -1007,12 +1007,10 @@ "statusNotFully": "Not fully replied", "statusNotReplied": "Not replied", "statusPartial": "Partially replied", - "totalCount": "{count} product lines", "selectAll": "Select all (this page)", "selectedCount": "{count} lines selected", "batchReply": "+ Batch reply", "batchNotify": "Batch notify", - "toolbarHint": "Batch reply only saves; click \"Batch notify\" to send and lock.", "colOrderLine": "Order : Item", "colOrderDate": "Order Date", "colCustomer": "Customer", @@ -1024,6 +1022,7 @@ "colSpec": "Spec", "colCustomerPartNo": "Customer Part No.", "colAgreedDate": "Agreed Date", + "colNotifiedTime": "Notified at", "colUnit": "Unit", "colQty": "Qty", "colDelivered": "Delivered", @@ -1032,15 +1031,13 @@ "colReply": "Delivery Reply", "colNotify": "Notify", "colReplyPerson": "Replied By", - "batchCount": "{count} batches", - "repliedOf": "replied {replied}/{remain}", - "overTag": "OVER", "collapse": "Collapse ▲", + "exportDone": "Exported", + "exportExcel": "Export Excel", + "exportFailed": "Export failed", "expand": "+{count} more ▾", - "lockedTag": "Locked", "replyAction": "Reply", "editReplyAction": "Edit reply", - "notifiedTag": "Notified {name}", "replyFirst": "Reply first", "notifyAction": "Send notification", "pendingNotify": "Recorded after notify", diff --git a/frontend/src/locales/th/workspace.json b/frontend/src/locales/th/workspace.json index 2360cfc4..314764fd 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -921,7 +921,7 @@ "syncSkipped": "มีการซิงค์กำลังทำงานอยู่ โปรดลองอีกครั้งภายหลัง", "syncFailedTitle": "ซิงค์ล้มเหลว ยังคงภาพรวมเดิมไว้", "filterKeyword": "คำค้นหา (คำสั่งซื้อ / ผลิตภัณฑ์ / ลูกค้า / พนักงานขาย / ผู้ตอบกำหนดส่ง)", - "filterKeywordPh": "ค้นหาด้วยเลขที่คำสั่งซื้อ รหัสสินค้า ชื่อสินค้า รหัสสินค้าลูกค้า ลูกค้า พนักงานขาย หรือผู้ตอบกำหนดส่งได้", + "filterKeywordPh": "คำสั่งซื้อ / สินค้า / ลูกค้า / พนักงานขาย / ผู้ตอบกำหนดส่ง", "filterOrderDate": "วันที่สั่งซื้อ", "filterStatus": "สถานะการตอบกลับ", "statusAll": "ทั้งหมด", @@ -929,12 +929,10 @@ "statusNotFully": "ยังตอบไม่ครบ", "statusNotReplied": "ยังไม่ตอบกลับ", "statusPartial": "ตอบบางส่วน", - "totalCount": "รวม {count} รายการสินค้า", "selectAll": "เลือกทั้งหมด (หน้านี้)", "selectedCount": "เลือกแล้ว {count} รายการ", "batchReply": "+ ตอบกลับหลายรายการ", "batchNotify": "แจ้งเตือนหลายรายการ", - "toolbarHint": "การตอบกลับหลายรายการเป็นเพียงบันทึก ต้องกดแจ้งเตือนจึงจะส่งและล็อก", "colOrderLine": "เลขที่ : รายการ", "colOrderDate": "วันที่สั่งซื้อ", "colCustomer": "ลูกค้า", @@ -946,6 +944,7 @@ "colSpec": "สเปก", "colCustomerPartNo": "รหัสสินค้าลูกค้า", "colAgreedDate": "กำหนดส่งตามข้อตกลง", + "colNotifiedTime": "เวลาแจ้งเตือน", "colUnit": "หน่วย", "colQty": "จำนวน", "colDelivered": "ส่งแล้ว", @@ -954,15 +953,13 @@ "colReply": "การตอบกลับกำหนดส่ง", "colNotify": "แจ้งเตือน", "colReplyPerson": "ผู้ตอบกลับ", - "batchCount": "{count} งวด", - "repliedOf": "ตอบแล้ว {replied}/{remain}", - "overTag": "เกิน", "collapse": "ย่อ ▲", + "exportDone": "ส่งออกสำเร็จ", + "exportExcel": "ส่งออก Excel", + "exportFailed": "ส่งออกล้มเหลว", "expand": "+{count} งวด ▾", - "lockedTag": "ล็อกแล้ว", "replyAction": "ตอบกลับ", "editReplyAction": "แก้ไขการตอบกลับ", - "notifiedTag": "แจ้งแล้ว {name}", "replyFirst": "กรุณาตอบกลับก่อน", "notifyAction": "ส่งการแจ้งเตือน", "pendingNotify": "บันทึกหลังแจ้งเตือน", diff --git a/frontend/src/locales/zh-CN/workspace.json b/frontend/src/locales/zh-CN/workspace.json index 12a80c3d..b5ea5f1b 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -999,7 +999,7 @@ "syncSkipped": "已有同步正在进行,请稍后再试", "syncFailedTitle": "同步失败,已保留上次快照", "filterKeyword": "关键词(订单 / 产品 / 客户 / 业务员 / 回复人员)", - "filterKeywordPh": "订单单号、产品编号、品名、客户料号、客户编号、业务员、交期回复人员均可搜索", + "filterKeywordPh": "订单/产品/客户/业务员/回复人员", "filterOrderDate": "订单日期", "filterStatus": "交期回复状态", "statusAll": "全部", @@ -1007,12 +1007,10 @@ "statusNotFully": "未完全回复", "statusNotReplied": "未回复", "statusPartial": "部分回复", - "totalCount": "共 {count} 条产品行", "selectAll": "全选(本页)", "selectedCount": "已勾选 {count} 行", "batchReply": "+ 联合回复交期", "batchNotify": "批量通知", - "toolbarHint": "联合回复只保存批次;点「批量通知」才发送并锁定。", "colOrderLine": "订单单号:项次", "colOrderDate": "订单日期", "colCustomer": "客户编号", @@ -1024,6 +1022,7 @@ "colSpec": "规格", "colCustomerPartNo": "客户产品编号", "colAgreedDate": "约定交货日", + "colNotifiedTime": "通知时间", "colUnit": "单位", "colQty": "数量", "colDelivered": "已交数量", @@ -1032,15 +1031,13 @@ "colReply": "交期回复", "colNotify": "通知业务部门", "colReplyPerson": "交期回复人员", - "batchCount": "{count} 批", - "repliedOf": "已回复 {replied}/{remain}", - "overTag": "超", "collapse": "收起 ▲", + "exportDone": "导出成功", + "exportExcel": "导出 Excel", + "exportFailed": "导出失败", "expand": "+{count} 批 ▾", - "lockedTag": "交期已锁定", "replyAction": "回复交期", "editReplyAction": "修改回复", - "notifiedTag": "已通知 {name}", "replyFirst": "请先回复交期", "notifyAction": "发送通知业务部门", "pendingNotify": "待通知后记录", diff --git a/frontend/src/locales/zh-TW/workspace.json b/frontend/src/locales/zh-TW/workspace.json index 0e0ac5b5..810a2b40 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -999,7 +999,7 @@ "syncSkipped": "已有同步正在進行,請稍後再試", "syncFailedTitle": "同步失敗,已保留上次快照", "filterKeyword": "關鍵詞(訂單 / 產品 / 客戶 / 業務員 / 回覆人員)", - "filterKeywordPh": "訂單單號、產品編號、品名、客戶料號、客戶編號、業務員、交期回覆人員均可搜尋", + "filterKeywordPh": "訂單/產品/客戶/業務員/回覆人員", "filterOrderDate": "訂單日期", "filterStatus": "交期回覆狀態", "statusAll": "全部", @@ -1007,12 +1007,10 @@ "statusNotFully": "未完全回覆", "statusNotReplied": "未回覆", "statusPartial": "部分回覆", - "totalCount": "共 {count} 條產品行", "selectAll": "全選(本頁)", "selectedCount": "已勾選 {count} 行", "batchReply": "+ 聯合回覆交期", "batchNotify": "批量通知", - "toolbarHint": "聯合回覆只儲存批次;點「批量通知」才發送並鎖定。", "colOrderLine": "訂單單號:項次", "colOrderDate": "訂單日期", "colCustomer": "客戶編號", @@ -1024,6 +1022,7 @@ "colSpec": "規格", "colCustomerPartNo": "客戶產品編號", "colAgreedDate": "約定交貨日", + "colNotifiedTime": "通知時間", "colUnit": "單位", "colQty": "數量", "colDelivered": "已交數量", @@ -1032,15 +1031,13 @@ "colReply": "交期回覆", "colNotify": "通知業務部門", "colReplyPerson": "交期回覆人員", - "batchCount": "{count} 批", - "repliedOf": "已回覆 {replied}/{remain}", - "overTag": "超", "collapse": "收起 ▲", + "exportDone": "匯出成功", + "exportExcel": "匯出 Excel", + "exportFailed": "匯出失敗", "expand": "+{count} 批 ▾", - "lockedTag": "交期已鎖定", "replyAction": "回覆交期", "editReplyAction": "修改回覆", - "notifiedTag": "已通知 {name}", "replyFirst": "請先回覆交期", "notifyAction": "發送通知業務部門", "pendingNotify": "待通知後記錄", diff --git a/frontend/src/shared/composables/useTheme.ts b/frontend/src/shared/composables/useTheme.ts index aa99a92f..be5ec836 100644 --- a/frontend/src/shared/composables/useTheme.ts +++ b/frontend/src/shared/composables/useTheme.ts @@ -1,6 +1,9 @@ /** * shared/composables/useTheme.ts - * 主题 preference 与 dark/light 切换(全局单例)。 + * 用途:主题 preference 与 dark/light 切换(单文档内全局单例)。 + * 逻辑:initTheme 读 localStorage + matchMedia 完成本文档初始化;同时监听 storage 事件做跨文档同步—— + * storage 事件只在「其他同源文档」触发,聊天壳父页面切换主题时,iframe 内嵌工作台页 + * (如订单交期回复 /apps/order-delivery-reply)无需刷新即可实时跟随变暗/变亮。 */ import { computed, ref } from 'vue'; @@ -15,6 +18,7 @@ const systemPrefersDark = ref(false); let initialized = false; let mediaListenerCleanup: (() => void) | null = null; +let storageListenerCleanup: (() => void) | null = null; const appliedTheme = computed(() => { if (themePreference.value === 'system') { @@ -68,6 +72,19 @@ const initTheme = () => { media.addEventListener('change', onMediaChange); mediaListenerCleanup = () => media.removeEventListener('change', onMediaChange); + // 跨文档主题同步:本监听只在「被其他文档修改 localStorage」时触发(自身切换走 setThemePreference), + // 使 iframe 等同源文档即时跟随父壳的亮暗切换。 + const onStorageChange = (event: StorageEvent) => { + if (event.key !== THEME_KEY) return; + const stored = parseTheme(event.newValue); + if (stored) { + themePreference.value = stored; + applyTheme(); + } + }; + window.addEventListener('storage', onStorageChange); + storageListenerCleanup = () => window.removeEventListener('storage', onStorageChange); + const stored = parseTheme(localStorage.getItem(THEME_KEY)); if (stored) { themePreference.value = stored; @@ -78,6 +95,8 @@ const initTheme = () => { const cleanupTheme = () => { mediaListenerCleanup?.(); mediaListenerCleanup = null; + storageListenerCleanup?.(); + storageListenerCleanup = null; initialized = false; }; diff --git a/frontend/src/shared/styles/utilities.css b/frontend/src/shared/styles/utilities.css index 1ee8553f..73a2cbbb 100644 --- a/frontend/src/shared/styles/utilities.css +++ b/frontend/src/shared/styles/utilities.css @@ -28,4 +28,38 @@ .divide-subtle > :not([hidden]) ~ :not([hidden]) { border-color: var(--border-subtle); } + + /* 状态前景文字:badge 之外的行内强调(如「超量」标记、成功/告警说明) */ + .text-status-success { color: var(--status-success-fg); } + .text-status-info { color: var(--status-info-fg); } + .text-status-warning { color: var(--status-warning-fg); } + .text-status-error { color: var(--status-error-fg); } + + /* 表格行交互态:选中=info、直达定位高亮=warning,状态令牌亮暗自适应 */ + .bg-row-selected { background-color: var(--status-info-bg); } + .bg-row-highlight { background-color: var(--status-warning-bg); } + + /* 表格行悬停:无交互态的行悬停压暗;选中/高亮行保持状态色不被悬停覆盖 */ + .hover-row:hover:not(.bg-row-selected):not(.bg-row-highlight) { + background-color: var(--bg-surface-soft); + } + + /* 表格冻结列单元格:必须实色基底(防透出横向滚动内容)。 + 选中/高亮态用「实色底 + 状态色平铺叠加」——暗色状态令牌为半透明 rgba, + 直接当背景色会在横向滚动时透出下层内容。 */ + .frozen-cell { background-color: var(--bg-surface); } + .hover-row:hover:not(.bg-row-selected):not(.bg-row-highlight) .frozen-cell { + background-color: var(--bg-surface-soft); + } + .frozen-cell--selected { + background-color: var(--bg-surface); + background-image: linear-gradient(var(--status-info-bg), var(--status-info-bg)); + } + .frozen-cell--highlight { + background-color: var(--bg-surface); + background-image: linear-gradient(var(--status-warning-bg), var(--status-warning-bg)); + } + + /* 冻结列右缘分隔阴影(与 admin-table-sticky-right-cell 同型),亮暗共用 */ + .shadow-sticky-col { box-shadow: 2px 0 6px -2px rgba(15, 23, 42, 0.12); } } diff --git a/frontend/src/style.css b/frontend/src/style.css index a196bc16..55b8b792 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -189,6 +189,31 @@ @apply px-2.5 py-0.5 rounded-full text-xs font-medium border; } + /* 徽章状态变体:颜色一律走 --status-* 令牌(亮暗自适应),禁止 rose/emerald 等原生色 */ + .badge-success { + background-color: var(--status-success-bg); + border-color: var(--status-success-border); + color: var(--status-success-fg); + } + + .badge-info { + background-color: var(--status-info-bg); + border-color: var(--status-info-border); + color: var(--status-info-fg); + } + + .badge-warning { + background-color: var(--status-warning-bg); + border-color: var(--status-warning-border); + color: var(--status-warning-fg); + } + + .badge-error { + background-color: var(--status-error-bg); + border-color: var(--status-error-border); + color: var(--status-error-fg); + } + .glass-panel { @apply backdrop-blur-xl border; background: var(--glass-panel-bg); From 28b4a428efd5478c25d0ce4177f40116866a09dc Mon Sep 17 00:00:00 2001 From: "HTEWJ\\26070045" <2815434552@qq.com> Date: Tue, 13 Oct 2026 10:31:42 +0800 Subject: [PATCH 13/32] =?UTF-8?q?fix(order-delivery-reply):=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9excel=E5=AF=BC=E5=87=BA=E5=90=8E=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E6=97=B6=E9=97=B4=E6=98=BE=E7=A4=BA=E4=B8=BA?= =?UTF-8?q?=E5=8C=97=E4=BA=AC=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../order-delivery-reply/api/orderDeliveryReply.api.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts index 47e634fb..298ce2ad 100644 --- a/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts +++ b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts @@ -175,7 +175,10 @@ export async function exportOrderDeliveryLines(params: OrderDeliveryExportParams const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; - link.download = `订单交期回复_${new Date().toISOString().slice(0, 10)}.xlsx`; + // 文件名日期取浏览器本地时区(toISOString 为 UTC,北京时间 0-8 点导出会差一天) + const now = new Date(); + const localDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; + link.download = `订单交期回复_${localDate}.xlsx`; document.body.appendChild(link); link.click(); link.remove(); From 7e7bcbd3888659ac44663d53fa38ca0c18342c3f Mon Sep 17 00:00:00 2001 From: sophie Date: Tue, 13 Oct 2026 11:55:38 +0800 Subject: [PATCH 14/32] =?UTF-8?q?fix:=20=E8=A7=A3=E5=86=B3merge=20conflict?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../api/equipment-acceptance.api.ts | 6 ++- .../api/orderDeliveryReply.api.spec.ts | 47 +++++++++++++++++++ .../api/orderDeliveryReply.api.ts | 37 ++++++++++----- .../views/OrderDeliveryReplyPage.vue | 3 +- frontend/src/shared/api/client.ts | 5 -- 5 files changed, 78 insertions(+), 20 deletions(-) create mode 100644 frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts diff --git a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts index 41ad0442..f1c2006c 100644 --- a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts +++ b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts @@ -3,6 +3,7 @@ * 用途:设备验收预警同步列表、详情和手动同步。 * 依赖:统一 requestJson;后端 /api/equipment-acceptance。 * 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。 + * 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。 * 发送记录只读已落库的行,扫描尚未写入时列表为空。 */ import { requestJson } from '@/shared/api/client'; @@ -206,8 +207,8 @@ export function getEquipmentAcceptanceConfig() { * @param payload.days - 四个逐档增大的天数 * @param payload.buyerManagerUserId - 采购经副理 * @param payload.cooUserId - COO - * @param payload.executiveUserId - 廖总对应岗位 - * @returns 保存后的配置 + * @param payload.executiveUserId - 总经理对应岗位 + * @returns 保存后的配置。请求头带 application/json,避免 Flask 把正文当成空对象。 */ export function saveEquipmentAcceptanceConfig(payload: { days: number[]; @@ -217,6 +218,7 @@ export function saveEquipmentAcceptanceConfig(payload: { }) { return requestJson('/api/equipment-acceptance/config', { method: 'PUT', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days: payload.days, buyer_manager_user_id: payload.buyerManagerUserId, diff --git a/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts new file mode 100644 index 00000000..a9dbe6a0 --- /dev/null +++ b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts @@ -0,0 +1,47 @@ +/** + * features/order-delivery-reply/api/orderDeliveryReply.api.spec.ts + * 用途:锁定交期回复 JSON 写请求自行声明 Content-Type。 + * 依赖:vitest、orderDeliveryReply.api。 + * 逻辑:requestJson 不再为所有 body 补 application/json;漏掉该头时 Flask get_json 会把保存当成空正文。 + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const requestJson = vi.hoisted(() => vi.fn()); + +vi.mock('@/shared/api/client', () => ({ + requestJson, +})); + +import { + batchReplyOrderDelivery, + notifyOrderDeliveryBatch, + saveOrderDeliveryBatches, +} from './orderDeliveryReply.api'; + +describe('order delivery reply JSON writes', () => { + beforeEach(() => { + requestJson.mockReset(); + requestJson.mockResolvedValue({}); + }); + + it('sends Content-Type application/json when saving one line', async () => { + await saveOrderDeliveryBatches('SO-1', 2, [{ planned_date: '2026-10-13', qty: '1' }]); + + const init = requestJson.mock.calls[0][1] as RequestInit; + // 断言:保存请求自己带 JSON 类型,不依赖公共客户端补头。 + expect((init.headers as Record)['Content-Type']).toBe('application/json'); + expect(init.method).toBe('PUT'); + expect(init.body).toBe(JSON.stringify({ batches: [{ planned_date: '2026-10-13', qty: '1' }] })); + }); + + it('sends Content-Type application/json for batch reply and batch notify', async () => { + await batchReplyOrderDelivery([]); + await notifyOrderDeliveryBatch([]); + + for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) { + // 断言:联合回复与批量通知同样声明 JSON 类型。 + expect((init.headers as Record)['Content-Type']).toBe('application/json'); + expect(init.method).toBe('POST'); + } + }); +}); diff --git a/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts index 41d3b7d9..53774ac1 100644 --- a/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts +++ b/frontend/src/features/order-delivery-reply/api/orderDeliveryReply.api.ts @@ -2,10 +2,26 @@ * 订单交期回复 API 类型与请求封装。 * 依赖:统一 requestJson(失败抛 BusinessError);后端 /api/order-delivery-reply。 * 逻辑:列表筛选分页、保存批次(单行/联合)、单行与批量通知、手动同步与最近同步状态。 + * 带 JSON 正文的写请求在本文件声明 Content-Type: application/json,供 Flask get_json 解析。 */ import { requestJson } from '@/shared/api/client'; +/** + * 组装带 JSON 正文的写请求。 + * 核心逻辑:显式声明 application/json。浏览器对字符串正文默认是 text/plain,Flask get_json 会读成空对象。 + * @param method - HTTP 方法 + * @param payload - 将序列化为 JSON 的请求体 + * @returns fetch 的 method、headers 与 body + */ +function jsonWrite(method: 'POST' | 'PUT', payload: unknown): RequestInit { + return { + method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }; +} + /** 已保存的交期批次(计划交期 + 数量 + 可选备注)。 */ export interface DeliveryBatch { seq?: number; @@ -100,7 +116,7 @@ export const listOrderDeliveryLines = (params?: OrderDeliveryListParams) => { return requestJson(`/api/order-delivery-reply/lines${suffix}`); }; -/** 保存单行交期批次(未锁定行整表替换)。 */ +/** 保存单行交期批次(未锁定行整表替换)。请求头带 application/json,避免正文被 Flask 当成空对象。 */ export const saveOrderDeliveryBatches = ( orderNo: string, lineNo: number, @@ -108,17 +124,14 @@ export const saveOrderDeliveryBatches = ( ) => requestJson<{ order_no: string; line_no: number; batches: DeliveryBatch[]; total_qty: string }>( `/api/order-delivery-reply/lines/${encodeURIComponent(orderNo)}/${lineNo}/batches`, - { method: 'PUT', body: JSON.stringify({ batches }) }, + jsonWrite('PUT', { batches }), ); -/** 联合回复:对多行逐行保存批次(只保存,不通知不锁定)。 */ +/** 联合回复:对多行逐行保存批次(只保存,不通知不锁定)。请求头带 application/json。 */ export const batchReplyOrderDelivery = ( items: { order_no: string; line_no: number; batches: { planned_date: string; qty: string | number; remark?: string | null }[] }[], ) => - requestJson('/api/order-delivery-reply/batch-reply', { - method: 'POST', - body: JSON.stringify({ items }), - }); + requestJson('/api/order-delivery-reply/batch-reply', jsonWrite('POST', { items })); /** 单行发送通知业务部门(企微),成功后行级锁定。 */ export const notifyOrderDeliveryLine = (orderNo: string, lineNo: number) => @@ -127,12 +140,12 @@ export const notifyOrderDeliveryLine = (orderNo: string, lineNo: number) => { method: 'POST' }, ); -/** 批量通知勾选行;无批次/已锁定跳过,单行失败不回滚其它行。 */ +/** 批量通知勾选行;无批次/已锁定跳过,单行失败不回滚其它行。请求头带 application/json。 */ export const notifyOrderDeliveryBatch = (lines: { order_no: string; line_no: number }[]) => - requestJson('/api/order-delivery-reply/notify-batch', { - method: 'POST', - body: JSON.stringify({ lines }), - }); + requestJson( + '/api/order-delivery-reply/notify-batch', + jsonWrite('POST', { lines }), + ); /** 手动触发 ERP 全量同步(范围与 07:00 排程一致)。 */ export const runOrderDeliverySync = () => diff --git a/frontend/src/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue b/frontend/src/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue index 81a5fd40..dadb92e8 100644 --- a/frontend/src/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue +++ b/frontend/src/features/order-delivery-reply/views/OrderDeliveryReplyPage.vue @@ -395,11 +395,12 @@ async function focusTargetLine(orderNo: string, lineNo: number) { highlightTimer = setTimeout(clearHighlight, 8000); } -/** 上报企微卡片打开回执(WecomNotifyAudit.opened_at);仅留痕,失败不影响页面使用。 */ +/** 上报企微卡片打开回执(WecomNotifyAudit.opened_at);仅留痕,失败不影响页面使用。请求头带 application/json,后端 get_json 才读得到 trace_id。 */ async function reportWecomTraceOpened(traceId: string) { try { await requestJson('/api/user/wecom/deeplink-opened', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ trace_id: traceId }), }); } catch { diff --git a/frontend/src/shared/api/client.ts b/frontend/src/shared/api/client.ts index 40c0b03e..3127d5a8 100644 --- a/frontend/src/shared/api/client.ts +++ b/frontend/src/shared/api/client.ts @@ -168,11 +168,6 @@ export async function requestJson(url: string, init?: RequestInit): Promise headers.set(k, v as string)); - // 带 body 的请求若未显式声明类型,统一补 JSON 头:否则 Flask get_json(silent=True) - // 会因 Content-Type 非 JSON 解析出 None,把有效载荷当空 body 处理(如订单交期回复保存被误判 400)。 - if (init?.body && !headers.has('Content-Type')) { - headers.set('Content-Type', 'application/json'); - } const res = await fetchJsonResponse(url, { ...init, headers }); let data: any = null; From ea94fb28db285f20d2e226184f24bb63ba729798 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 13 Oct 2026 15:04:40 +0800 Subject: [PATCH 15/32] =?UTF-8?q?feat(shipping-notice):=20=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E9=87=8D=E5=8F=96=E5=BA=93=E5=AD=98=E5=89=8D=E7=BD=AE?= =?UTF-8?q?=E5=80=99=E9=80=89=E5=88=B7=E6=96=B0=E5=B9=B6=E6=94=BE=E5=BC=80?= =?UTF-8?q?=E8=A1=8C=E7=BA=A7=E5=BA=93=E5=AD=98=E6=BA=90=E4=B8=8B=E6=8B=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划 --- backend/app/api/workspace/shipping_notice.py | 117 +- .../chat_action_extended_handlers.py | 2 +- .../shipping_notice/export_archive.py | 28 +- .../inventory_candidate_freeze_service.py | 249 ++++ .../inventory_candidate_projection.py | 32 +- .../shipping_notice/inventory_source_gate.py | 15 +- .../line_inventory_match_persistence.py | 48 +- .../shipping_notice/process_gate_executor.py | 36 + .../services/shipping_notice/query_service.py | 45 +- .../app/services/shipping_notice/ui_state.py | 23 +- .../test_inventory_source_gate_notice_task.py | 121 ++ .../test_line_inventory_match_persistence.py | 88 ++ ...st_shipping_line_scoped_inventory_retry.py | 6 + .../test_shipping_notice_export_archive.py | 41 + .../test_shipping_notice_query_service.py | 22 + .../tests/test_shipping_notice_ui_state.py | 33 + .../test_shipping_process_recovery_plan.py | 6 + ...t_shipping_refresh_inventory_candidates.py | 504 ++++++++ docs/features/shipping-notice/technical.md | 35 +- docs/funclist.md | 1 + ...3-shipping-inventory-candidates-refresh.md | 1077 +++++++++++++++++ .../shipping-review/useShippingOrderReview.ts | 42 +- .../chat/shipping/inlineSourceOptions.test.ts | 43 + .../chat/shipping/inlineSourceOptions.ts | 50 + .../features/chat/types/shipping.api.types.ts | 2 + .../chat/views/ShippingOrderReviewView.vue | 53 +- ...hippingTaskCenterPage.notice-batch.spec.ts | 2 + .../ShippingTaskCenterPage.vue | 8 +- .../ShippingTaskDrawer.vue | 5 +- .../ShippingTaskTable.vue | 7 +- .../shippingTaskCenterShared.ts | 9 + frontend/src/locales/en/chat.json | 2 +- frontend/src/locales/th/chat.json | 2 +- frontend/src/locales/zh-CN/chat.json | 2 +- frontend/src/locales/zh-TW/chat.json | 2 +- 35 files changed, 2675 insertions(+), 83 deletions(-) create mode 100644 backend/tests/test_inventory_source_gate_notice_task.py create mode 100644 backend/tests/test_shipping_notice_export_archive.py create mode 100644 backend/tests/test_shipping_refresh_inventory_candidates.py create mode 100644 docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md create mode 100644 frontend/src/features/chat/shipping/inlineSourceOptions.test.ts create mode 100644 frontend/src/features/chat/shipping/inlineSourceOptions.ts diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 8252face..fa662e01 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -186,6 +186,7 @@ def workspace_shipping_tasks(): lifecycle_status=lifecycle_status, page=page, page_size=page_size, + is_admin=bool(user.is_platform_admin()), )) @@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks(): @workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) def workspace_shipping_export_archive(): - """按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" + """按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。""" user = _require_user() data = request.get_json(silent=True) or {} task_nos = data.get('task_nos') if task_nos is not None and not isinstance(task_nos, list): raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') from app.services.shipping_notice.export_archive import build_export_archive - stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or []) + from app.services.shipping_notice.fulfillment_audit import record_access_audit + + stream, filename, manifest = build_export_archive( + user_id=user.id, + task_nos=task_nos or [], + is_admin=bool(user.is_platform_admin()), + ) + # 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。 + for entry in manifest.get('entries') or []: + aggregate_no = str(entry.get('business_no') or '').strip() + task_no = str(entry.get('task_no') or '').strip() + if not aggregate_no and not task_no: + continue + record_access_audit( + action='download_task_excel', + aggregate_type='shipping_task', + aggregate_id=task_no or aggregate_no, + actor_id=user.id, + task_no=task_no or None, + reason_code='excel_downloaded', + metadata={ + 'export': 'batch_zip', + 'batch_status': str(entry.get('status') or ''), + }, + ) response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response.call_on_close(stream.close) return response @@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str): details={'field': 'customer_id'}, ) from exc updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id) - return _ok(serialize_task_detail(updated)) + return _ok(serialize_task_detail( + updated, + viewer_user_id=user.id, + is_admin=bool(user.is_platform_admin()), + )) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice(): db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator orchestrator_started = start_task_orchestrator(task_id) - return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) + return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) @workspace_shipping_notice_bp.route('/shipping-tasks//replace-notice', methods=['POST']) def workspace_replace_shipping_task_notice(task_no: str): @@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') - return _ok(build_task_ui_state(task, include_stage_context=True)) + return _ok(build_task_ui_state( + task, + include_stage_context=True, + viewer_user_id=user.id, + viewer_is_admin=bool(user.is_platform_admin()), + )) @workspace_shipping_notice_bp.route('/shipping-tasks//chat-actions', methods=['GET']) def workspace_shipping_task_chat_actions(task_no: str): @@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin return task +def _load_business_notice_readable_for_user( + *, + business_no: str, + user_id: int, + is_admin: bool, +) -> ShippingNotice: + """ + 按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。 + + 核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径 + (可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式 + Notice,且每次下载均由端点写入 record_access_audit。 + + Args: + business_no: 对外发货通知单号。 + user_id: 当前服务端会话用户主键。 + is_admin: 是否平台管理员。 + + Returns: + 可下载的 ShippingNotice。 + + Raises: + NotFoundError: 编号不存在、非正式 Notice 或用户不可见。 + """ + normalized = str(business_no or '').strip().upper() + from app.services.shipping_notice.query_service import get_task_visible_to_user + task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin) + if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized: + raise NotFoundError('Shipping notice not found') + return task + + def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: """按 business_no 发起单张通知的货代 RPA 上传或重试。""" task = _load_business_notice_for_user(business_no=business_no, user_id=user_id) @@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload(): @workspace_shipping_notice_bp.route('/shipping-notices//export', methods=['GET']) def workspace_shipping_notice_export(business_no: str): - """按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。""" + """按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。""" user = _require_user() - task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id)) + task = _load_business_notice_readable_for_user( + business_no=business_no, + user_id=int(user.id), + is_admin=bool(user.is_platform_admin()), + ) err_msg = task_export_error_message(task) if err_msg: raise NotFoundError(err_msg) @@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str): @workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST']) def workspace_shipping_notice_export_archive(): - """按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。""" + """按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。""" user = _require_user() data = request.get_json(silent=True) or {} raw_values = data.get('business_nos') @@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive(): if not business_nos or len(business_nos) > 100: raise ValidationError('business_nos must contain 1 to 100 business numbers') from app.services.shipping_notice.export_archive import build_export_archive + from app.services.shipping_notice.fulfillment_audit import record_access_audit - stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos) + stream, filename, manifest = build_export_archive( + user_id=int(user.id), + business_nos=business_nos, + is_admin=bool(user.is_platform_admin()), + ) + # 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交), + # manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。 + for entry in manifest.get('entries') or []: + aggregate_no = str(entry.get('business_no') or '').strip() + task_no = str(entry.get('task_no') or '').strip() + if not aggregate_no and not task_no: + continue + record_access_audit( + action='download_notice_excel', + aggregate_type='shipping_notice', + aggregate_id=aggregate_no or task_no, + actor_id=user.id, + task_no=task_no or None, + reason_code='excel_downloaded', + metadata={ + 'export': 'batch_zip', + 'batch_status': str(entry.get('status') or ''), + }, + ) response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response.call_on_close(stream.close) return response @@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive(): @workspace_shipping_notice_bp.route('/shipping-tasks//export', methods=['GET']) def workspace_shipping_task_export(task_no: str): - """下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" + """下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。""" user = _require_user() - task = get_task_for_user(task_no, user.id) + from app.services.shipping_notice.query_service import get_task_visible_to_user + task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin())) task = _require_formal_notice(task) err_msg = task_export_error_message(task) if err_msg: diff --git a/backend/app/services/shipping_notice/chat_action_extended_handlers.py b/backend/app/services/shipping_notice/chat_action_extended_handlers.py index 82f08c51..3e6066ac 100644 --- a/backend/app/services/shipping_notice/chat_action_extended_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_extended_handlers.py @@ -169,7 +169,7 @@ class ShippingQueryShortageDetailsAction: def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: task = _require_task(ctx) yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."}) - detail = serialize_task_detail(task) + detail = serialize_task_detail(task, viewer_user_id=int(ctx.user_id)) content = format_shortage_details_message(detail if isinstance(detail, dict) else {}) yield from stream_text_events(content, payload={"task_no": task.task_no}) yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"}) diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index f44c6d5d..48e83d0c 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -18,7 +18,10 @@ from zipfile import ZIP_DEFLATED, ZipFile from app.core.errors import NotFoundError, ValidationError from app.models import ShippingExportArtifact, ShippingNotice -from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download +from app.services.shipping_notice.query_service import ( + get_task_visible_to_user, + resolve_task_export_download, +) MAX_ARCHIVE_TASKS = 100 @@ -28,15 +31,17 @@ def _select_tasks( user_id: int, task_refs: list[str] | None, selection_name: str, + is_admin: bool = False, require_business_no: bool = False, ) -> tuple[list[ShippingNotice], str]: - """按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。""" + """按显式 task_no 或 business_no 选择当前用户可下载通知,禁止部分越权成功。""" normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip())) if not normalized_tasks: raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') tasks = [] for task_no in normalized_tasks: - task = get_task_for_user(task_no, user_id) + # 下载授权与单票导出同一谓词:创建者或管理员(可下载=可见)。 + task = get_task_visible_to_user(task_no, user_id, is_admin=is_admin) # 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。 if not isinstance(task, ShippingNotice) or ( require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper() @@ -90,10 +95,17 @@ def build_export_archive( user_id: int, task_nos: list[str] | None = None, business_nos: list[str] | None = None, + is_admin: bool = False, ) -> tuple[BinaryIO, str, dict]: """ 生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。 + Args: + user_id: 当前下载用户;与 ``is_admin`` 共同构成下载授权谓词口径。 + task_nos: 按 SN 技术号选择(与 business_nos 二选一)。 + business_nos: 按发货通知单号选择(与 task_nos 二选一)。 + is_admin: 是否平台管理员;管理员可打包其可见的正式 Notice。 + Returns: (定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。 """ @@ -105,6 +117,7 @@ def build_export_archive( user_id=user_id, task_refs=selection_values, selection_name=selection_name, + is_admin=is_admin, require_business_no=business_nos is not None, ) artifacts = _ready_artifacts(tasks) @@ -115,11 +128,16 @@ def build_export_archive( included = 0 with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive: for task in tasks: + # business_no 供端点按票写入访问审计(与单票下载同一 aggregate 口径)。 + entry_base = { + 'task_no': task.task_no, + 'business_no': str(getattr(task, 'business_no', '') or ''), + } task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else [] if not task_artifacts: - entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None}) + entries.append({**entry_base, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None}) for artifact in task_artifacts: - entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None} + entry = {**entry_base, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None} entry['artifact_no'] = artifact.artifact_no path = Path(artifact.file_path) if not path.is_file(): diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py index acdf8873..ecfd5780 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py @@ -716,6 +716,255 @@ def freeze_manual_line_source_selection( return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections) +def active_candidate_set_is_manually_pinned( + task: ShippingNotice, + *, + session: Session | None = None, +) -> bool: + """ + 判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。 + + Args: + task: 当前 ShippingOrderTask。 + session: 可选 Session。 + + Returns: + bool: True 表示人工已裁决候选源,自动重路由必须跳过。 + """ + sess = session or db.session + active_set = ( + sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + if getattr(task, 'active_inventory_candidate_set_id', None) is not None + else None + ) + if active_set is None: + return False + if getattr(active_set, 'frozen_by_id', None) is not None: + return True + return any( + str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override' + for source in (active_set.sources or []) + ) + + +def refresh_candidates_from_current_routing( + task: ShippingNotice, + *, + execution_id: int | None = None, + session: Session | None = None, +) -> bool: + """ + 任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。 + 【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用; + 禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。 + + 核心逻辑: + [守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单 + 不得自动改源,换源走 override_line_inventory_source 行级覆写。 + [守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override') + 时跳过:人工指定即定论,禁止重路由洗掉人工裁决。 + [STEP 1] 记录当前活动 set_id。 + [STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结 + (freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时 + apply 不落任何事实,活动集保持不变,同样视为无变化)。 + [STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs: + 匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。 + + Args: + task: 当前 ShippingOrderTask(须已冻结候选集)。 + execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。 + session: 可选 Session。 + + Returns: + bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 + """ + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + sess = session or db.session + if len(task_frozen_inventory_source_codes(task)) <= 1: + return False + if active_candidate_set_is_manually_pinned(task, session=sess): + return False + before = get_active_candidate_set(task) + before_set_id = int(before.id) if before is not None else None + adjudicate_and_apply_inventory_source(task, execution_id=execution_id) + sess.flush() + after = get_active_candidate_set(task) + after_set_id = int(after.id) if after is not None else None + if before_set_id == after_set_id: + return False + from app.services.shipping_notice.tool_common import log_task_event + + log_task_event( + task, + 'inventory_candidates_refreshed', + { + 'scope': 'task', + 'previous_set_id': before_set_id, + 'new_set_id': after_set_id, + 'source_codes': task_frozen_inventory_source_codes(task), + }, + source='system', + ) + return True + + +def refresh_line_candidates_from_current_routing( + task: ShippingNotice, + *, + line_no: int, + execution_id: int | None = None, + session: Session | None = None, +) -> bool: + """ + 行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。 + 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带 + line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。 + + 核心逻辑: + [守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。 + [守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。 + [STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False), + evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经 + get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义); + 仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。 + [STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承 + (保留既有行候选,不做整单重路由)。 + [STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版 + 候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。 + + Args: + task: 当前 ShippingOrderTask(须已冻结候选集)。 + line_no: 目标订单项次(1 基,对应冻结快照 line_no)。 + execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。 + session: 可选 Session。 + + Returns: + bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 + """ + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, + ) + from app.services.shipping_notice.inventory_source_rules import ( + _task_routing_lines, + compute_routing_fingerprint, + evaluate_inventory_source_rules, + extract_routing_context, + ) + + sess = session or db.session + active_set = get_active_candidate_set(task) + if active_set is None: + return False + if active_candidate_set_is_manually_pinned(task, session=sess): + return False + existing_lines = { + int(row.line_no): row + for row in (active_set.lines or []) + if getattr(row, 'line_no', None) is not None + } + target = existing_lines.get(int(line_no)) + if target is None: + return False + current_codes = [ + str(code).strip().upper() + for code in (target.source_codes_json or []) + if str(code or '').strip() + ] + if len(current_codes) <= 1: + return False + + routing_lines = _task_routing_lines(task) + position = int(line_no) - 1 + if position < 0 or position >= len(routing_lines): + return False + line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position]) + line_status = str(getattr(line_result, 'status', '') or '').strip().lower() + if line_status not in {'resolved', 'ambiguous'}: + return False + new_codes: list[str] = [] + for raw in (getattr(line_result, 'source_codes', None) or []): + code = str(raw or '').strip().upper() + if code and code not in new_codes and get_database_inventory_source(code) is not None: + new_codes.append(code) + if not new_codes: + return False + + line_projections: list[dict[str, Any]] = [] + union_codes: list[str] = [] + for row_line_no in sorted(existing_lines): + row = existing_lines[row_line_no] + codes = ( + new_codes + if row_line_no == int(line_no) + else [ + str(code).strip().upper() + for code in (row.source_codes_json or []) + if str(code or '').strip() + ] + ) + for code in codes: + if code not in union_codes: + union_codes.append(code) + line_projections.append({ + 'line_no': row_line_no, + 'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None, + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'candidate_inventory_source_codes': codes, + }) + if not union_codes: + return False + + context = extract_routing_context(task) + adjudication = InventorySourceAdjudication( + status='candidates_frozen', + method='line_refresh_reroute', + source_code=None, + connector_type=None, + warehouse_id=None, + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[{'source_code': code} for code in union_codes], + evidence=[{ + 'line_candidates_refresh': { + 'line_no': int(line_no), + 'previous_codes': current_codes, + 'new_codes': new_codes, + }, + }], + reason='line_refresh_reroute', + ) + freeze_result = freeze_candidates_for_task( + task, + adjudication=adjudication, + line_projections=line_projections, + execution_id=execution_id, + session=sess, + ) + if not freeze_result.created_new: + return False + from app.services.shipping_notice.tool_common import log_task_event + + log_task_event( + task, + 'inventory_candidates_refreshed', + { + 'scope': 'line', + 'line_no': int(line_no), + 'previous_codes': current_codes, + 'new_codes': new_codes, + 'new_set_id': int(freeze_result.candidate_set_id), + }, + source='system', + ) + return True + + def freeze_wave_notice_routing( notice: ShippingNotice, *, diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/inventory_candidate_projection.py index bb42bcff..68dd12a2 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/inventory_candidate_projection.py @@ -21,6 +21,7 @@ from app.models import ( ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, ShippingInventoryFile, + ShippingNotice, ShippingOrderTask, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt, @@ -82,8 +83,35 @@ def _candidate_set_filter( return list(rows) +def resolve_inventory_fact_task(task: Any) -> Any: + """ + 将库存事实读取对象归一为正式 OT。 + + 核心逻辑:候选集/库存 Link 全部挂在 OT 上,而货代上传等入口按 business_no + 加载 ShippingNotice——Notice 没有 active_inventory_candidate_set_id 字段, + 直接查询会 fail-closed 成「库存源尚未确定」(历史缺陷:RPA 上传被恒拦截, + 自动推进的 freight_upload_rpa 门禁也因此秒切人工)。OT 原样返回;Notice 沿 + order_task_id 解析,缺绑定或 OT 不存在时原样返回,由上层无候选集语义继续 + fail-closed。 + + Args: + task: ShippingOrderTask 或 ShippingNotice。 + + Returns: + 归一后的 OT(或无法解析时的原对象)。 + """ + if isinstance(task, ShippingNotice): + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is None: + return task + order_task = _session().get(ShippingOrderTask, int(order_task_id)) + if order_task is not None: + return order_task + return task + + def get_active_candidate_set( - task: ShippingOrderTask, + task: ShippingOrderTask | ShippingNotice, *, session: Session | None = None, ) -> ShippingInventoryCandidateSet | None: @@ -92,7 +120,9 @@ def get_active_candidate_set( 核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id; 指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。 + 传入 ShippingNotice 时先归一为其 order_task(见 resolve_inventory_fact_task)。 """ + task = resolve_inventory_fact_task(task) candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None) if candidate_set_id is None: return None diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index d84d0305..8ae4d075 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -277,9 +277,14 @@ def assert_inventory_source_gate( def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]: - """返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。""" + """返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。 + + 传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。 + """ + from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + task = resolve_inventory_fact_task(task) source_codes = task_frozen_inventory_source_codes(task) source_code = source_codes[0] if len(source_codes) == 1 else None source = get_database_inventory_source(source_code) if source_code else None @@ -294,13 +299,19 @@ def resolve_inventory_source_warehouse_id( *, source: dict[str, Any] | None, ) -> str | None: - """解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。""" + """解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。 + + 传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。 + """ if not source: return None mode = str(source.get('warehouse_resolution_mode') or '').strip().lower() if mode == 'fixed': return str(source.get('fixed_warehouse_id') or '').strip().upper() or None + from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task + + task = resolve_inventory_fact_task(task) task_id = getattr(task, 'id', None) source_code = str(source.get('source_code') or '').strip().upper() if not task_id or not source_code: diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 56bb7ed8..2ef9fc87 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -5,6 +5,9 @@ services/shipping_notice/line_inventory_match_persistence.py 依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。 逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库; 新快照新增行并切换 is_current;不覆盖历史快照事实。 + 行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」; + 仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件 + ≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。 匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列, 供后续投影层与自动放行服务读取。 """ @@ -111,12 +114,14 @@ def persist_line_inventory_match_facts( from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts snap_id = active_inventory_runtime_facts(task).get('inventory_file_id') - # 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的 - # 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。 + # 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。 snapshot_file_no = None if snap_id is not None: snapshot = ShippingInventoryFile.query.get(int(snap_id)) snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None + # 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照 + # (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。 + file_id_by_no: dict[str, int | None] = {} line_results = [ item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict) @@ -156,6 +161,23 @@ def persist_line_inventory_match_facts( continue snapshot_line_id = int(snapshot_line.id) + # [STEP] 行级文件归因:匹配结果自带 inventory_file_no 时解析命中文件 ID; + # 未回填(如 not_found)或文件号无法解析时回退任务级锚点快照。 + # 禁止把锚点文件身份盖到命中了其他源文件的行上(历史缺陷根因)。 + line_file_no = str(result.get('inventory_file_no') or '').strip() or None + line_snap_id = snap_id + if line_file_no is not None: + if line_file_no not in file_id_by_no: + hit_file = ( + ShippingInventoryFile.query + .filter_by(inventory_file_no=line_file_no) + .first() + ) + file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None + resolved_file_id = file_id_by_no[line_file_no] + if resolved_file_id is not None: + line_snap_id = resolved_file_id + match_result, inventory_status = map_disposition_to_match_codes( disposition=str(result.get('disposition') or res.get('disposition') or ''), part_number=result.get('part_number') or res.get('part_number'), @@ -172,8 +194,8 @@ def persist_line_inventory_match_facts( else [] ) - # [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0) - if snap_id is None and ( + # [STEP] BE-5:本行无任何库存文件身份时禁止 ready/not_found(不得规范为 0) + if line_snap_id is None and ( inventory_status == 'ready' or match_result in {'matched', 'not_found'} ): @@ -195,20 +217,20 @@ def persist_line_inventory_match_facts( ) unit_value = str(unit_raw or '').strip()[:32] or None - # [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current + # [STEP] 同 OT+行+命中文件:更新;否则新建并撤销旧 current existing = None - if snap_id is not None: + if line_snap_id is not None: existing = ( ShippingNoticeLineInventoryMatch.query .filter_by( task_id=int(task.id), snapshot_line_id=snapshot_line_id, line_no=line_no, - inventory_snapshot_id=int(snap_id), + inventory_snapshot_id=int(line_snap_id), ) .first() ) - if existing is None and snap_id is None: + if existing is None and line_snap_id is None: existing = ( ShippingNoticeLineInventoryMatch.query .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) @@ -253,7 +275,7 @@ def persist_line_inventory_match_facts( 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), 'inventory_file_no': file_no, 'inventory_row_ref': result.get('inventory_row_ref'), - 'snapshot_missing': snap_id is None, + 'snapshot_missing': line_snap_id is None, 'evidence_ref_plain': evidence_plain if evidence_ref else None, } row = ShippingNoticeLineInventoryMatch( @@ -273,7 +295,7 @@ def persist_line_inventory_match_facts( else None ), candidate_line_id=int(candidate_line.id) if candidate_line is not None else None, - inventory_snapshot_id=int(snap_id) if snap_id is not None else None, + inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None, match_result=match_result, inventory_status=inventory_status, required_qty=str(required) if required is not None else None, @@ -304,7 +326,7 @@ def persist_line_inventory_match_facts( 'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None, 'allowed_source_codes_snapshot': list(allowed_source_codes), 'inventory_file_no': file_no, - 'inventory_snapshot_id': int(snap_id) if snap_id is not None else None, + 'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None, 'inventory_row_ref': result.get('inventory_row_ref'), 'match_result': match_result, }).encode('utf-8') @@ -342,7 +364,7 @@ def persist_line_inventory_match_facts( 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), 'inventory_file_no': file_no, 'inventory_row_ref': result.get('inventory_row_ref'), - 'snapshot_missing': snap_id is None, + 'snapshot_missing': line_snap_id is None, 'evidence_ref_plain': evidence_plain if evidence_ref else None, } existing.match_result = match_result @@ -385,7 +407,7 @@ def persist_line_inventory_match_facts( 'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None, 'allowed_source_codes_snapshot': list(allowed_source_codes), 'inventory_file_no': file_no, - 'inventory_snapshot_id': int(snap_id) if snap_id is not None else None, + 'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None, 'inventory_row_ref': result.get('inventory_row_ref'), 'match_result': match_result, }).encode('utf-8') diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 096b034c..efd03c70 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -938,6 +938,42 @@ def _handle_retry_inventory_preparation( freeze_mode='manual', ) db.session.flush() + # [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前 + # 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。 + # 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方 + # 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」 + # 即可让新源进入取数与匹配范围,无需重建订单。 + # 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新; + # 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走 + # override_line_inventory_source)。 + # 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope + # 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。 + if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation': + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + if latest_export_artifact(task) is None: + from app.services.shipping_notice.inventory_candidate_freeze_service import ( + refresh_candidates_from_current_routing, + refresh_line_candidates_from_current_routing, + ) + + if line_scope is None: + refresh_candidates_from_current_routing(task, execution_id=int(execution.id)) + elif refresh_line_candidates_from_current_routing( + task, line_no=int(line_scope['line_no']), execution_id=int(execution.id), + ): + # 刷新产生新候选集后旧 scope 已过期:按同参重解析行作用域,让本次失效与 + # RPA 取数直接使用新冻结码;重解析为 None(如行键已失效)则保守沿用旧值。 + refreshed_scope = _resolve_line_inventory_scope( + task, + line_scope_key=( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ), + ) + if refreshed_scope is not None: + line_scope = refreshed_scope if payload.get('action_code') in { 'retry_inventory_preparation', 'retry_inventory_from_preparation', diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index cd490a3f..683fb292 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -1564,13 +1564,22 @@ def _enrich_task_center_fields( data["created_by"] = task.user_id if viewer_user_id is not None: data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin) + # 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。 + data["can_download_export"] = can_download_task_export( + task, user_id=int(viewer_user_id), is_admin=is_admin, + ) data["recent_event"] = _latest_task_event_summary(task) data["artifact_summary"] = _artifact_summary_for_task(task) data['notice_line_summary'] = _notice_line_summary_for_task(task) # [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。 from app.services.shipping_notice.ui_state import build_task_ui_state - ui_state = build_task_ui_state(task, include_stage_context=include_stage_context) + ui_state = build_task_ui_state( + task, + include_stage_context=include_stage_context, + viewer_user_id=viewer_user_id, + viewer_is_admin=is_admin, + ) data["ui_state"] = ui_state # [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution); # 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。 @@ -1730,12 +1739,15 @@ def list_tasks_page_for_user( page: int = 1, page_size: int = 20, lifecycle_status: str | None = None, + is_admin: bool = False, ) -> dict[str, Any]: """ 分页列出当前用户可见的发货任务摘要。 工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页; `items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。 + ``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export), + 不扩大列表可见范围(仍为本人 + 无主 Notice)。 """ normalized_page = max(1, int(page)) normalized_page_size = max(1, min(int(page_size), 100)) @@ -1795,7 +1807,7 @@ def list_tasks_page_for_user( rows = [row for row in rows if row is not None] return { "items": [ - serialize_task_summary(item, viewer_user_id=user_id) + serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin) for item in rows ], "page": normalized_page, @@ -1849,6 +1861,35 @@ def get_task_visible_to_user( return task +def can_download_task_export( + task: ShippingOrderTask | ShippingNotice | None, + *, + user_id: int, + is_admin: bool = False, +) -> bool: + """ + 导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。 + + 核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、 + can_download_export 字段都必须消费本谓词,禁止各处另行推导归属; + 管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。 + 无主任务(user_id IS NULL)仅管理员可下载。 + + Args: + task: 已加载的任务实体(可为 None)。 + user_id: 当前查看/下载用户。 + is_admin: 是否平台管理员。 + + Returns: + 当前用户是否允许下载该任务的正式 Excel。 + """ + if task is None: + return False + if is_admin: + return True + return task.user_id is not None and int(task.user_id) == int(user_id) + + def list_freight_notice_groups_for_task( task: ShippingNotice, *, diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index cfe8babd..e15d5c49 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -61,7 +61,11 @@ from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGES, project_lifecycle, ) -from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary +from app.services.shipping_notice.query_service import ( + can_download_task_export, + resolve_task_export_download, + serialize_task_summary, +) from app.services.shipping_notice.state_machine import ( UserMode, ) @@ -1162,6 +1166,8 @@ def build_task_ui_state( task: ShippingNotice, *, include_stage_context: bool = False, + viewer_user_id: int | None = None, + viewer_is_admin: bool = False, ) -> dict[str, Any]: """ 构建单票任务 UI State。 @@ -1170,6 +1176,14 @@ def build_task_ui_state( 禁止 Chat、通知卡与任务中心分别推导状态; 可点击用户动作只由 Gate 与已验证 Artifact 授权产生。 Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。 + + Args: + task: 源任务实体。 + include_stage_context: 是否附带 stage_context(工作面只读事实)。 + viewer_user_id: 当前查看者;给定时时 download_excel 动作按导出统一谓词 + (can_download_task_export:创建者或管理员)门禁下发;为 None 时维持 + 聊天链路旧口径(仅按 Artifact 授权,聊天会话与创建者同源)。 + viewer_is_admin: 查看者是否平台管理员(配合 viewer_user_id 使用)。 """ from app.services.shipping_notice.state_machine import ( _review_status_fallback_ui_state, @@ -1210,7 +1224,12 @@ def build_task_ui_state( # [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作, # 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在 # Artifact 已通过 resolve_task_export_download 校验时补入下载授权。 - if resolve_task_export_download(task) is not None: + # 下载动作与导出端点消费同一谓词:viewer 已知时按创建者/管理员门禁, + # 避免非创建者"看得到点不动";viewer 未知(聊天链路)维持 Artifact 口径。 + if resolve_task_export_download(task) is not None and ( + viewer_user_id is None + or can_download_task_export(task, user_id=int(viewer_user_id), is_admin=viewer_is_admin) + ): download_action = _unified_action({ 'id': 'download_excel', 'label': '下载 Excel', diff --git a/backend/tests/test_inventory_source_gate_notice_task.py b/backend/tests/test_inventory_source_gate_notice_task.py new file mode 100644 index 00000000..d3c43a76 --- /dev/null +++ b/backend/tests/test_inventory_source_gate_notice_task.py @@ -0,0 +1,121 @@ +""" +tests/test_inventory_source_gate_notice_task.py + +用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。 +依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。 +逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿 + order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id + 字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被 + 「库存源尚未确定」静默拦截(无事件、无 attempt 记录)。 +""" + +from __future__ import annotations + + +def _make_frozen_task_with_notice(task_no: str): + """构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。""" + from app import db + from app.models import ( + ShippingInventoryCandidateLine, + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, + ShippingNotice, + ShippingOrderTask, + ) + + task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1) + db.session.add(task) + db.session.flush() + + candidate_set = ShippingInventoryCandidateSet( + task_id=int(task.id), + set_version=1, + lifecycle_status='frozen', + input_fingerprint=f'fp-{task_no}', + routing_rule_version_json={}, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=int(candidate_set.id), + source_code='CRANE', + candidate_order=1, + candidate_origin='rule', + )) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=int(candidate_set.id), + line_no=1, + part_number='PN-1', + reservation_id='3000092917', + source_codes_json=['CRANE'], + )) + task.active_inventory_candidate_set_id = int(candidate_set.id) + db.session.flush() + + notice = ShippingNotice( + task_no=f'SN-{task_no}', + order_task_id=int(task.id), + business_no=f'USZ{task_no[-6:]}', + user_id=1, + ) + db.session.add(notice) + db.session.flush() + return task, notice + + +def _patch_source_lookup(monkeypatch): + """注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。""" + from app.services.shipping_notice import inventory_source_gate as gate_mod + + def _source(code): + if str(code).upper() != 'CRANE': + return None + return { + 'source_code': 'CRANE', + 'display_name': 'Crane FootPrint', + 'connector_type': 'crane', + 'warehouse_resolution_mode': 'inventory_match', + 'fixed_warehouse_id': None, + 'enabled': True, + } + + monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source) + + +def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch): + """门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。""" + _patch_source_lookup(monkeypatch) + with app.app_context(): + from app.services.shipping_notice.inventory_source_gate import ( + is_inventory_source_stable, + task_inventory_identity, + ) + + task, notice = _make_frozen_task_with_notice('OT-NOTICE-GATE-OK') + # 断言意图:OT 与其 Notice 的稳定性判定一致(历史缺陷:Notice 恒 False) + assert is_inventory_source_stable(task) is True + assert is_inventory_source_stable(notice) is True + # 断言意图:库存身份(RPA 网点/仓库)对两者一致,且能解析到源 + identity_ot = task_inventory_identity(task) + identity_notice = task_inventory_identity(notice) + assert identity_ot == identity_notice + assert identity_notice['inventory_source_code'] == 'CRANE' + + +def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch): + """Notice 缺 OT 绑定时保持 fail-closed(不得误判稳定)。""" + _patch_source_lookup(monkeypatch) + with app.app_context(): + from app import db + from app.models import ShippingNotice + from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable + + orphan = ShippingNotice( + task_no='SN-ORPHAN-NOTICE', + business_no='USZORPH01', + user_id=1, + ) + db.session.add(orphan) + db.session.flush() + # 断言意图:无法归一到 OT 的 Notice 保持 fail-closed + assert is_inventory_source_stable(orphan) is False diff --git a/backend/tests/test_line_inventory_match_persistence.py b/backend/tests/test_line_inventory_match_persistence.py index b3ed9299..43ebde3b 100644 --- a/backend/tests/test_line_inventory_match_persistence.py +++ b/backend/tests/test_line_inventory_match_persistence.py @@ -187,3 +187,91 @@ def test_persist_updates_part_available_qty_on_existing_row(app): assert rows[0].part_available_qty is None # 断言意图:同快照幂等更新,始终只有一条 current 事实 assert len(rows) == 1 + + +# --------------------------------------------------------------------------- +# 行级文件归因契约(多源池:锚点文件 ≠ 命中文件) +# --------------------------------------------------------------------------- + + +def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int: + """构造最小可用库存快照文件,返回主键。""" + from app import db + from app.models import ShippingInventoryFile + + file_row = ShippingInventoryFile( + inventory_file_no=file_no, + storage_path=f'/tmp/{file_no}.xlsx', + source_code='DSV360_TEST', + warehouse_id=warehouse_id, + warehouse_code=warehouse_id, + snapshot_status='ready', + line_count=1, + share_mode='warehouse_pool', + ) + db.session.add(file_row) + db.session.flush() + return int(file_row.id) + + +def _ok_result(*, line_index: int = 0, inventory_file_no: str | None = None) -> dict: + """构造命中库存的行结果桩;inventory_file_no 模拟匹配器回填的命中文件身份。""" + result = { + 'line_index': line_index, + 'disposition': 'ok', + 'part_number': 'PN-1', + 'reservation_id': '3000092917', + 'required_qty': 8.0, + 'available_qty': 8.0, + } + if inventory_file_no is not None: + result['inventory_file_no'] = inventory_file_no + return result + + +def test_persist_attributes_line_to_hit_file_not_anchor(app): + """多源池下行命中 B 文件时,inventory_snapshot_id 必须归因 B,而非任务锚点 A。 + + 历史缺陷:持久化把任务级锚点文件 ID 盖到所有行,Excel 仓库列因此写成 + 锚点仓(AWSCV 单写成 CMH01)。 + """ + with app.app_context(): + from app import db + from app.models import ShippingInventoryFile + + task = _make_snapshot_task('OT-LINE-FILE-ATTR') + anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01') + hit_id = _make_inventory_file(app, 'SIF-TEST-HIT', 'AWSCV') + + rows = persist_line_inventory_match_facts( + task=task, + match_payload={ + 'line_results': [_ok_result(inventory_file_no='SIF-TEST-HIT')], + 'resolutions': [], + }, + inventory_snapshot_id=anchor_id, + ) + # 断言意图:行事实挂到命中文件,而不是任务级锚点文件 + assert rows[0].inventory_snapshot_id == hit_id + assert rows[0].matched_file_no == 'SIF-TEST-HIT' + # 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源) + hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id) + assert hit_file.warehouse_id == 'AWSCV' + + +def test_persist_falls_back_to_anchor_without_line_file_no(app): + """行结果未回填文件号(如 not_found)时,保持任务级锚点回退,行为不变。""" + with app.app_context(): + task = _make_snapshot_task('OT-LINE-FILE-FALLBACK') + anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR-FB', 'BYAWSCMH01') + + rows = persist_line_inventory_match_facts( + task=task, + match_payload={ + 'line_results': [_not_found_result(part_available_qty=None)], + 'resolutions': [], + }, + inventory_snapshot_id=anchor_id, + ) + # 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容) + assert rows[0].inventory_snapshot_id == anchor_id diff --git a/backend/tests/test_shipping_line_scoped_inventory_retry.py b/backend/tests/test_shipping_line_scoped_inventory_retry.py index 85bbfdbd..a56aebd7 100644 --- a/backend/tests/test_shipping_line_scoped_inventory_retry.py +++ b/backend/tests/test_shipping_line_scoped_inventory_retry.py @@ -31,6 +31,12 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch): 'app.services.shipping_notice.process_gate_executor._resolve_order_task', lambda _execution: task, ) + # [回归] 执行器 [STEP 0B] 新增 latest_export_artifact(Excel 源锁定判断,查库)依赖; + # 纯单测无 Flask/DB,打桩为「Excel 已生成」使刷新块短路,保持本用例聚焦行级收窄断言。 + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: SimpleNamespace(id=77), + ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', lambda _task: candidate_set, diff --git a/backend/tests/test_shipping_notice_export_archive.py b/backend/tests/test_shipping_notice_export_archive.py new file mode 100644 index 00000000..5d28d676 --- /dev/null +++ b/backend/tests/test_shipping_notice_export_archive.py @@ -0,0 +1,41 @@ +""" +backend/tests/test_shipping_notice_export_archive.py + +用途:shipping_notice 批量导出归档(build_export_archive)下载授权单测。 +依赖:pytest、ShippingNotice、export_archive.build_export_archive。 +逻辑:批量选择与单票导出消费同一谓词口径(创建者或管理员);无 Artifact 时 + 保留 manifest missing 语义,并按票携带 business_no 供端点写访问审计。 +""" + +import pytest + +from app.core.errors import NotFoundError +from app.models import ShippingNotice + + +def test_build_export_archive_selects_by_creator_or_admin(app): + """批量归档与单票下载同一谓词:陌生用户整体拒绝,创建者/管理员放行。""" + with app.app_context(): + from app import db + from app.services.shipping_notice.export_archive import build_export_archive + + owned = ShippingNotice( + task_no="SN-ARC-OWNED", business_no="QMN-ARC-1", user_id=7, source_type="manual", + ) + db.session.add(owned) + db.session.commit() + + # 非创建者普通用户:任一越权即整体拒绝(防部分成功)。 + with pytest.raises(NotFoundError): + build_export_archive(user_id=8, business_nos=["QMN-ARC-1"]) + + # 创建者放行;无 Artifact 时保留 missing_artifact 语义并携带 business_no。 + _stream, _name, manifest = build_export_archive(user_id=7, business_nos=["QMN-ARC-1"]) + assert manifest["entries"][0]["status"] == "missing_artifact" + assert manifest["entries"][0]["business_no"] == "QMN-ARC-1" + + # 管理员可下载=可见:他人正式 Notice 放行(端点按票补访问审计)。 + _stream, _name, admin_manifest = build_export_archive( + user_id=8, business_nos=["QMN-ARC-1"], is_admin=True, + ) + assert admin_manifest["entries"][0]["task_no"] == "SN-ARC-OWNED" diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 9ebf9f87..9f67b39e 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -321,6 +321,28 @@ def test_get_task_for_user_rejects_null_owner(app): assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None +def test_can_download_task_export_creator_or_admin(app): + """导出统一谓词:创建者/管理员可下载;非创建者普通用户与无主单一律拒绝。""" + with app.app_context(): + from app import db + from app.services.shipping_notice.query_service import can_download_task_export + + owned = ShippingNotice(task_no="SN-DL-OWNED", business_no="QMN-DL-1", user_id=7, source_type="manual") + orphan = ShippingNotice(task_no="SN-DL-ORPHAN", business_no="QMN-DL-2", user_id=None, source_type="manual") + db.session.add_all([owned, orphan]) + db.session.commit() + + # 创建者可下载;同票对非创建者普通用户拒绝。 + assert can_download_task_export(owned, user_id=7) is True + assert can_download_task_export(owned, user_id=8) is False + # 管理员可下载=可见:他人票与无主票均放行(下载留痕审计兜底)。 + assert can_download_task_export(owned, user_id=8, is_admin=True) is True + assert can_download_task_export(orphan, user_id=7) is False + assert can_download_task_export(orphan, user_id=7, is_admin=True) is True + # 缺实体一律拒绝。 + assert can_download_task_export(None, user_id=7, is_admin=True) is False + + def test_serialize_task_summary_enriches_todo_and_can_handle(app): """SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。""" with app.app_context(): diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index abcffd5a..449972d6 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -465,6 +465,39 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa assert "download_excel" in button_ids +def test_task_ui_state_gates_download_by_viewer(app, monkeypatch) -> None: + """下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。""" + with app.app_context(): + from app import db + + task = ShippingNotice( + task_no="SN-UI-VIEWER-EXPORT", + source_type="manual", + user_id=7, + ) + db.session.add(task) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.resolve_task_export_download', + lambda _task: (object(), 'shipping-export.xlsx'), + ) + + def button_ids(state): + return [ + item.get("code") + for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] + if item + ] + + # 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。 + assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7)) + assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True)) + # 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。 + assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8)) + # viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。 + assert "download_excel" in button_ids(build_task_ui_state(task)) + + def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None: """当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。""" with app.app_context(): diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 5df0855e..fd8435ca 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -1651,6 +1651,12 @@ def test_inventory_preparation_mode_maps_by_action_code(monkeypatch): 'app.services.shipping_notice.process_gate_executor._resolve_order_task', lambda _execution: task, ) + # [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖; + # 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。 + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: SimpleNamespace(id=77), + ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', lambda _task: candidate_set, diff --git a/backend/tests/test_shipping_refresh_inventory_candidates.py b/backend/tests/test_shipping_refresh_inventory_candidates.py new file mode 100644 index 00000000..1ad25d17 --- /dev/null +++ b/backend/tests/test_shipping_refresh_inventory_candidates.py @@ -0,0 +1,504 @@ +""" +tests/test_shipping_refresh_inventory_candidates.py + +用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评, + 未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。 +依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与 + inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、 + process_gate_executor(Task 2 的挂载点集成测试)。 +逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫 + (目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在 + 人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +def _task(set_id=10): + """构造最小 OT 形状:仅 helper/执行器读取的字段。""" + return SimpleNamespace( + id=19, task_no='SN-REFRESH', + order_snapshot_id=3, + active_inventory_candidate_set_id=set_id, + step_payload_json={}, + ) + + +def _active_set(line_defs): + """构造最小活动候选集:lines 为 (line_no, codes) 列表。""" + return SimpleNamespace( + id=10, frozen_by_id=None, sources=[], + lines=[ + SimpleNamespace( + line_no=line_no, source_codes_json=list(codes), + source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}', + ) + for line_no, codes in line_defs + ], + ) + + +def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'): + """隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。""" + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.extract_routing_context', + lambda _task: {'customer': 'X'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint', + lambda _ctx: fingerprint, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version', + lambda: config_version, + ) + + +# ---------- 任务级刷新 ---------- + +def test_refresh_skips_when_single_source_resolved(app, monkeypatch): + """[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU'], + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: called.append(1), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not called + + +def test_refresh_skips_when_manual_selection_exists(app, monkeypatch): + """[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True, + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: called.append(1), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not called + + +def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch): + """[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task(set_id=10) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id), + ) + + def _fake_readjudicate(_task, **_k): + task.active_inventory_candidate_set_id = 11 + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + _fake_readjudicate, + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True + assert events and events[0][0] == 'inventory_candidates_refreshed' + assert events[0][1]['scope'] == 'task' + assert events[0][1]['previous_set_id'] == 10 + assert events[0][1]['new_set_id'] == 11 + + +def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch): + """[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task(set_id=10) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: None, + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not events + + +# ---------- 行级刷新 ---------- + +def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch): + """[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSDU'])]), + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not called + + +def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch): + """[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True, + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not called + + +def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch): + """[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='unresolved', source_codes=()), + ) + freeze_called = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda *_a, **_k: freeze_called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not freeze_called + + +def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch): + """[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: None, + ) + freeze_called = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda *_a, **_k: freeze_called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not freeze_called + + +def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch): + """[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([ + (1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']), + (2, ['DSV360_AWSCV']), + ]), + ) + _patch_routing_common(monkeypatch) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: {'source_code': code}, + ) + freeze_kwargs = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12), + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True + projections = freeze_kwargs[0]['line_projections'] + assert projections[0]['line_no'] == 1 + assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV'] + assert projections[1]['line_no'] == 2 + assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV'] + assert events and events[0][0] == 'inventory_candidates_refreshed' + assert events[0][1]['scope'] == 'line' + assert events[0][1]['line_no'] == 1 + assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV'] + + +def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch): + """[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + _patch_routing_common(monkeypatch) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: {'source_code': code}, + ) + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10), + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not events + + +def _retry_payload(**overrides): + base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7} + base.update(overrides) + return base + + +def _exercise_retry_handler( + monkeypatch, task, payload, *, + refresh_calls, line_scope=None, excel_artifact=None, ensure_calls=None, line_refresh_result=False, +): + """按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。 + + refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。 + line_scope 传 dict 时每次解析都返回它(缺省行为);传 list 时按调用次序逐个弹出 + (用尽后返回 None),用于断言「刷新产生新集后重解析行作用域」。 + line_refresh_result 控制行级刷新 helper mock 的返回值(True 表示产生了新候选集)。 + ensure_calls 顺序捕获 ensure_inventory 收到的 payload(供断言取数范围)。 + 另须打桩 inventory_candidate_projection 三个读取函数:执行器 [STEP 0A] 会真实查库校验 + 活动 CandidateSet,假 Task 不打桩会被提前拦回 inventory_source_routing_required, + 永远到不了被测的 [STEP 0B] 刷新块(与 test_shipping_line_scoped_inventory_retry 同模式)。 + """ + from app.services.shipping_notice import process_gate_executor as executor + + execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout') + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: SimpleNamespace(id=1), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines', + lambda _task: [SimpleNamespace(source_codes_json=['DSV360_AWSDU'])], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources', + lambda _task: [SimpleNamespace(source_code='DSV360_AWSDU')], + ) + if isinstance(line_scope, list): + scope_sequence = list(line_scope) + monkeypatch.setattr( + executor, + '_resolve_line_inventory_scope', + lambda _task, **_k: scope_sequence.pop(0) if scope_sequence else None, + ) + else: + monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope) + monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no}) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: excel_artifact, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing', + lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing', + lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or line_refresh_result, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **_k: {'outcome': 'passed'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_k: None, + ) + if ensure_calls is None: + ensure_calls = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda _payload: ensure_calls.append(dict(_payload)) or {'status': 'ok', 'data': {}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_k: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + return executor._handle_retry_inventory_preparation( + execution=execution, gate=gate, payload=payload, + ) + + +def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch): + """[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。""" + refresh_calls = [] + outcome = _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls, + ) + assert refresh_calls and refresh_calls[0][0] == 'task' + assert refresh_calls[0][1].get('execution_id') == 5 + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'} + + +def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch): + """[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。""" + refresh_calls = [] + outcome = _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls, + line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1}, + ) + assert refresh_calls and refresh_calls[0][0] == 'line' + assert refresh_calls[0][1].get('line_no') == 1 + assert refresh_calls[0][1].get('execution_id') == 5 + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'} + + +def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch): + """[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。""" + refresh_calls = [] + task = _task() + _exercise_retry_handler( + monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'), + refresh_calls=refresh_calls, + ) + _exercise_retry_handler( + monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls, + excel_artifact=SimpleNamespace(id=77), + ) + _exercise_retry_handler( + monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls, + line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1}, + excel_artifact=SimpleNamespace(id=77), + ) + assert not refresh_calls + + +def test_retry_line_refresh_requeries_with_new_scope(app, monkeypatch): + """[断言] 行级刷新产生新候选集后须按同参重解析行作用域:同一次点击的失效与 RPA 取数 + 直接使用新冻结码,而非刷新前解析的旧码;重解析为 None 时才保守沿用旧值。""" + refresh_calls = [] + ensure_calls = [] + outcome = _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls, + line_scope=[ + {'source_codes': ['DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1}, + {'source_codes': ['DSV360_AWSDU', 'DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1}, + ], + line_refresh_result=True, + ensure_calls=ensure_calls, + ) + assert refresh_calls and refresh_calls[0][0] == 'line' + assert refresh_calls[0][1].get('line_no') == 1 + assert ensure_calls and ensure_calls[-1].get('source_codes') == ['DSV360_AWSDU', 'DSV360_AWSCV'] + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'} + + +def test_retry_from_preparation_does_not_refresh(app, monkeypatch): + """[断言] retry_inventory_from_preparation 不做候选集刷新前置(仅 retry_inventory_preparation 触发,锁定文档排除项)。""" + refresh_calls = [] + _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(action_code='retry_inventory_from_preparation'), + refresh_calls=refresh_calls, + ) + assert not refresh_calls diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index b307d7a1..0ccd237d 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -15,7 +15,9 @@ **已完成桶**:默认子视图「通知完成」为跨 OT 平铺的明细行报表(`GET /shipping-tasks/my-todos/done-lines`),行 = 标准 12 字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价)+ 页面溯源列(`business_no||task_no`);筛选支持 客户 / 料号 / 发货通知日期(Notice created_at)范围,按明细行分页;导出 `GET .../done-lines/export` 严格 12 列中文表头(OT 不落列,openpyxl 直写,不注册模板)。已用数量/open qty 后端暂无数据源,契约留空;约定出货日期取行级 `required_date`(缺失回退快照表头列)、订单单号取表头 `source_order_number`(field_id 键)、单价取行 `unit_price`。「复核驳回 / 已作废」子视图走既有任务表 + 抽屉,`my-todos` 新增 `terminal_kind` 参数(`upload_complete|reject_void`)服务端过滤。 -**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。 +**批量操作**:仅「货代上传」阶段且当前用户可下载(`isBatchDownloadableRow` = `isFreightUploadRow` + 后端谓词字段 `can_download_export`)的正式 Notice 行有复选框,勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。 + +**Excel 下载权限统一口径(2026-10-13)**:单票(`/shipping-tasks//export`、`/shipping-notices//export`)与批量(`/shipping-notices/batch/export`、`/shipping-exports/archive`)的下载授权一律消费 `query_service.can_download_task_export` 统一谓词——**创建者或平台管理员(可下载=可见,无主单仅管理员)**;管理员下载消除"看得到点不动",全部下载(含批量按票)写 `record_access_audit`(批量 `metadata.export=batch_zip` 并附 `batch_status`)。UI 与端点同源:SUMMARY/DETAIL enrich 下发 `can_download_export`;`ui_state` 的 `download_excel` 动作按查看者门禁下发(viewer 缺省的聊天链路维持仅 Artifact 授权旧口径);任务中心复选框/全选、抽屉下载链接均消费谓词字段,禁止前端由 `created_by` 自行反推。写路径归属(`get_task_for_user` / 履约归属断言)不变。 ## 任务中心 OT 直链工作台:深链补 Case 锚点 + 任务详情兜底(2026-09-17) @@ -1902,7 +1904,7 @@ GET /api/admin/shipping-order-schema/published-contract - `GET /api/workspace/shipping-tasks?page=1&page_size=10` 由数据库执行排序、总数统计和切片,返回 `{ items, page, page_size, total }`;业务阶段统一由 `ui_state.stage` 投影,接口不再接受 `process_status`。 - 工作台每页展示 10 条任务,筛选或刷新重置为第一页;任务多选、全选和 ZIP 下载只作用于当前页,切页时清空选择,禁止跨页误操作。 - 工作台提供“下载本批次 ZIP”和任务列表显式多选两种入口;多选可全选当前页结果并显示选择数量。 -- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。 +- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。下载授权与单票导出同一谓词(`can_download_task_export`:创建者或管理员),成功后按票写 `record_access_audit`(`metadata.export=batch_zip`,manifest entries 携带 `business_no` 供审计聚合)。 - 每票只选择最新且仍与 Task 当前导出路径一致的 `status=ready` Artifact,并在打包前复算 SHA-256;任务纠错清空引用、文件缺失或校验失败均不进入 ZIP 文件区,但必须进入 `manifest.json`。 - manifest 状态为 `included / missing_artifact / missing_file / checksum_mismatch`;同名文件保留首个,其余追加 `task_no`,禁止覆盖。 - ZIP 使用 `SpooledTemporaryFile`:小文件在内存,超过 16 MiB 自动落临时磁盘,由响应结束后释放。 @@ -3968,3 +3970,32 @@ inventory_preparation Gate - Excel/波次条件零改动:出单仍需人工勾选波次,放行行可勾选资格规则不变(`export.py` / wave 服务 / 满足性聚合未改动)。 - 同名不同义:订单明细表 / 聊天匹配卡的「可用数量」仍是预约匹配语义;prep 工作台新「可用数量」列是料号兜底总量,两处是否统一待产品定。 - 存量 canonical-only 快照行料号兜底不生效(与基线一致)。 + +## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等) + +**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的 +取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源, +通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断 +(prod 实例 SORC-E19FE1B9AB8F4FD2)。 + +**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前 +新增幂等前置刷新,任务级与行级共用守卫红线: +- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source` + 整单重判候选集。 +- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评 + (`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source` + 启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后 + `freeze_candidates_for_task` 重冻结,其余行原样继承。 +- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时 + 由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有 + `invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。 +- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走 + `override_line_inventory_source`;候选集含人工选源(frozen_by_id / + candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新; + 轮询/自动首投/`retry_inventory_from_preparation` 不刷新。 +- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源 + 去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写 + 动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。 + +**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed` +(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。 diff --git a/docs/funclist.md b/docs/funclist.md index c3518059..8ad3e987 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -229,6 +229,7 @@ | **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | | **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | | 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 | +| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 | ### 排程平台任务契约中心(schedule) diff --git a/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md b/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md new file mode 100644 index 00000000..5ec2c7bc --- /dev/null +++ b/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md @@ -0,0 +1,1077 @@ +# 库存候选集刷新(任务级+行级人工重取前置)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 让「重新获取库存(RPA)」的**任务级与行级**人工重取前,按当前主数据幂等重判候选库存源(任务级整单重路由;行级仅重评目标行),并放开前端歧义行库存源下拉到全部已启用源。 + +**Architecture:** 零新动作码、零契约变更、零 UI 按钮变更。后端在 `_handle_retry_inventory_preparation` 人工重试分支插入前置刷新:任务级走 `refresh_candidates_from_current_routing`(复用 `adjudicate_and_apply_inventory_source` + freeze 幂等);行级走 `refresh_line_candidates_from_current_routing`(行级规则重评 + 以活动集为骨架定向替换目标行后 `freeze_candidates_for_task` 冻结,`created_new` 判变化)。两者共用三条守卫红线;新版候选集 supersede 时由 `_invalidate_task_candidate_outputs` 内置失效旧库存事实。前端把行级下拉选项抽为纯函数 `mergeInlineSourceOptions`(候选置顶 + 全量源去重兜底)。 + +**Tech Stack:** Flask + SQLAlchemy(backend/app/services/shipping_notice)、Vue 3 + TS + Vitest(frontend/src/features/chat)。 + +**Spec:** 会话内已确认的「升级不换按钮 + 任务级/行级都刷新」方案(2026-10-13 诊断与设计,要点见 Global Constraints;诊断结论另存于 `.engramory-memory/shipping-source-selection-impl.md`)。 + +## Global Constraints + +- **零新动作码**:不改 `process_gate_contract` 动作清单、不下发新 capability、前端不新增按钮。 +- **刷新只是显式人工重取的伴随前置**:仅 `retry_inventory_preparation` 触发——任务级(`line_scope` 为空)整单刷新;行级(`line_scope` 非空)仅刷新目标行。`poll_inventory_preparation`(只读轮询)、自动首投(`trigger=='gate_attempt_passed'`)、`retry_inventory_from_preparation`(恢复流变体)一律不刷新。 +- **守卫红线(任务级与行级同源)**:① 已定源不自动改源——任务级冻结候选 ≤1 不刷新,行级该行候选 ≤1 不刷新;换源走 `override_line_inventory_source` 行级覆写;② 活动候选集含人工选源(`frozen_by_id` 非空或 `candidate_origin=='manual_override'`)不刷新——人工指定即定论;③ Excel 已生成(`latest_export_artifact` 非空,D7 锁定边界)不刷新。 +- **幂等**:输入指纹未变时 `freeze_candidates_for_task` 复用旧集(`created_new=False`),刷新返回 False、零副作用;主数据有变但路由结论未变时会产生新版集(配置版本进入指纹),此时用户本就在显式重取,失效重取符合预期,重复点击收敛。 +- **行级候选必须过滤可用性**:`InventoryRoutingResult.source_codes` 为规则原始候选(未做启停过滤),入候选集前必须经 `get_database_inventory_source` 校验(对齐 `_result_to_adjudication` 语义)。 +- **不改 `models.py`,无数据库迁移**(候选集天然支持 `set_version` 多版本)。 +- **不动既有边界**:`inventory_candidate_freeze_service.py` 中已有的 `#region debug-point A/C/E` 调试代码块**保持原样不要删除**(边界外事项,另行处理)。 +- i18n 四语言(zh-CN / zh-TW / en / th)同步;禁止硬编码文案。 +- 注释遵循 AGENTS §5:文件层三要素 + 函数层 docstring/JSDoc;业务步骤用 `[STEP n]`;禁止逐行翻译代码。 +- **禁止自动 commit**:每个任务以 `git add <具体文件>` 收尾,提交由用户显式决定。 +- 后端测试命令:`cd backend && .\.venv\Scripts\python.exe -m pytest tests/ -q`;前端验证:`cd frontend && npx vitest run ` + 最终 `npm run build` 必须通过。 + +--- + +### Task 1: 后端刷新 helper(freeze service 内新增,任务级+行级) + +**Files:** +- Modify: `backend/app/services/shipping_notice/inventory_candidate_freeze_service.py`(在 `freeze_manual_line_source_selection` 之后追加三个函数) +- Test: `backend/tests/test_shipping_refresh_inventory_candidates.py`(新建) + +**Interfaces:** +- Consumes: `adjudicate_and_apply_inventory_source(task, *, execution_id=None)`(inventory_source_gate.py:121);`get_active_candidate_set(task)`(inventory_candidate_projection.py);`task_frozen_inventory_source_codes(task)`(stp_inventory_freeze.py:186);`evaluate_inventory_source_rules(*, task, line=None)` / `_task_routing_lines(task)` / `extract_routing_context` / `compute_routing_fingerprint`(inventory_source_rules.py,重导出自 routing_engine);`get_database_inventory_source` / `inventory_sources_runtime_version`(inventory_source_repository.py);`log_task_event`(tool_common.py);同模块 `freeze_candidates_for_task`。 +- Produces: + - `active_candidate_set_is_manually_pinned(task, *, session=None) -> bool` + - `refresh_candidates_from_current_routing(task, *, execution_id=None, session=None) -> bool`(任务级,True=产生新版候选集) + - `refresh_line_candidates_from_current_routing(task, *, line_no: int, execution_id=None, session=None) -> bool`(行级,True=产生新版候选集) + - 任务事件 `inventory_candidates_refreshed`(payload 含 `scope: 'task'|'line'`)。 + +- [ ] **Step 1: 写失败测试(新建测试文件)** + +```python +""" +tests/test_shipping_refresh_inventory_candidates.py + +用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评, + 未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。 +依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与 + inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、 + process_gate_executor(Task 2 的挂载点集成测试)。 +逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫 + (目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在 + 人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +def _task(set_id=10): + """构造最小 OT 形状:仅 helper/执行器读取的字段。""" + return SimpleNamespace( + id=19, task_no='SN-REFRESH', + order_snapshot_id=3, + active_inventory_candidate_set_id=set_id, + step_payload_json={}, + ) + + +def _active_set(line_defs): + """构造最小活动候选集:lines 为 (line_no, codes) 列表。""" + return SimpleNamespace( + id=10, frozen_by_id=None, sources=[], + lines=[ + SimpleNamespace( + line_no=line_no, source_codes_json=list(codes), + source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}', + ) + for line_no, codes in line_defs + ], + ) + + +def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'): + """隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。""" + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.extract_routing_context', + lambda _task: {'customer': 'X'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint', + lambda _ctx: fingerprint, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version', + lambda: config_version, + ) + + +# ---------- 任务级刷新 ---------- + +def test_refresh_skips_when_single_source_resolved(app, monkeypatch): + """[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU'], + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: called.append(1), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not called + + +def test_refresh_skips_when_manual_selection_exists(app, monkeypatch): + """[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True, + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: called.append(1), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not called + + +def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch): + """[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task(set_id=10) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id), + ) + + def _fake_readjudicate(_task, **_k): + task.active_inventory_candidate_set_id = 11 + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + _fake_readjudicate, + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True + assert events and events[0][0] == 'inventory_candidates_refreshed' + assert events[0][1]['scope'] == 'task' + assert events[0][1]['previous_set_id'] == 10 + assert events[0][1]['new_set_id'] == 11 + + +def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch): + """[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task(set_id=10) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'], + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source', + lambda _task, **_k: None, + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_candidates_from_current_routing(task) is False + assert not events + + +# ---------- 行级刷新 ---------- + +def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch): + """[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSDU'])]), + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not called + + +def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch): + """[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True, + ) + called = [] + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not called + + +def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch): + """[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='unresolved', source_codes=()), + ) + freeze_called = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda *_a, **_k: freeze_called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not freeze_called + + +def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch): + """[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: None, + ) + freeze_called = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda *_a, **_k: freeze_called.append(1), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not freeze_called + + +def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch): + """[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([ + (1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']), + (2, ['DSV360_AWSCV']), + ]), + ) + _patch_routing_common(monkeypatch) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: {'source_code': code}, + ) + freeze_kwargs = [] + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12), + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True + projections = freeze_kwargs[0]['line_projections'] + assert projections[0]['line_no'] == 1 + assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV'] + assert projections[1]['line_no'] == 2 + assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV'] + assert events and events[0][0] == 'inventory_candidates_refreshed' + assert events[0][1]['scope'] == 'line' + assert events[0][1]['line_no'] == 1 + assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV'] + + +def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch): + """[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。""" + from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service + + task = _task() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]), + ) + _patch_routing_common(monkeypatch) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules._task_routing_lines', + lambda _task, **_k: [{'part_number': 'PN1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules', + lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', + lambda code, **_k: {'source_code': code}, + ) + monkeypatch.setattr( + freeze_service, 'freeze_candidates_for_task', + lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10), + ) + events = [] + monkeypatch.setattr( + 'app.services.shipping_notice.tool_common.log_task_event', + lambda _task, event_type, payload, **_k: events.append((event_type, payload)), + ) + assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False + assert not events +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: FAIL(`AttributeError: ... has no attribute 'refresh_candidates_from_current_routing'` 等) + +- [ ] **Step 3: 实现 helper(追加到 `freeze_manual_line_source_selection` 之后)** + +```python +def active_candidate_set_is_manually_pinned( + task: ShippingNotice, + *, + session: Session | None = None, +) -> bool: + """ + 判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。 + + Args: + task: 当前 ShippingOrderTask。 + session: 可选 Session。 + + Returns: + bool: True 表示人工已裁决候选源,自动重路由必须跳过。 + """ + sess = session or db.session + active_set = ( + sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + if getattr(task, 'active_inventory_candidate_set_id', None) is not None + else None + ) + if active_set is None: + return False + if getattr(active_set, 'frozen_by_id', None) is not None: + return True + return any( + str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override' + for source in (active_set.sources or []) + ) + + +def refresh_candidates_from_current_routing( + task: ShippingNotice, + *, + execution_id: int | None = None, + session: Session | None = None, +) -> bool: + """ + 任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。 + 【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用; + 禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。 + + 核心逻辑: + [守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单 + 不得自动改源,换源走 override_line_inventory_source 行级覆写。 + [守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override') + 时跳过:人工指定即定论,禁止重路由洗掉人工裁决。 + [STEP 1] 记录当前活动 set_id。 + [STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结 + (freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时 + apply 不落任何事实,活动集保持不变,同样视为无变化)。 + [STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs: + 匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。 + + Args: + task: 当前 ShippingOrderTask(须已冻结候选集)。 + execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。 + session: 可选 Session。 + + Returns: + bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 + """ + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + sess = session or db.session + if len(task_frozen_inventory_source_codes(task)) <= 1: + return False + if active_candidate_set_is_manually_pinned(task, session=sess): + return False + before = get_active_candidate_set(task) + before_set_id = int(before.id) if before is not None else None + adjudicate_and_apply_inventory_source(task, execution_id=execution_id) + sess.flush() + after = get_active_candidate_set(task) + after_set_id = int(after.id) if after is not None else None + if before_set_id == after_set_id: + return False + from app.services.shipping_notice.tool_common import log_task_event + + log_task_event( + task, + 'inventory_candidates_refreshed', + { + 'scope': 'task', + 'previous_set_id': before_set_id, + 'new_set_id': after_set_id, + 'source_codes': task_frozen_inventory_source_codes(task), + }, + source='system', + ) + return True + + +def refresh_line_candidates_from_current_routing( + task: ShippingNotice, + *, + line_no: int, + execution_id: int | None = None, + session: Session | None = None, +) -> bool: + """ + 行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。 + 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带 + line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。 + + 核心逻辑: + [守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。 + [守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。 + [STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False), + evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经 + get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义); + 仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。 + [STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承 + (保留既有行候选,不做整单重路由)。 + [STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版 + 候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。 + + Args: + task: 当前 ShippingOrderTask(须已冻结候选集)。 + line_no: 目标订单项次(1 基,对应冻结快照 line_no)。 + execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。 + session: 可选 Session。 + + Returns: + bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 + """ + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, + ) + from app.services.shipping_notice.inventory_source_rules import ( + _task_routing_lines, + compute_routing_fingerprint, + evaluate_inventory_source_rules, + extract_routing_context, + ) + + sess = session or db.session + active_set = get_active_candidate_set(task) + if active_set is None: + return False + if active_candidate_set_is_manually_pinned(task, session=sess): + return False + existing_lines = { + int(row.line_no): row + for row in (active_set.lines or []) + if getattr(row, 'line_no', None) is not None + } + target = existing_lines.get(int(line_no)) + if target is None: + return False + current_codes = [ + str(code).strip().upper() + for code in (target.source_codes_json or []) + if str(code or '').strip() + ] + if len(current_codes) <= 1: + return False + + routing_lines = _task_routing_lines(task) + position = int(line_no) - 1 + if position < 0 or position >= len(routing_lines): + return False + line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position]) + line_status = str(getattr(line_result, 'status', '') or '').strip().lower() + if line_status not in {'resolved', 'ambiguous'}: + return False + new_codes: list[str] = [] + for raw in (getattr(line_result, 'source_codes', None) or []): + code = str(raw or '').strip().upper() + if code and code not in new_codes and get_database_inventory_source(code) is not None: + new_codes.append(code) + if not new_codes: + return False + + line_projections: list[dict[str, Any]] = [] + union_codes: list[str] = [] + for row_line_no in sorted(existing_lines): + row = existing_lines[row_line_no] + codes = ( + new_codes + if row_line_no == int(line_no) + else [ + str(code).strip().upper() + for code in (row.source_codes_json or []) + if str(code or '').strip() + ] + ) + for code in codes: + if code not in union_codes: + union_codes.append(code) + line_projections.append({ + 'line_no': row_line_no, + 'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None, + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'candidate_inventory_source_codes': codes, + }) + if not union_codes: + return False + + context = extract_routing_context(task) + adjudication = InventorySourceAdjudication( + status='candidates_frozen', + method='line_refresh_reroute', + source_code=None, + connector_type=None, + warehouse_id=None, + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[{'source_code': code} for code in union_codes], + evidence=[{ + 'line_candidates_refresh': { + 'line_no': int(line_no), + 'previous_codes': current_codes, + 'new_codes': new_codes, + }, + }], + reason='line_refresh_reroute', + ) + freeze_result = freeze_candidates_for_task( + task, + adjudication=adjudication, + line_projections=line_projections, + execution_id=execution_id, + session=sess, + ) + if not freeze_result.created_new: + return False + from app.services.shipping_notice.tool_common import log_task_event + + log_task_event( + task, + 'inventory_candidates_refreshed', + { + 'scope': 'line', + 'line_no': int(line_no), + 'previous_codes': current_codes, + 'new_codes': new_codes, + 'new_set_id': int(freeze_result.candidate_set_id), + }, + source='system', + ) + return True +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: PASS(10 passed) + +- [ ] **Step 5: 暂存** + +```bash +git add backend/app/services/shipping_notice/inventory_candidate_freeze_service.py backend/tests/test_shipping_refresh_inventory_candidates.py +``` + +--- + +### Task 2: 执行器前置步骤(任务级+行级挂载) + +**Files:** +- Modify: `backend/app/services/shipping_notice/process_gate_executor.py`(`_handle_retry_inventory_preparation` 内,约 928-952 行的 `if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:` 块内、`invalidate_inventory_downstream(...)` 调用之前插入) +- Test: `backend/tests/test_shipping_refresh_inventory_candidates.py`(追加集成用例) + +**Interfaces:** +- Consumes: Task 1 的 `refresh_candidates_from_current_routing(task, *, execution_id=None)` 与 `refresh_line_candidates_from_current_routing(task, *, line_no, execution_id=None)`;`latest_export_artifact(task)`(upload_attempt_service.py);`line_scope['line_no']`(executor 内 `_resolve_line_inventory_scope` 产物,含 `snapshot_line_id`/`line_no`/`source_codes`)。 +- Produces: 无新接口(行为变更:人工重取——任务级先整单刷新、行级先刷新目标行——再走既有失效 + `ensure_inventory(mode='retry_rpa')` 重取链)。 + +- [ ] **Step 1: 追加失败测试(同测试文件末尾)** + +```python +def _retry_payload(**overrides): + base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7} + base.update(overrides) + return base + + +def _exercise_retry_handler(monkeypatch, task, payload, *, refresh_calls, line_scope=None, excel_artifact=None): + """按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。 + + refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。 + """ + from app.services.shipping_notice import process_gate_executor as executor + + execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None) + gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout') + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task) + monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope) + monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no}) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: excel_artifact, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing', + lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing', + lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **_k: {'outcome': 'passed'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_k: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda _payload: {'status': 'ok', 'data': {}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_k: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + return executor._handle_retry_inventory_preparation( + execution=execution, gate=gate, payload=payload, + ) + + +def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch): + """[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。""" + refresh_calls = [] + outcome = _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls, + ) + assert refresh_calls and refresh_calls[0][0] == 'task' + assert refresh_calls[0][1].get('execution_id') == 5 + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'} + + +def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch): + """[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。""" + refresh_calls = [] + outcome = _exercise_retry_handler( + monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls, + line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1}, + ) + assert refresh_calls and refresh_calls[0][0] == 'line' + assert refresh_calls[0][1].get('line_no') == 1 + assert refresh_calls[0][1].get('execution_id') == 5 + assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'} + + +def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch): + """[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。""" + refresh_calls = [] + task = _task() + _exercise_retry_handler( + monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'), + refresh_calls=refresh_calls, + ) + _exercise_retry_handler( + monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls, + excel_artifact=SimpleNamespace(id=77), + ) + _exercise_retry_handler( + monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls, + line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1}, + excel_artifact=SimpleNamespace(id=77), + ) + assert not refresh_calls +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: 新增 3 例 FAIL(`refresh_calls` 为空,断言不成立);Task 1 的 10 例保持 PASS + +- [ ] **Step 3: 实现前置步骤** + +在 `_handle_retry_inventory_preparation` 中定位该块(约 928 行): + +```python + if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: +``` + +在该块内、`if payload.get('action_code') in { 'retry_inventory_preparation', ... }:` 的 `invalidate_inventory_downstream(...)` 调用**之前**插入: + +```python + # [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前 + # 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。 + # 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方 + # 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」 + # 即可让新源进入取数与匹配范围,无需重建订单。 + # 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新; + # 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走 + # override_line_inventory_source)。 + if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation': + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + if latest_export_artifact(task) is None: + from app.services.shipping_notice.inventory_candidate_freeze_service import ( + refresh_candidates_from_current_routing, + refresh_line_candidates_from_current_routing, + ) + + if line_scope is None: + refresh_candidates_from_current_routing(task, execution_id=int(execution.id)) + else: + refresh_line_candidates_from_current_routing( + task, line_no=int(line_scope['line_no']), execution_id=int(execution.id), + ) +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: PASS(13 passed) + +- [ ] **Step 5: 回归相邻测试面(轮询语义与覆写动作不受影响)** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py tests/test_shipping_line_source_ambiguity.py -q` +Expected: PASS(如遇与本改动无关的既有 WIP 失败,记录并对照 `git stash` 验证,不得顺手修改) + +- [ ] **Step 6: 暂存** + +```bash +git add backend/app/services/shipping_notice/process_gate_executor.py backend/tests/test_shipping_refresh_inventory_candidates.py +``` + +--- + +### Task 3: 前端下拉合并(候选置顶 + 全量源兜底) + +**Files:** +- Create: `frontend/src/features/chat/shipping/inlineSourceOptions.ts` +- Create: `frontend/src/features/chat/shipping/inlineSourceOptions.test.ts` +- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(`inlineSourceOptions` 函数改约 3053-3068 行;删除仅被其使用的 `lineSourceOptionLabel` 约 2657-2661 行与 `overrideSourceOptionLabel` 约 2666-2668 行) + +**Interfaces:** +- Consumes: `formSourceOptions`(视图已有 computed,来自 `ui_state.stage_context.preparation.source_options`);行投影字段 `source_ambiguous` / `source_candidates`。 +- Produces: `mergeInlineSourceOptions(line: InlineSourceLine, enabledSources: ReadonlyArray): InlineSourceOption[]`(纯函数,供视图 `inlineSourceOptions` 委托)。 + +- [ ] **Step 1: 写失败测试(新建 spec,命名对齐同目录 `shippingText.test.ts`)** + +```ts +/** + * features/chat/shipping/inlineSourceOptions.test.ts + * + * 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。 + * 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。 + * 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。 + */ +import { describe, expect, it } from 'vitest'; +import { mergeInlineSourceOptions } from './inlineSourceOptions'; + +describe('mergeInlineSourceOptions', () => { + it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] }, + [{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual([ + 'DSV360_AWSCV', + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSDU', + ]); + }); + + it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] }, + [{ source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']); + }); + + it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true }, + [{ source_code: 'dsv360_awssg' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']); + }); + + it('两侧皆空返回空数组(调用方据此回退文本展示)', () => { + expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]); + }); +}); +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts` +Expected: FAIL(Cannot find module './inlineSourceOptions') + +- [ ] **Step 3: 实现纯函数(新建 `inlineSourceOptions.ts`)** + +```ts +/** + * features/chat/shipping/inlineSourceOptions.ts + * + * 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。 + * 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。 + * 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源 + * (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开 + * 「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。 + */ + +/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */ +export interface InlineSourceOption { + value: string; + label: string; +} + +/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */ +export interface InlineSourceLine { + source_ambiguous?: boolean; + source_candidates?: Array; +} + +/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */ +export interface EnabledSourceOption { + source_code?: string | null; +} + +/** + * 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。 + * @param line - 准备行(读 source_ambiguous / source_candidates) + * @param enabledSources - 后端下发的全部已启用库存源(保持后端排序) + * @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示) + */ +export function mergeInlineSourceOptions( + line: InlineSourceLine, + enabledSources: ReadonlyArray, +): InlineSourceOption[] { + const merged = new Map(); + if (line.source_ambiguous) { + for (const raw of line.source_candidates || []) { + const code = String(raw || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + } + for (const source of enabledSources) { + const code = String(source.source_code || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + return [...merged.values()]; +} +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts` +Expected: PASS(4 passed) + +- [ ] **Step 5: 视图接入(`ShippingOrderReviewView.vue`)** + +1. 在既有 `../shipping/` 相对导入区追加: +```ts +import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions'; +``` +2. 将 `inlineSourceOptions`(约 3053-3068 行)整体替换为: +```ts +/** + * 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。 + * 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。 + */ +function inlineSourceOptions(line: { + source_ambiguous?: boolean; + source_candidates?: Array; +}): Array<{ value: string; label: string }> { + return mergeInlineSourceOptions(line, formSourceOptions.value); +} +``` +3. 删除 `lineSourceOptionLabel`(约 2657-2661 行)与 `overrideSourceOptionLabel`(约 2666-2668 行)及其注释——二者仅被旧 `inlineSourceOptions` 使用,删除后全仓无引用(`formSourceOptions` computed 保留,仍在使用)。 + +- [ ] **Step 6: 全量验证(受影响 spec + 构建)** + +Run: `cd frontend && npx vitest run src/features/chat/views/ShippingOrderReviewView.spec.ts && npm run build` +Expected: vitest PASS(既有 108+ 用例不回归);build 成功 + +- [ ] **Step 7: 暂存** + +```bash +git add frontend/src/features/chat/shipping/inlineSourceOptions.ts frontend/src/features/chat/shipping/inlineSourceOptions.test.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue +``` + +--- + +### Task 4: i18n 提示文案 + 文档同步 + +**Files:** +- Modify: `frontend/src/locales/zh-CN/chat.json`、`frontend/src/locales/zh-TW/chat.json`、`frontend/src/locales/en/chat.json`、`frontend/src/locales/th/chat.json`(各 1 处 `diagnosisInventoryRpaAdvice`) +- Modify: `docs/features/shipping-notice/technical.md`(末尾追加章节)、`docs/funclist.md`(shipping-notice 表追加 1 行) + +**Interfaces:** +- Consumes: Task 1/2 的后端行为语义(任务级+行级刷新前置)。 +- Produces: 四语言一致的提示文案;文档与代码一致(AGENTS §9)。 + +- [ ] **Step 1: 四语言更新 `diagnosisInventoryRpaAdvice`(键已在四语言存在,只改值)** + +- `zh-CN`(约 689 行): +```json +"diagnosisInventoryRpaAdvice": "建议先重新获取库存(将按最新主数据重新裁决候选源:任务级整单重判、行级仅重评该行);若外部系统不可用,可人工上传库存文件。" +``` +- `zh-TW`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "建議先重新獲取庫存(將依最新主檔重新裁決候選來源:任務級整單重判、行級僅重評該行);若外部系統不可用,可人工上傳庫存檔。" +``` +- `en`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "Retry inventory fetch first (candidate sources are re-adjudicated against the latest master data: task-level re-routes the whole order, line-level re-evaluates only that line); if the external system is unavailable, upload an inventory file manually." +``` +- `th`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "ลองดึงสต็อกใหม่ก่อน (ระบบจะประเมินแหล่งสต็อกที่เป็นไปได้ใหม่ตามข้อมูลหลักล่าสุด: ระดับงานประเมินทั้งใบสั่ง ระดับบรรทัดประเมินเฉพาะบรรทัดนั้น) หากระบบภายนอกใช้ไม่ได้ ให้อัปโหลดไฟล์สต็อกด้วยตนเอง" +``` + +- [ ] **Step 2: 构建验证(JSON 合法性由 build 兜底)** + +Run: `cd frontend && npm run build` +Expected: 成功 + +- [ ] **Step 3: `docs/features/shipping-notice/technical.md` 末尾追加(只追加,不改既有内容)** + +```markdown +## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等) + +**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的 +取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源, +通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断 +(prod 实例 SORC-E19FE1B9AB8F4FD2)。 + +**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前 +新增幂等前置刷新,任务级与行级共用守卫红线: +- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source` + 整单重判候选集。 +- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评 + (`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source` + 启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后 + `freeze_candidates_for_task` 重冻结,其余行原样继承。 +- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时 + 由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有 + `invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。 +- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走 + `override_line_inventory_source`;候选集含人工选源(frozen_by_id / + candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新; + 轮询/自动首投/`retry_inventory_from_preparation` 不刷新。 +- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源 + 去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写 + 动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。 + +**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed` +(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。 +``` + +- [ ] **Step 4: `docs/funclist.md` shipping-notice 表追加 1 行** + +在货代发货通知功能清单表(`### 货代发货通知(shipping-notice)`,3 列:功能项 | 状态 | 说明)末尾追加: + +```markdown +| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 | +``` + +- [ ] **Step 5: 暂存** + +```bash +git add frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json docs/features/shipping-notice/technical.md docs/funclist.md +``` + +--- + +## 任务依赖与验证总览 + +- Task 1 → Task 2(执行器消费两个 helper);Task 3、Task 4 相互独立,可并行。 +- 全部完成后整体回归:`cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py -q` + `cd frontend && npm run build`。 +- 人工冒烟(部署 dev 后):多候选缺口单——任务级「重新获取库存(RPA)」→ 整单候选按当前主数据重判;行级「重新获取库存(RPA)」→ 仅该行候选重评;两者在主数据无变化时行为与升级前一致;管理端启用新源后再点 → 新源进入对应范围。 diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index 4b7ef7b8..a879ed9a 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -90,6 +90,13 @@ export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILI */ export const PROGRESS_POLL_MS = 5000; +/** + * waiting_human / failed 的降频保活间隔。两者不是不可逆终态:自愈回收、 + * RPA 回调仍会把任务继续推进(历史缺陷:一帧停死令界面永久冻结在旧阶段), + * 降频而非停转,状态回到活跃态自动恢复基础间隔。 + */ +export const PROGRESS_POLL_IDLE_MS = 15000; + /** / Case */ export type DraftVersionConflict = { localVersion: number; @@ -449,6 +456,7 @@ export function useShippingOrderReview(options: { // 浏览器端 window.setInterval 返回 number;勿用 ReturnType, // 其在 @types/node 与 DOM lib 混用时会解析为 NodeJS.Timeout 导致 TS2322。 let progressPollTimer: number | null = null; + let progressPollIntervalMs = PROGRESS_POLL_MS; let stpCreatePollTimer: number | null = null; let reparseCaseRefreshTimer: number | null = null; @@ -639,15 +647,17 @@ export function useShippingOrderReview(options: { if (!authoritativeOrderTaskNo.value && !targetRunNo) return; showWorkflowProgress.value = true; workflowProgressPolling.value = true; - // RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。 - // 等待人工(waiting_human,即“中断”)视为线性终态:结果不会自行变化,继续轮询浪费资源。 - // 注意:统一投影的用户态值是 waiting_human(旧字段是 needs_human),若沿用旧的 - // needs_human 会让已中断任务永远匹配不到终态、一直空转轮询;failed 同理是停止状态。 - // 可重试失败(retryable)不在此列,需保留轮询以便后续成功回调自动刷新工作流。 - const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'waiting_human', 'failed']); + // RPA 超时、可重试失败、人工复核与自愈回收都可能被后续回调推进,页面留存期间持续 + // 读取 Projection。completed/cancelled 是不可逆终态,命中即停;waiting_human/failed + // 不是终态(自愈回收、回调仍会推进),历史缺陷是一帧停死令界面永久冻结在旧阶段—— + // 改为降频保活,状态回到活跃态自动恢复基础间隔。 + const WORKFLOW_STOP_STATUSES = new Set(['completed', 'cancelled']); + const WORKFLOW_SLOW_STATUSES = new Set(['waiting_human', 'failed']); let lastUnifiedStatus = ''; let lastLifecycleFingerprint = ''; - const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']); + // Run 级 partially_completed 只代表解析阶段收尾,OT 随后仍会被 STP 建单产出; + // 命中即停会令提交订单后的轮询在 OT 诞生前死亡(历史缺陷),同样只降频不停转。 + const RUN_STOP_STATUSES = new Set(['completed', 'cancelled']); const tick = async () => { // 页面不可见时暂停轮询(返回前台后下一拍自动恢复),避免后台标签持续占用服务端。 if (typeof document !== 'undefined' && document.hidden) return; @@ -677,10 +687,13 @@ export function useShippingOrderReview(options: { // 否则提交订单后秒级阻断时五阶段条卡在订单复核、自动跳转永不触发。 await refreshActiveAutomationLifecycle(); } - if (UNIFIED_TERMINAL.has(unifiedStatus)) { + if (WORKFLOW_STOP_STATUSES.has(unifiedStatus)) { stopWorkflowProgressPolling(); return; } + ensureWorkflowProgressInterval( + WORKFLOW_SLOW_STATUSES.has(unifiedStatus) ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS, + ); return; } if (targetRunNo) { @@ -695,15 +708,26 @@ export function useShippingOrderReview(options: { userTaskNo: reviewProgressContext.value?.user_task_no, }); if (synthesized) reviewProgressContext.value = synthesized; - if (RUN_TERMINAL.has(String(run.status || '').trim())) { + const runStatus = String(run.status || '').trim(); + if (RUN_STOP_STATUSES.has(runStatus)) { stopWorkflowProgressPolling(); + return; } + ensureWorkflowProgressInterval(runStatus === 'failed' ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS); } } catch { /* */ } }; + // 状态分级轮询:活跃态基础间隔;waiting_human/failed 降频保活。间隔变化才重建定时器。 + const ensureWorkflowProgressInterval = (intervalMs: number) => { + if (progressPollTimer != null && progressPollIntervalMs === intervalMs) return; + if (progressPollTimer != null) window.clearInterval(progressPollTimer); + progressPollIntervalMs = intervalMs; + progressPollTimer = window.setInterval(() => { void tick(); }, intervalMs); + }; void tick(); + progressPollIntervalMs = PROGRESS_POLL_MS; progressPollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS); }; diff --git a/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts b/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts new file mode 100644 index 00000000..160fcb61 --- /dev/null +++ b/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts @@ -0,0 +1,43 @@ +/** + * features/chat/shipping/inlineSourceOptions.test.ts + * + * 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。 + * 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。 + * 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。 + */ +import { describe, expect, it } from 'vitest'; +import { mergeInlineSourceOptions } from './inlineSourceOptions'; + +describe('mergeInlineSourceOptions', () => { + it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] }, + [{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual([ + 'DSV360_AWSCV', + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSDU', + ]); + }); + + it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] }, + [{ source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']); + }); + + it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true }, + [{ source_code: 'dsv360_awssg' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']); + }); + + it('两侧皆空返回空数组(调用方据此回退文本展示)', () => { + expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]); + }); +}); diff --git a/frontend/src/features/chat/shipping/inlineSourceOptions.ts b/frontend/src/features/chat/shipping/inlineSourceOptions.ts new file mode 100644 index 00000000..a6ce7fb9 --- /dev/null +++ b/frontend/src/features/chat/shipping/inlineSourceOptions.ts @@ -0,0 +1,50 @@ +/** + * features/chat/shipping/inlineSourceOptions.ts + * + * 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。 + * 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。 + * 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源 + * (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开 + * 「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。 + */ + +/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */ +export interface InlineSourceOption { + value: string; + label: string; +} + +/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */ +export interface InlineSourceLine { + source_ambiguous?: boolean; + source_candidates?: Array; +} + +/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */ +export interface EnabledSourceOption { + source_code?: string | null; +} + +/** + * 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。 + * @param line - 准备行(读 source_ambiguous / source_candidates) + * @param enabledSources - 后端下发的全部已启用库存源(保持后端排序) + * @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示) + */ +export function mergeInlineSourceOptions( + line: InlineSourceLine, + enabledSources: ReadonlyArray, +): InlineSourceOption[] { + const merged = new Map(); + if (line.source_ambiguous) { + for (const raw of line.source_candidates || []) { + const code = String(raw || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + } + for (const source of enabledSources) { + const code = String(source.source_code || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + return [...merged.values()]; +} diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index e0bf26da..bcabd5b1 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -922,6 +922,8 @@ export interface ShippingTaskSummary { owner_agent_id?: number | null; /** 当前用户是否可写;管理员查看他人任务时为 false */ can_handle?: boolean; + /** 当前用户是否可下载正式 Excel(与导出端点同一谓词:创建者或管理员) */ + can_download_export?: boolean; /** 统一 ShippingProcessing status(列表轮询优先读此字段)。 */ shipping_processing_status?: string | null; /** 统一 ShippingProcessing stage(任务中心紧凑进度)。 */ diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index 26b2b648..1a33949a 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -52,6 +52,7 @@ import { resolveExtractionActivityMessage, resolveRunLifecycleUserStatus, } from '../shipping/shippingProcessingLabels'; +import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions'; import ReviewActionConfirmDialog, { type ReviewConfirmAction, type ReviewConfirmPayload, @@ -2654,20 +2655,9 @@ const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationCo /** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交 * (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */ -/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */ -function lineSourceOptionLabel(code: string): string { - // 兜底:只会展示源编码(如 DSV360_AWSSG),不展示冗长显示名。 - return String(code || '').trim().toUpperCase(); -} - /** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */ const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []); -function overrideSourceOptionLabel(code: string): string { - // 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。 - return String(code || '').trim().toUpperCase(); -} - /** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */ const formalPreparationOdmColumnVisible = computed(() => (formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1), @@ -3051,20 +3041,14 @@ function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean { } /** - * 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源; + * 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。 * 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。 */ function inlineSourceOptions(line: { source_ambiguous?: boolean; source_candidates?: Array; }): Array<{ value: string; label: string }> { - if (line.source_ambiguous && (line.source_candidates?.length || 0) > 0) { - return (line.source_candidates || []).map((code) => ({ value: String(code), label: lineSourceOptionLabel(String(code)) })); - } - if (formSourceOptions.value.length) { - return formSourceOptions.value.map((s) => ({ value: String(s.source_code), label: overrideSourceOptionLabel(String(s.source_code)) })); - } - return []; + return mergeInlineSourceOptions(line, formSourceOptions.value); } /** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */ @@ -3516,9 +3500,11 @@ async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') { if (action === 'download') { await downloadWorkspaceShippingNoticeExportArchive(selectedFreightBusinessNos.value); } else if (action === 'confirm') { - await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value); + const summary = await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value); + warnBlockedFreightNoticeResults(summary.results); } else { - await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value); + const summary = await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value); + warnBlockedFreightNoticeResults(summary.results); } // 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。 if (action === 'confirm' || action === 'rpa') { @@ -3554,9 +3540,11 @@ async function runFreightNoticeAction( freightBatchBusy.value = action; try { if (action === 'confirm') { - await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]); + const summary = await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]); + warnBlockedFreightNoticeResults(summary.results); } else if (action === 'rpa') { - await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]); + const summary = await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]); + warnBlockedFreightNoticeResults(summary.results); } else { if (String(formalTaskDetail.value?.business_no || '').trim() !== group.business_no) return; await submitFormalGateAction('regenerate_excel_artifact'); @@ -3577,6 +3565,25 @@ async function runFreightNoticeAction( } } +/** + * 批量 RPA/确认结果逐单消费:被拦截项的原因必须浮出。 + * 核心逻辑:批量接口恒返回 202 成功 envelope,逐单 blocked 藏在 results 里 + * (历史缺陷:前端不检查,界面零反馈,用户以为点击无效——如「库存源尚未确定」)。 + * blocked 携带后端本地化 message(AppError 在顶层、tool_response 在 result 内), + * 去重后合并为一条 warning;accepted 项的状态推进由既有投影刷新呈现。 + * @param results - 批量接口返回的逐单结果数组。 + */ +function warnBlockedFreightNoticeResults(results: Array> | undefined): void { + const reasons = new Set(); + for (const item of results || []) { + if (String(item?.status || '') !== 'blocked') continue; + const detail = item as { message?: unknown; code?: unknown; result?: { message?: unknown } }; + const reason = String(detail.message || detail.result?.message || detail.code || '').trim(); + if (reason) reasons.add(reason); + } + if (reasons.size) msg.warning(Array.from(reasons).join(';')); +} + /** 当前任务的 Excel 重生只可映射到其自身 business_no,禁止跨 PO/通知单展示。 */ function canRegenerateFreightNotice(group: ShippingFreightNoticeGroup): boolean { return canRunFreightNoticeAction(group, 'regenerate_excel_artifact') diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts index 2ed380fd..b1e02b10 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts @@ -147,6 +147,8 @@ function notice(businessNo: string, poNumber: string, partNumber: string) { id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo, item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave', po_number: poNumber, customer_name: 'Customer', upload_status: 'pending', + // 后端 SUMMARY 契约:下载能力与导出端点同一谓词(创建者或管理员)。 + can_download_export: true, ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] }, notice_line_summary: [ { line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }, diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue index 86ceccde..14adec40 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue @@ -38,7 +38,7 @@ import { useShippingTodoBadge } from '../composables/useShippingTodoBadge'; import { useMessage } from '@/shared/composables/useMessage'; import { BusinessError } from '@/shared/api/client'; import { - isFreightUploadRow, + isBatchDownloadableRow, lifecycleStageCodeOf, todoItemKey, type LifecycleStageCode, @@ -134,8 +134,8 @@ const filteredTasks = computed(() => ( ? tasks.value : tasks.value.filter((item) => lifecycleStageCodeOf(item) === lifecycleStageFilter.value) )); -/** 批量可选行:货代上传阶段的正式 Notice(业务约束:批量仅该阶段可用)。 */ -const selectableRows = computed(() => filteredTasks.value.filter((item) => isFreightUploadRow(item))); +/** 批量可选行:货代上传阶段的正式 Notice 且当前用户可下载(与批量导出端点同口径)。 */ +const selectableRows = computed(() => filteredTasks.value.filter((item) => isBatchDownloadableRow(item))); const selectedBusinessNoSet = computed(() => new Set(selectedBusinessNos.value)); /** 当前桶是否为通知完成明细报表视图。 */ @@ -366,7 +366,7 @@ async function loadTodos(resetPage = false, options?: { silent?: boolean }) { tasks.value = result.items || []; const visibleBusinessNos = new Set( tasks.value - .filter((item) => isFreightUploadRow(item)) + .filter((item) => isBatchDownloadableRow(item)) .map((item) => String(item.business_no || '').trim()), ); selectedBusinessNos.value = selectedBusinessNos.value.filter((value) => visibleBusinessNos.has(value)); diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue index 5a269e8d..4ea27178 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue @@ -137,6 +137,9 @@ const exportFileName = computed(() => String( props.item?.artifact_summary?.export_file_name || '', )); +/** 下载能力由后端统一谓词下发(创建者或管理员);缺失按不可下载处理。 */ +const canDownloadExport = computed(() => props.item?.can_download_export === true); + const lineRows = computed(() => { const item = props.item as ShippingTaskSummary | null; return Array.isArray(item?.notice_line_summary) ? item!.notice_line_summary : []; @@ -376,7 +379,7 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onEsc)); {{ $t('chat.shippingOrderReview.autoProgress.retryStp') }} (); const selectedSet = computed(() => new Set(props.selectedBusinessNos || [])); -const selectableRows = computed(() => props.items.filter((item) => isFreightUploadRow(item))); +/** 复选框与全选状态消费同一可下载谓词,保证"能勾的都能下单成功"。 */ +const selectableRows = computed(() => props.items.filter((item) => isBatchDownloadableRow(item))); const hasSelection = computed(() => (props.selectedBusinessNos?.length || 0) > 0); const allSelectableChecked = computed(() => ( selectableRows.value.length > 0 @@ -158,7 +159,7 @@ function onToggleAll(): void { > Date: Tue, 13 Oct 2026 08:45:24 +0800 Subject: [PATCH 16/32] =?UTF-8?q?fix:=20=E8=AE=BE=E5=A4=87=E9=AA=8C?= =?UTF-8?q?=E6=94=B6=E9=A2=84=E8=AD=A6=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/api/equipment_acceptance/__init__.py | 28 +- backend/app/models/__init__.py | 2 + backend/app/models/equipment_acceptance.py | 29 +- .../equipment_acceptance/alert_notice.py | 90 ++++++ .../equipment_acceptance/alert_plan.py | 17 +- .../equipment_acceptance/alert_service.py | 273 ++++++++++++++--- .../equipment_acceptance/config_service.py | 55 +++- .../send_record_service.py | 117 +++++++- ...1f2_add_equipment_acceptance_send_files.py | 97 ++++++ .../test_equipment_acceptance_alert_notice.py | 58 ++++ .../test_equipment_acceptance_alert_plan.py | 1 + .../tests/test_equipment_acceptance_config.py | 18 +- docs/demand.md | 2 +- .../config-redesign-preview.html | 14 +- .../equipment-acceptance-warning/demand.md | 4 +- .../send-redesign-preview.html | 279 ++++++++++++++++++ .../equipment-acceptance-warning/technical.md | 6 +- docs/funclist.md | 6 +- .../api/equipment-acceptance.api.ts | 40 ++- .../views/EquipmentAcceptanceConfigPage.vue | 273 ++++++++++------- .../views/EquipmentAcceptanceSendsPage.vue | 106 ++++++- frontend/src/locales/en/admin.json | 19 +- frontend/src/locales/th/admin.json | 19 +- frontend/src/locales/zh-CN/admin.json | 19 +- frontend/src/locales/zh-TW/admin.json | 19 +- 25 files changed, 1398 insertions(+), 193 deletions(-) create mode 100644 backend/app/services/equipment_acceptance/alert_notice.py create mode 100644 backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py create mode 100644 backend/tests/test_equipment_acceptance_alert_notice.py create mode 100644 docs/features/equipment-acceptance-warning/send-redesign-preview.html diff --git a/backend/app/api/equipment_acceptance/__init__.py b/backend/app/api/equipment_acceptance/__init__.py index 61611cce..e108908b 100644 --- a/backend/app/api/equipment_acceptance/__init__.py +++ b/backend/app/api/equipment_acceptance/__init__.py @@ -3,12 +3,14 @@ backend/app/api/equipment_acceptance/__init__.py 用途:设备验收预警的 Chat 作业面接口。 依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。 -逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。 +逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。 """ from __future__ import annotations -from flask import Blueprint, g, request +from io import BytesIO + +from flask import Blueprint, g, request, send_file from app.core.auth.jwt import get_current_user from app.core.errors import ForbiddenError, UnauthorizedError @@ -19,7 +21,7 @@ from app.services.equipment_acceptance.config_service import ( save_acceptance_config, ) from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts -from app.services.equipment_acceptance.send_record_service import list_send_records +from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records from app.services.equipment_acceptance.sync_service import ( get_acceptance_order, list_acceptance_orders, @@ -157,6 +159,26 @@ def send_equipment_acceptance_alerts(): return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None)) +@equipment_acceptance_bp.route("/send-files", methods=["GET"]) +def list_equipment_acceptance_send_files(): + """列出最近按收件人归档的 Excel。不含文件字节。""" + _require_equipment_acceptance_access() + return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None)) + + +@equipment_acceptance_bp.route("/send-files//excel", methods=["GET"]) +def download_equipment_acceptance_send_file(file_id: int): + """下载一份当时发给收件人的设备验收预警 Excel。""" + _require_equipment_acceptance_access() + row = get_send_file(file_id) + return send_file( + BytesIO(row.excel_file_data), + as_attachment=True, + download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx", + mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + + @equipment_acceptance_bp.route("/sends", methods=["GET"]) def list_equipment_acceptance_sends(): """分页查看发送记录。扫描写入后这里才有行。""" diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index e1704f81..34bd23d1 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -242,6 +242,7 @@ from app.models.equipment_acceptance import ( EquipmentAcceptanceNode, EquipmentAcceptanceOperator, EquipmentAcceptanceOrder, + EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord, EquipmentAcceptanceSetting, ) @@ -445,6 +446,7 @@ __all__ = [ 'EquipmentAcceptanceNode', 'EquipmentAcceptanceOperator', 'EquipmentAcceptanceSetting', + 'EquipmentAcceptanceSendFile', 'EquipmentAcceptanceSendRecord', 'TransferRun', 'TransferSourceJob', diff --git a/backend/app/models/equipment_acceptance.py b/backend/app/models/equipment_acceptance.py index fdf90bd8..1483797f 100644 --- a/backend/app/models/equipment_acceptance.py +++ b/backend/app/models/equipment_acceptance.py @@ -4,8 +4,9 @@ backend/app/models/equipment_acceptance.py 用途:设备验收预警的本地同步快照和可改配置。 依赖:models.base.Base、users。 逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。 -配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。 +配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。 发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。 +发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。 不保存流程编号、第二合同编号、验收日期和 isremark。 """ @@ -14,7 +15,7 @@ from __future__ import annotations from datetime import datetime from typing import Optional -from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint +from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base @@ -116,6 +117,7 @@ class EquipmentAcceptanceSetting(Base): day_2: Mapped[int] = mapped_column(nullable=False, default=37) day_3: Mapped[int] = mapped_column(nullable=False, default=44) day_4: Mapped[int] = mapped_column(nullable=False, default=51) + round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) buyer_manager_user_id: Mapped[Optional[int]] = mapped_column( ForeignKey("users.id", ondelete="SET NULL"), nullable=True ) @@ -154,3 +156,26 @@ class EquipmentAcceptanceSendRecord(Base): sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False) + + +class EquipmentAcceptanceSendFile(Base): + """一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。""" + + __tablename__ = "equipment_acceptance_send_files" + __table_args__ = ( + Index("ix_equipment_acceptance_send_files_created", "created_at"), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + recipient_user_id: Mapped[Optional[int]] = mapped_column( + ForeignKey("users.id", ondelete="SET NULL"), nullable=True + ) + recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True) + excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True) + send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent") + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False) diff --git a/backend/app/services/equipment_acceptance/alert_notice.py b/backend/app/services/equipment_acceptance/alert_notice.py new file mode 100644 index 00000000..7fa232ea --- /dev/null +++ b/backend/app/services/equipment_acceptance/alert_notice.py @@ -0,0 +1,90 @@ +""" +backend/app/services/equipment_acceptance/alert_notice.py + +用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。 +依赖:openpyxl。 +逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。 +""" + +from __future__ import annotations + +from io import BytesIO +from typing import Any + +from openpyxl import Workbook +from openpyxl.styles import Font + +NOTICE_HEADERS = ( + "验收单号", + "采购单号", + "申请人", + "轮次", + "停留天数", + "当前节点", + "当前处理人", + "通知身份", +) +NOTICE_FILE_NAME = "设备验收停留提醒.xlsx" + + +def summary_message(lines: list[dict[str, Any]]) -> str: + """ + 拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。 + + 核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。 + Args: + lines: 已按发送记录去重的明细。每项含 threshold_days。 + Returns: + 卡片正文。没有明细时仍返回可发送的空汇总。 + """ + counts: dict[int, int] = {} + order: list[int] = [] + for line in lines: + day = int(line.get("threshold_days") or 0) + if day not in counts: + order.append(day) + counts[day] = 0 + counts[day] += 1 + detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无" + return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。" + + +def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes: + """ + 生成这名收件人的验收停留明细。 + + 核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。 + Args: + lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。 + Returns: + xlsx 字节。 + """ + workbook = Workbook() + sheet = workbook.active + sheet.title = "停留提醒" + sheet.append(list(NOTICE_HEADERS)) + for cell in sheet[1]: + cell.font = Font(bold=True) + for line in lines: + dwell = line.get("dwell_days") + sheet.append([ + _cell(line.get("acceptance_no")), + _cell(line.get("purchase_order_no")), + _cell(line.get("applicant")), + f"超过 {int(line.get('threshold_days') or 0)} 天", + "—" if dwell is None or dwell == "" else dwell, + _cell(line.get("node_name")), + _cell(line.get("handlers")), + _cell(line.get("identity")), + ]) + sheet.freeze_panes = "A2" + sheet.auto_filter.ref = sheet.dimensions + output = BytesIO() + workbook.save(output) + return output.getvalue() + + +def _cell(value: Any) -> str: + """空值写成横线,避免 Excel 里出现空白列。""" + text = str(value or "").strip() + return text or "—" diff --git a/backend/app/services/equipment_acceptance/alert_plan.py b/backend/app/services/equipment_acceptance/alert_plan.py index 9f7122f9..26655928 100644 --- a/backend/app/services/equipment_acceptance/alert_plan.py +++ b/backend/app/services/equipment_acceptance/alert_plan.py @@ -11,20 +11,31 @@ from __future__ import annotations from typing import Any -def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]: +def due_tiers( + dwell_days: int | None, + thresholds: tuple[int, int, int, int], + *, + max_tier: int = 4, +) -> list[int]: """ 按累计天数给出已经跨过的档位。 核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。 + 第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。 Args: dwell_days: 签核自然日。没有计时起点时为空。 thresholds: 四个天数,对应第 1 到第 4 档。 + max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。 Returns: - 档位号 1 到 4 的列表。没有跨档时为空。 + 档位号列表。没有跨档时为空。 """ if dwell_days is None: return [] - return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day] + return [ + index + 1 + for index, day in enumerate(thresholds) + if dwell_days > day and index + 1 <= max_tier + ] def make_person( diff --git a/backend/app/services/equipment_acceptance/alert_service.py b/backend/app/services/equipment_acceptance/alert_service.py index fc86e93c..f0f521b5 100644 --- a/backend/app/services/equipment_acceptance/alert_service.py +++ b/backend/app/services/equipment_acceptance/alert_service.py @@ -2,8 +2,9 @@ backend/app/services/equipment_acceptance/alert_service.py 用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。 -依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。 -逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。 +依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。 +逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。 +周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。 """ from __future__ import annotations @@ -11,15 +12,23 @@ from __future__ import annotations import logging from datetime import datetime from typing import Any +from zoneinfo import ZoneInfo from app.extensions import db from app.models.equipment_acceptance import ( + EquipmentAcceptanceNode, EquipmentAcceptanceOperator, EquipmentAcceptanceOrder, + EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord, EquipmentAcceptanceSetting, ) from app.models.user import User +from app.services.equipment_acceptance.alert_notice import ( + NOTICE_FILE_NAME, + build_notice_workbook, + summary_message, +) from app.services.equipment_acceptance.alert_plan import ( assemble_tier, due_tiers, @@ -27,7 +36,7 @@ from app.services.equipment_acceptance.alert_plan import ( resolve_account, resolve_configured_user, ) -from app.services.equipment_acceptance.config_service import reminder_days +from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days from app.services.equipment_acceptance.snapshot_rules import WATCHING _LOGGER = logging.getLogger(__name__) @@ -61,7 +70,7 @@ def refresh_pending_alerts( """ 按本地快照刷新待发送记录。 - 核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。 + 核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。 未计时或已停表的单据,把还没发出的记录改成已取消。 Args: directory: 测试注入的人员目录和经副理。空则查询 E10。 @@ -74,6 +83,7 @@ def refresh_pending_alerts( users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies)) roles = _configured_users() thresholds = reminder_days() + max_tier = 4 if is_round_4_enabled() else 3 existing = { (row.order_id, row.tier): row for row in db.session.query(EquipmentAcceptanceSendRecord).all() @@ -86,7 +96,16 @@ def refresh_pending_alerts( if order.monitor_status != WATCHING: cancelled += cancel_unsent(order.id) continue - for draft in _drafts(order, operators.get(order.id, []), people, deputies, users_by_job, roles, thresholds): + for draft in _drafts( + order, + operators.get(order.id, []), + people, + deputies, + users_by_job, + roles, + thresholds, + max_tier=max_tier, + ): current = existing.get((order.id, draft["tier"])) if current is not None and current.status in ("sent", "cancelled"): continue @@ -136,24 +155,37 @@ def send_pending_alerts() -> dict[str, Any]: """ 把待发送记录按收件人合并成一条企业微信。 - 核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。 + 核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。 + 解析失败的人不改发给别人。已取消和已发送不参与。 + 第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。 + 卡片或附件任一失败都记失败原因,并打一条 warning 日志。 + 每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。 Returns: 成功人数、失败人数,以及对应的记录条数。 """ from app.models import Agent - from app.services.integrations.wecom.notify import send_wecom_event_message + from app.services.integrations.wecom.notify import ( + send_wecom_event_message, + send_wecom_file_message, + upload_wecom_temp_media, + ) rows = ( db.session.query(EquipmentAcceptanceSendRecord) .filter(EquipmentAcceptanceSendRecord.status == "pending") .all() ) + if not is_round_4_enabled(): + rows = [row for row in rows if row.tier != 4] orders = { order.id: order for order in db.session.query(EquipmentAcceptanceOrder) .filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id])) .all() } if rows else {} + order_ids = [row.order_id for row in rows if row.order_id] + nodes = _nodes_by_order(order_ids) + operators = _operators_by_order(order_ids) users = _users_by_id(_recipient_user_ids(rows)) buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {} for row in rows: @@ -166,24 +198,58 @@ def send_pending_alerts() -> dict[str, Any]: jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace" jump_params = {"view": "sends"} if agent is not None else None sent_ids: set[str] = set() - failed_ids: set[str] = set() + failed_reasons: dict[str, str] = {} for wecom_id, entries in buckets.items(): user = _audit_user(entries, users) + lines = _notice_lines(entries, orders, nodes, operators) + workbook = build_notice_workbook(lines) + archived = _archive_send_file(user, entries, workbook) + failure = "" try: result = send_wecom_event_message( event_type=_EVENT, user=user, title="设备验收停留提醒", - content=_message(entries, orders), + content=summary_message(lines), jump_path=jump_path, jump_params=jump_params, wecom_userid=wecom_id, ) - ok = bool(result.get("ok")) except Exception: - _LOGGER.warning("equipment acceptance wecom send failed") - ok = False - (sent_ids if ok else failed_ids).add(wecom_id) + _LOGGER.exception("equipment acceptance wecom send failed") + failure = "企业微信发送异常" + result = {} + if not failure and not result.get("ok"): + failure = _wecom_failure_text(result) + _LOGGER.warning( + "equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s", + result.get("reason"), + result.get("trace_id"), + failure, + ) + if not failure: + try: + media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME) + file_result = send_wecom_file_message(wecom_id, media_id) + except Exception: + _LOGGER.exception("equipment acceptance wecom file upload failed") + failure = "企业微信附件上传失败" + file_result = {} + if not failure and file_result.get("errcode") != 0: + failure = _file_failure_text(file_result) + _LOGGER.warning( + "equipment acceptance wecom file failed errcode=%s errmsg=%s", + file_result.get("errcode"), + failure, + ) + if failure: + failed_reasons[wecom_id] = failure + archived.status = "failed" + archived.error_message = failure + else: + sent_ids.add(wecom_id) + archived.status = "sent" + archived.sent_at = datetime.utcnow() records_sent = 0 records_failed = 0 now = datetime.utcnow() @@ -196,9 +262,10 @@ def send_pending_alerts() -> dict[str, Any]: ready.discard("") if not ready: continue - if ready & failed_ids: + hit = [failed_reasons[item] for item in ready if item in failed_reasons] + if hit: row.status = "failed" - row.error_message = _join_error(row.error_message, "企业微信发送失败") + row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit))) records_failed += 1 elif ready <= sent_ids: row.status = "sent" @@ -207,7 +274,7 @@ def send_pending_alerts() -> dict[str, Any]: db.session.commit() return { "sent": len(sent_ids), - "failed": len(failed_ids), + "failed": len(failed_reasons), "records_sent": records_sent, "records_failed": records_failed, } @@ -221,9 +288,11 @@ def _drafts( users_by_job: dict[str, User], roles: dict[str, User | None], thresholds: tuple[int, int, int, int], + *, + max_tier: int = 4, ) -> list[dict[str, Any]]: - """按当前处理人展开四档里已经跨过的档。""" - due = due_tiers(order.dwell_days, thresholds) + """按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。""" + due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier) if not due: return [] handlers: list[dict[str, Any]] = [] @@ -410,6 +479,21 @@ def _users_by_id(user_ids: list[int]) -> dict[int, User]: return {row.id: row for row in rows} +def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]: + """取出这些验收单的当前节点名称。""" + if not order_ids: + return {} + grouped: dict[int, list[EquipmentAcceptanceNode]] = {} + rows = ( + db.session.query(EquipmentAcceptanceNode) + .filter(EquipmentAcceptanceNode.order_id.in_(order_ids)) + .all() + ) + for row in rows: + grouped.setdefault(row.order_id, []).append(row) + return grouped + + def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]: """取出这些验收单的当前处理人。""" if not order_ids: @@ -447,28 +531,145 @@ def _audit_user( return None -def _message( +def _archive_send_file( + user: User | None, + entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]], + workbook: bytes, +) -> EquipmentAcceptanceSendFile: + """ + 把这次准备发给一名收件人的 Excel 先落库。 + + 核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。 + Args: + user: 系统用户。对不上账号时只留姓名。 + entries: 这名收件人的发送记录和席位,用来取展示名。 + workbook: xlsx 字节。 + Returns: + 已加入当前事务、尚未提交的文件行。 + """ + now = datetime.utcnow() + name = _recipient_display_name(user, entries) + row = EquipmentAcceptanceSendFile( + recipient_user_id=None if user is None else user.id, + recipient_name=name or None, + excel_file_name=_archive_file_name(name, now), + excel_file_data=workbook, + excel_file_size=len(workbook), + send_record_ids=[row.id for row, _person in entries if row.id], + status="pending", + created_at=now, + ) + db.session.add(row) + return row + + +def _recipient_display_name( + user: User | None, + entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]], +) -> str: + """优先用系统姓名,没有账号时用收件人席位上的名字。""" + if user is not None: + named = str(user.real_name or user.username or "").strip() + if named: + return named + for _row, person in entries: + named = str(person.get("name") or "").strip() + if named: + return named + return "" + + +def _archive_file_name(recipient_name: str, moment: datetime) -> str: + """文件名带上海日期和收件人,避免多次发送都叫同一个名字。""" + local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai")) + safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人" + return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255] + + +def _notice_lines( entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]], orders: dict[int, EquipmentAcceptanceOrder], -) -> str: - """拼一名收件人本轮要看的验收单。过长时截断。""" - lines: list[str] = [] - seen: set[int] = set() + nodes: dict[int, list[EquipmentAcceptanceNode]], + operators: dict[int, list[EquipmentAcceptanceOperator]], +) -> list[dict[str, Any]]: + """ + 把一名收件人的发送记录收成 Excel 行。 + + 核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。 + Args: + entries: 这名收件人挂到的发送记录和对应席位。 + orders: 验收单主键到快照。 + nodes: 验收单主键到当前节点。 + operators: 验收单主键到当前处理人。 + Returns: + 传给汇总文案和 Excel 的明细行。 + """ + grouped: dict[int, dict[str, Any]] = {} + order_keys: list[int] = [] for row, person in entries: - if row.id in seen: - continue - seen.add(row.id) + label = str(person.get("label") or "").strip() + bucket = grouped.get(row.id) + if bucket is None: + bucket = {"row": row, "labels": []} + grouped[row.id] = bucket + order_keys.append(row.id) + if label and label not in bucket["labels"]: + bucket["labels"].append(label) + lines: list[dict[str, Any]] = [] + for key in order_keys: + row = grouped[key]["row"] order = orders.get(row.order_id or 0) - days = "—" if order is None or order.dwell_days is None else str(order.dwell_days) - role = "主送" if person.get("slot") == "to" else "抄送" - lines.append( - f"{role} {row.acceptance_no or '—'},采购单 {row.purchase_order_no or '—'}," - f"停留 {days} 天,超过 {row.threshold_days} 天" - ) - text = "\n".join(lines[:12]) - if len(lines) > 12: - text = f"{text}\n另有 {len(lines) - 12} 条" - return text[:500] + node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, [])) + handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, [])) + lines.append({ + "acceptance_no": row.acceptance_no, + "purchase_order_no": row.purchase_order_no, + "applicant": None if order is None else order.applicant_name, + "threshold_days": row.threshold_days, + "dwell_days": None if order is None else order.dwell_days, + "node_name": "、".join(node_names), + "handlers": "、".join(handler_names), + "identity": "、".join(grouped[key]["labels"]), + }) + return lines + + +def _unique_text(values) -> list[str]: + """按出现顺序去掉空白和重复名称。""" + found: list[str] = [] + for value in values: + text = str(value or "").strip() + if text and text not in found: + found.append(text) + return found + + +def _file_failure_text(result: dict[str, Any]) -> str: + """把企微文件消息的返回收成失败原因。不写入 userid。""" + code = result.get("errcode") + message = str(result.get("errmsg") or "").strip() + text = f"企业微信附件发送失败 {code} {message}".strip() + return text[:255] + + +def _wecom_failure_text(result: dict[str, Any]) -> str: + """把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。""" + reason = str(result.get("reason") or "") + if reason == "notify_disabled": + return "企业微信通知总开关已关闭" + if reason == "event_disabled": + return "未开启设备验收预警的企业微信事件" + if reason == "user_unbound": + return "收件人未绑定企业微信" + raw = result.get("raw") if isinstance(result.get("raw"), dict) else {} + if reason == "send_failed": + code = raw.get("errcode") + message = str(raw.get("errmsg") or "").strip() + text = f"企业微信返回 {code} {message}".strip() + return text[:255] + if reason == "exception": + return "企业微信发送异常" + return "企业微信发送失败" def _join_error(current: str | None, extra: str) -> str: diff --git a/backend/app/services/equipment_acceptance/config_service.py b/backend/app/services/equipment_acceptance/config_service.py index 021fdd8c..f85bf0ba 100644 --- a/backend/app/services/equipment_acceptance/config_service.py +++ b/backend/app/services/equipment_acceptance/config_service.py @@ -1,10 +1,10 @@ """ backend/app/services/equipment_acceptance/config_service.py -用途:读写设备验收预警配置:四档天数和三个固定岗位。 +用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。 依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。 逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。 -没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。 +没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。 """ from __future__ import annotations @@ -29,6 +29,44 @@ _ROLE_FIELDS = ( _MAX_DAY = 3650 +def is_round_4_enabled() -> bool: + """ + 读取第 4 轮是否启用。 + + 核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。 + Returns: + 启用为 True。 + """ + row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID) + if row is None: + return False + return bool(row.round_4_enabled) + + +def parse_round_4_enabled(raw: Any) -> bool: + """ + 校验第 4 轮开关。 + + 核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。 + Args: + raw: 接口里的 round_4_enabled。缺省为 None。 + Returns: + 是否启用第 4 轮。 + + Raises: + ValidationError: 传入了布尔以外的值。 + """ + if raw is None: + return False + if not isinstance(raw, bool): + raise ValidationError( + "第 4 轮开关必须是是否启用", + code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID", + details={"field": "round_4_enabled"}, + ) + return raw + + def reminder_days() -> tuple[int, int, int, int]: """ 读取四档天数。 @@ -65,12 +103,13 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]: Args: include_candidates: 为 True 时附带在职用户,供选人弹窗使用。 Returns: - days、三个岗位用户主键、已选用户、候选人和更新时间。 + days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。 """ row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID) selected_ids = _selected_ids(row) return { "days": list(_days_of(row)), + "round_4_enabled": False if row is None else bool(row.round_4_enabled), "buyer_manager_user_id": None if row is None else row.buyer_manager_user_id, "coo_user_id": None if row is None else row.coo_user_id, "executive_user_id": None if row is None else row.executive_user_id, @@ -82,12 +121,12 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]: def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]: """ - 保存四档天数和三个岗位用户。 + 保存四档天数、第 4 轮开关和三个岗位用户。 - 核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。 - 保存后只影响以后的预警,这里不改历史发送记录。 + 核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。 + 保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。 Args: - payload: days 为四个整数;三个岗位字段为用户主键或空。 + payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。 updated_by: 操作人的系统用户主键。 Returns: 与读取接口相同的配置,并带候选人。 @@ -96,12 +135,14 @@ def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[ ValidationError: 天数不合法,或岗位用户不存在。 """ days = validate_reminder_days(payload.get("days")) + round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled")) role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS} row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID) if row is None: row = EquipmentAcceptanceSetting(id=_SETTING_ID) db.session.add(row) row.day_1, row.day_2, row.day_3, row.day_4 = days + row.round_4_enabled = round_4_enabled row.buyer_manager_user_id = role_ids["buyer_manager_user_id"] row.coo_user_id = role_ids["coo_user_id"] row.executive_user_id = role_ids["executive_user_id"] diff --git a/backend/app/services/equipment_acceptance/send_record_service.py b/backend/app/services/equipment_acceptance/send_record_service.py index d9b7d7ce..57f41de6 100644 --- a/backend/app/services/equipment_acceptance/send_record_service.py +++ b/backend/app/services/equipment_acceptance/send_record_service.py @@ -2,17 +2,20 @@ backend/app/services/equipment_acceptance/send_record_service.py 用途:分页读取设备验收预警的发送记录。 -依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。 -逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。 +依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。 +逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。 """ from __future__ import annotations from typing import Any +from sqlalchemy.orm import defer + +from app.core.errors import NotFoundError from app.core.response import utc_iso from app.extensions import db -from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord +from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord def list_send_records(*, page: int, page_size: int) -> dict[str, Any]: @@ -36,21 +39,122 @@ def list_send_records(*, page: int, page_size: int) -> dict[str, Any]: .limit(page_size) .all() ) + file_rows = _file_rows_for([row.id for row in rows]) return { - "items": [send_record_payload(row) for row in rows], + "items": [ + send_record_payload(row, _files_for_record(row.id, file_rows)) + for row in rows + ], "total": total, "page": page, "page_size": page_size, } -def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]: +def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]: + """ + 列出最近留下的收件人 Excel,不含文件字节。 + + 核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。 + Args: + limit: 最多返回条数,上限 50。 + Returns: + 文件名、收件人、状态和发送时间。 + """ + limit = min(50, max(1, limit)) + rows = ( + db.session.query(EquipmentAcceptanceSendFile) + .order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc()) + .limit(limit) + .all() + ) + return [send_file_payload(row) for row in rows] + + +def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile: + """ + 取出一份已归档的 Excel。 + + Args: + file_id: 文件行主键。 + Returns: + 含字节的文件行。 + + Raises: + NotFoundError: 记录不存在或没有文件内容。 + """ + row = db.session.get(EquipmentAcceptanceSendFile, file_id) + if row is None or not row.excel_file_data: + raise NotFoundError("设备验收预警附件不存在") + return row + + +def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]: + """列表用的文件摘要。不返回 Excel 字节。""" + return { + "id": row.id, + "recipient_name": row.recipient_name, + "excel_file_name": row.excel_file_name, + "excel_file_size": row.excel_file_size, + "status": row.status, + "sent_at": utc_iso(row.sent_at), + "created_at": utc_iso(row.created_at), + } + + +def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]: + """ + 取出可能挂在这些发送记录上的 Excel 摘要。 + + 核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。 + Args: + record_ids: 当前页发送记录主键。为空时不查。 + Returns: + 归档文件行,不含 excel_file_data。 + """ + if not record_ids: + return [] + return ( + db.session.query(EquipmentAcceptanceSendFile) + .options(defer(EquipmentAcceptanceSendFile.excel_file_data)) + .order_by(EquipmentAcceptanceSendFile.id.asc()) + .all() + ) + + +def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]: + """ + 挑出包含这条发送记录的 Excel。 + + 核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。 + Args: + record_id: 发送记录主键。 + file_rows: 已去掉文件字节的归档行。 + Returns: + 下载按钮需要的 id 和文件名。 + """ + found: list[dict[str, Any]] = [] + for row in file_rows: + ids = {int(item) for item in list(row.send_record_ids or []) if item} + if record_id in ids and row.excel_file_name: + found.append({ + "id": row.id, + "excel_file_name": row.excel_file_name, + }) + return found + + +def send_record_payload( + row: EquipmentAcceptanceSendRecord, + files: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: """ 把一条发送记录收成接口数据。 - 核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。 + 核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。 Args: row: 本地发送记录。 + files: 这份记录出现过的归档 Excel。 Returns: 页签表格用的字段。 """ @@ -68,4 +172,5 @@ def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]: "sent_at": utc_iso(row.sent_at), "error_message": row.error_message, "created_at": utc_iso(row.created_at), + "files": files or [], } diff --git a/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py b/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py new file mode 100644 index 00000000..a7e2c7df --- /dev/null +++ b/backend/migrations/versions/eah8c9d0e1f2_add_equipment_acceptance_send_files.py @@ -0,0 +1,97 @@ +"""补齐设备验收预警的企微事件、第 4 轮开关和 Excel 归档。 + +Revision ID: eah8c9d0e1f2 +Revises: b7a2b2155155 +Create Date: 2026-10-13 14:30:00.000000 + +用途:把尚未提交的三步收成一次升级。已有库如果停在本版本,结构已经齐,不会重跑。 +依赖:b7a2b2155155、app_settings、equipment_acceptance_settings、users。 +逻辑:企微事件名单末尾补上 equipment_acceptance_warning;第 4 轮默认关闭;按收件人留下发送时的 Excel。 +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy import text + + +revision = "eah8c9d0e1f2" +down_revision = "b7a2b2155155" +branch_labels = None +depends_on = None + +_KEY = "WECOM_NOTIFY_EVENTS" +_EVENT = "equipment_acceptance_warning" + + +def _split_events(raw: str | None) -> list[str]: + """按逗号拆开事件名单,去掉空白项。""" + return [part.strip() for part in str(raw or "").split(",") if part.strip()] + + +def upgrade(): + """补上企微事件、第 4 轮开关,并建立按收件人归档 Excel 的表。""" + _append_wecom_event() + op.add_column( + "equipment_acceptance_settings", + sa.Column("round_4_enabled", sa.Boolean(), nullable=False, server_default=sa.false()), + ) + op.create_table( + "equipment_acceptance_send_files", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("recipient_user_id", sa.Integer(), nullable=True), + sa.Column("recipient_name", sa.String(length=200), nullable=True), + sa.Column("excel_file_name", sa.String(length=255), nullable=True), + sa.Column("excel_file_data", sa.LargeBinary(), nullable=True), + sa.Column("excel_file_size", sa.Integer(), nullable=True), + sa.Column("send_record_ids", sa.JSON(), nullable=True), + sa.Column("status", sa.String(length=32), nullable=False), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("sent_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"], ondelete="SET NULL"), + ) + op.create_index( + "ix_equipment_acceptance_send_files_created", + "equipment_acceptance_send_files", + ["created_at"], + ) + + +def downgrade(): + """按相反顺序去掉 Excel 归档、第 4 轮开关和企微事件。""" + op.drop_index("ix_equipment_acceptance_send_files_created", table_name="equipment_acceptance_send_files") + op.drop_table("equipment_acceptance_send_files") + op.drop_column("equipment_acceptance_settings", "round_4_enabled") + _remove_wecom_event() + + +def _append_wecom_event() -> None: + """已有事件名单时在末尾补上设备验收预警。没有这一行则不插入。""" + bind = op.get_bind() + if "app_settings" not in sa.inspect(bind).get_table_names(): + return + row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone() + if row is None: + return + events = _split_events(row[0]) + if _EVENT in events: + return + events.append(_EVENT) + bind.execute( + text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"), + {"key": _KEY, "value": ",".join(events)}, + ) + + +def _remove_wecom_event() -> None: + """从已保存的企微事件名单里去掉设备验收预警。没有这一行时不处理。""" + bind = op.get_bind() + if "app_settings" not in sa.inspect(bind).get_table_names(): + return + row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone() + if row is None: + return + events = [part for part in _split_events(row[0]) if part != _EVENT] + bind.execute( + text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"), + {"key": _KEY, "value": ",".join(events)}, + ) diff --git a/backend/tests/test_equipment_acceptance_alert_notice.py b/backend/tests/test_equipment_acceptance_alert_notice.py new file mode 100644 index 00000000..136b7680 --- /dev/null +++ b/backend/tests/test_equipment_acceptance_alert_notice.py @@ -0,0 +1,58 @@ +""" +tests/test_equipment_acceptance_alert_notice.py + +用途:锁定设备验收企微汇总文案和 Excel 列。 +依赖:alert_notice、openpyxl。 +逻辑:不连数据库,不发企业微信。卡片只写张数。工作簿含申请人,不写主送。 +""" + +from io import BytesIO + +import pytest +from openpyxl import load_workbook + +pytestmark = pytest.mark.pure_unit + +from app.services.equipment_acceptance.alert_notice import ( + NOTICE_HEADERS, + build_notice_workbook, + summary_message, +) + + +def test_summary_counts_rounds_without_listing_orders(): + """第一行写已逾期张数。正文不出现验收单号,也不写主送。""" + text = summary_message([ + {"threshold_days": 30}, + {"threshold_days": 30}, + {"threshold_days": 37}, + ]) + assert text == "共 3 张验收单已逾期。\n超过 30 天 2 张,超过 37 天 1 张。\n明细见下一条文件。" + assert "主送" not in text + assert "20260210" not in text + + +def test_workbook_includes_applicant_and_identity(): + """Excel 列与原型一致。通知身份保留角色名,停留天数为空时写横线。""" + data = build_notice_workbook([{ + "acceptance_no": "20260210000001", + "purchase_order_no": "1111", + "applicant": "孙浩", + "threshold_days": 30, + "dwell_days": None, + "node_name": "使用部门担当", + "handlers": "吴敏", + "identity": "直接主管", + }]) + sheet = load_workbook(BytesIO(data)).active + assert [cell.value for cell in sheet[1]] == list(NOTICE_HEADERS) + assert [cell.value for cell in sheet[2]] == [ + "20260210000001", + "1111", + "孙浩", + "超过 30 天", + "—", + "使用部门担当", + "吴敏", + "直接主管", + ] diff --git a/backend/tests/test_equipment_acceptance_alert_plan.py b/backend/tests/test_equipment_acceptance_alert_plan.py index ee3fd168..26fa2dad 100644 --- a/backend/tests/test_equipment_acceptance_alert_plan.py +++ b/backend/tests/test_equipment_acceptance_alert_plan.py @@ -30,6 +30,7 @@ def test_due_tiers_use_strictly_greater_than_threshold(): assert due_tiers(31, _DAYS) == [1] assert due_tiers(51, _DAYS) == [1, 2, 3] assert due_tiers(52, _DAYS) == [1, 2, 3, 4] + assert due_tiers(52, _DAYS, max_tier=3) == [1, 2, 3] def test_tier_one_keeps_missing_supervisor_as_failure(): diff --git a/backend/tests/test_equipment_acceptance_config.py b/backend/tests/test_equipment_acceptance_config.py index 8e9df48c..19f9052c 100644 --- a/backend/tests/test_equipment_acceptance_config.py +++ b/backend/tests/test_equipment_acceptance_config.py @@ -1,15 +1,15 @@ """ tests/test_equipment_acceptance_config.py -用途:锁定设备验收预警四档天数的保存前校验。 -依赖:config_service.validate_reminder_days、ValidationError。 -逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。 +用途:锁定设备验收预警四档天数和第 4 轮开关的保存前校验。 +依赖:config_service.validate_reminder_days、parse_round_4_enabled、ValidationError。 +逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。第 4 轮缺省关闭。 """ import pytest from app.core.errors import ValidationError -from app.services.equipment_acceptance.config_service import validate_reminder_days +from app.services.equipment_acceptance.config_service import parse_round_4_enabled, validate_reminder_days def test_default_reminder_days_pass(): @@ -30,3 +30,13 @@ def test_days_reject_bool_and_wrong_length(): validate_reminder_days([True, 37, 44, 51]) with pytest.raises(ValidationError): validate_reminder_days([30, 37, 44]) + + +def test_round_4_defaults_off_and_rejects_non_bool(): + """未传开关时按关闭处理。数字 1 不能当成启用,避免误通知总经理。""" + assert parse_round_4_enabled(None) is False + assert parse_round_4_enabled(False) is False + assert parse_round_4_enabled(True) is True + with pytest.raises(ValidationError) as caught: + parse_round_4_enabled(1) + assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID" diff --git a/docs/demand.md b/docs/demand.md index 034a54a8..10c7d8eb 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -22,7 +22,7 @@ ## 设备验收预警(2026-09) - 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。 -- 超过 30/37/44/51 天各发一次企业微信。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。 +- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。 - 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。 ## 合同付款预警 Agent(2026-08) diff --git a/docs/features/equipment-acceptance-warning/config-redesign-preview.html b/docs/features/equipment-acceptance-warning/config-redesign-preview.html index 3ca7dc9d..f4b3a74a 100644 --- a/docs/features/equipment-acceptance-warning/config-redesign-preview.html +++ b/docs/features/equipment-acceptance-warning/config-redesign-preview.html @@ -76,6 +76,9 @@ } .when { display: flex; flex-direction: column; gap: 8px; } .when b { font-size: 12px; color: var(--muted); font-weight: 700; } + .switch { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 700; } + .when small { color: var(--muted); font-size: 12px; } + .round.off .people { opacity: 0.45; } .day { display: flex; align-items: center; @@ -267,10 +270,12 @@

-
+
第 4 轮 + + 默认关闭,不通知总经理
@@ -305,7 +310,12 @@
-

效果图,尚未接到现有页面。

+

效果图。第 4 轮开关已接到现有配置页,默认关闭。

+ diff --git a/docs/features/equipment-acceptance-warning/demand.md b/docs/features/equipment-acceptance-warning/demand.md index bcb4c1f7..45646869 100644 --- a/docs/features/equipment-acceptance-warning/demand.md +++ b/docs/features/equipment-acceptance-warning/demand.md @@ -60,6 +60,8 @@ | 超过 44 天 | COO | 采购经副理 | | 超过 51 天 | 总经理 | COO、采购经副理 | +第 4 轮在配置里单独开关,默认关闭。关闭时不生成、也不发送总经理这一轮。打开后,下一次扫描才按超过第 4 档的天数产生待发送。前 3 轮不受这个开关影响。 + 人员解析: - 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。 @@ -70,7 +72,7 @@ ## 6. 推送 -已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总。渠道只有企业微信。 +已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总卡片,并紧跟一份只含该收件人明细的 Excel。这份 Excel 按收件人归档,挂在发送记录表的 Excel 附件列上,点文件名再下载。卡片不逐条列出验收单,也不区分主送和抄送。渠道只有企业微信。 ## 7. 数据来源 diff --git a/docs/features/equipment-acceptance-warning/send-redesign-preview.html b/docs/features/equipment-acceptance-warning/send-redesign-preview.html new file mode 100644 index 00000000..b3ad67cb --- /dev/null +++ b/docs/features/equipment-acceptance-warning/send-redesign-preview.html @@ -0,0 +1,279 @@ + + + + + 设备验收预警 · 发送效果图 + + + +
+

设备验收预警 · 发送效果图

+

效果图,尚未接到现有页面。同一个人只收一条汇总卡片,明细在下一条 Excel。不再区分主送和抄送。

+ +
+
+
+

sophie 收到的企业微信

+

她这一轮有 18 张单,卡片里不逐条列出。

+
+
+
+
设备验收预警
+
+

19:52

+
+

设备验收停留提醒

+

共 18 张验收单。 +超过 30 天 12 张,超过 37 天 4 张,超过 44 天 2 张。 +明细见下一条文件。

+
查看详情›
+
+
+
XLS
+
+ 设备验收停留提醒.xlsx + 28.4 KB +
+
+
+
+
+
+ +
+
+

附件里的前 8 行

+

只含 sophie 本人要看的单。通知身份说明她为什么会收到,不再写主送、抄送。

+
+
+ + + + + + + + + + + + + + + + + + + + + + + +
验收单号采购单号申请人轮次停留天数当前节点当前处理人通知身份
202602100000011111孙浩超过 30 天31使用部门担当吴敏直接主管
20260211000008CG-0881李文超过 30 天33品质担当林可直接主管
20260212000015CG-0902周洋超过 30 天36公用主管sophie当前处理人
20260213000022CG-0910孙浩超过 37 天40设备管理部周宁采购经副理
20260214000031CG-0933陈敏超过 37 天41品质经理何倩采购经副理
20260215000040CG-0948刘洋超过 44 天46COO陈立采购经副理
20260216000052CG-0961王磊超过 30 天32使用部门经理赵凯直接主管
20260217000060CG-0977孙浩超过 30 天35固定资产管理人孙浩采购担当
+
+

文件内共 18 行。同一张单若第 1 轮和第 2 轮都还没发过,会各占一行。停留天数是发送当时的天数。

+
+
+ +
+
+ 停留情况 + 发送记录 + 预警配置 +
+
+

每日扫描生成待发送。每周五 18:00 按人汇总,每人一条卡片加一份 Excel。这里仍是一条记录对应一张单的一轮。

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
验收单号采购单号轮次收件人结果发送时间
202602100000011111超过 30 天吴敏、sophie、孙浩已发送2026-10-12 18:55:18
20260212000015CG-0902超过 37 天孙经理、COO、赵琴待发送—
20260215000040CG-0948超过 44 天COO、赵琴发送失败—
+
+

页面上的「导出 Excel」是当前列表里的全部记录。个人在企业微信里收到的文件只含他自己的行。

+
+
+ + diff --git a/docs/features/equipment-acceptance-warning/technical.md b/docs/features/equipment-acceptance-warning/technical.md index bbda39fe..1e6f4622 100644 --- a/docs/features/equipment-acceptance-warning/technical.md +++ b/docs/features/equipment-acceptance-warning/technical.md @@ -412,7 +412,7 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid; 页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。 -`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。 +`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`round_4_enabled` 默认关闭,关闭时扫描不生成第 4 轮,发送也会跳过已经待发送的第 4 轮。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。 ## 9. 扫描与发送 @@ -423,11 +423,11 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid; - 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。 - 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。 - 超过第 3 档:主送 COO,抄送采购经副理。 -- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。 +- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。配置里的第 4 轮开关默认关闭,关闭时这一档不产生、也不发送。 人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。 -每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号合并成一条文本卡片,标题「设备验收停留提醒」,事件 `equipment_acceptance_warning`。卡片过长时先留 12 行,其余写成「另有 N 条」。发送成功改为已发送。有人失败则整档改为失败,并附上「企业微信发送失败」;下次扫描会按当前处理人重算并回到待发送。已发出的企业微信不撤回。 +每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号先收一条文本卡片,标题「设备验收停留提醒」,正文先写共多少张验收单已逾期,再写各轮次数量,事件 `equipment_acceptance_warning`。紧跟着一条文件消息《设备验收停留提醒.xlsx》,列是验收单号、采购单号、申请人、轮次、停留天数、当前节点、当前处理人、通知身份。卡片不写主送、抄送,也不逐条列出验收单。卡片和文件都成功才改为已发送。任一失败则整档改为失败,并写上卡片或附件的原因;下次扫描会按当前处理人重算并回到待发送。每位收件人的 Excel 写入 `equipment_acceptance_send_files`,并记下对应的发送记录。发送失败也保留。发送记录表用 Excel 附件列下载,同一行可有多份。已发出的企业微信不撤回。 停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。 diff --git a/docs/funclist.md b/docs/funclist.md index c3518059..27407db2 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -48,9 +48,9 @@ | 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 | | 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 | | 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 | -| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,采购经副理、COO、总经理选择系统用户。发送时刻不在此页,以后由排程 Cron 配置,默认每周五 18:00。 | -| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果和发送时间。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 | -| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人汇总一条企业微信。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | +| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 | +| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 | +| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 | ## 知识库同步状态校验 diff --git a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts index f1c2006c..70974f3a 100644 --- a/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts +++ b/frontend/src/features/equipment-acceptance/api/equipment-acceptance.api.ts @@ -4,9 +4,9 @@ * 依赖:统一 requestJson;后端 /api/equipment-acceptance。 * 逻辑:Chat 作业面调用。同步只读 E10。配置只保存天数和系统用户,不保存发送时刻。 * 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。 - * 发送记录只读已落库的行,扫描尚未写入时列表为空。 + * 发送记录只读已落库的行。每位收件人的 Excel 可再下载。 */ -import { requestJson } from '@/shared/api/client'; +import { requestBlob, requestJson } from '@/shared/api/client'; export interface EquipmentAcceptanceNode { node_id?: string | null; @@ -150,6 +150,7 @@ export interface EquipmentAcceptanceSendRecord { sent_at?: string | null; error_message?: string | null; created_at?: string | null; + files?: Array<{ id: number; excel_file_name?: string | null }>; } export interface EquipmentAcceptanceSendListResponse { @@ -166,6 +167,33 @@ export interface EquipmentAcceptanceSendListResponse { * @param params.pageSize - 每页条数 * @returns 当前页记录和总数 */ +export interface EquipmentAcceptanceSendFile { + id: number; + recipient_name?: string | null; + excel_file_name?: string | null; + excel_file_size?: number | null; + status: string; + sent_at?: string | null; + created_at?: string | null; +} + +/** + * 列出最近按收件人归档的 Excel。不含文件内容。 + * @returns 文件摘要 + */ +export function listEquipmentAcceptanceSendFiles() { + return requestJson<{ items: EquipmentAcceptanceSendFile[] }>('/api/equipment-acceptance/send-files'); +} + +/** + * 下载一份当时发给收件人的 Excel。 + * @param fileId - 归档文件主键 + * @returns 文件字节和文件名 + */ +export function downloadEquipmentAcceptanceSendFile(fileId: number) { + return requestBlob(`/api/equipment-acceptance/send-files/${fileId}/excel`); +} + export function listEquipmentAcceptanceSends(params?: { page?: number; pageSize?: number }) { const search = new URLSearchParams(); if (params?.page) search.set('page', String(params.page)); @@ -185,6 +213,7 @@ export interface EquipmentAcceptanceConfigUser { export interface EquipmentAcceptanceConfig { days: number[]; + round_4_enabled?: boolean; buyer_manager_user_id?: number | null; coo_user_id?: number | null; executive_user_id?: number | null; @@ -202,9 +231,10 @@ export function getEquipmentAcceptanceConfig() { } /** - * 保存四档天数和三个岗位的系统用户。仅平台管理员。 - * 核心逻辑:岗位传用户主键或 null,不传姓名。 + * 保存四档天数、第 4 轮开关和三个岗位的系统用户。仅平台管理员。 + * 核心逻辑:岗位传用户主键或 null,不传姓名。第 4 轮关闭时不通知总经理。 * @param payload.days - 四个逐档增大的天数 + * @param payload.round4Enabled - 是否启用第 4 轮 * @param payload.buyerManagerUserId - 采购经副理 * @param payload.cooUserId - COO * @param payload.executiveUserId - 总经理对应岗位 @@ -212,6 +242,7 @@ export function getEquipmentAcceptanceConfig() { */ export function saveEquipmentAcceptanceConfig(payload: { days: number[]; + round4Enabled: boolean; buyerManagerUserId: number | null; cooUserId: number | null; executiveUserId: number | null; @@ -221,6 +252,7 @@ export function saveEquipmentAcceptanceConfig(payload: { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days: payload.days, + round_4_enabled: payload.round4Enabled, buyer_manager_user_id: payload.buyerManagerUserId, coo_user_id: payload.cooUserId, executive_user_id: payload.executiveUserId, diff --git a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue index 3dc5e222..e78af866 100644 --- a/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue +++ b/frontend/src/features/equipment-acceptance/views/EquipmentAcceptanceConfigPage.vue @@ -1,8 +1,8 @@ diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts index c47c3bd1..7463e981 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts @@ -1,21 +1,52 @@ /** * features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts - * 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。 - * 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。 - * 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。 + * 用途:锁定客户识别面板两态行为——未确认态保留候选确认流程;已确认态折叠为摘要条并提供「修改客户」改绑入口。 + * 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel、shipping.api(mock)。 + * 逻辑:已确认摘要条默认折叠(已确认徽标 + 标准客户名 + chevron),展开仅显示既有识别详情; + * rebindAllowed=false 时改绑按钮禁用并展示原因;选定新客户经影响确认弹窗提交改绑 API 并 emit refreshed。 + * 改绑 i18n 键由 Task 3 落 chat.json,这里在 vue-i18n mock 中前置补齐同路径键。 */ -import { describe, expect, it } from 'vitest'; -import { mount } from '@vue/test-utils'; +import { flushPromises, mount } from '@vue/test-utils'; import { createI18n } from 'vue-i18n'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue'; +import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue'; +import { + listWorkspaceShippingCustomerOptions, + rebindWorkspaceShippingOrderReviewCustomer, +} from '@/features/chat/api/shipping.api'; +import { useMessage } from '@/shared/composables/useMessage'; + +const messageSpies = vi.hoisted(() => ({ + success: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + info: vi.fn(), +})); + +vi.mock('@/features/chat/api/shipping.api', () => ({ + confirmWorkspaceShippingOrderReviewCustomer: vi.fn(), + listWorkspaceShippingCustomerOptions: vi.fn(), + retryWorkspaceShippingOrderReviewCustomerResolution: vi.fn(), + rebindWorkspaceShippingOrderReviewCustomer: vi.fn(), +})); + +vi.mock('@/shared/composables/useMessage', () => ({ + useMessage: () => messageSpies, +})); const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': { + common: { cancel: '取消' }, chat: { - shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' }, + shippingCustomer: { + loadFailed: '加载失败', + confirmFailed: '确认失败', + confirm: '确认', + }, shippingOrderReview: { customerResolution: { title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。', @@ -24,6 +55,13 @@ const i18n = createI18n({ standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF', inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' }, status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' }, + // 改绑键:与 Task 3 将落入 locales/*/chat.json 的键路径保持一致 + rebindButton: '修改客户', + rebindDisabledExcelExists: '已产生发货通知/Excel,请先走撤销流程', + rebindConfirmTitle: '确认修改客户', + rebindConfirmImpact: '将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成', + rebindSuccessToast: '客户已更新,可回通知准备重新生成 Excel', + rebindFailedToast: '修改客户失败,请稍后重试', }, resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' }, }, @@ -32,32 +70,110 @@ const i18n = createI18n({ }, }); -function mountPanel(status: string) { +const resolvedResolution = { + resolved: true, + status: 'confirmed', + rebind_allowed: true, + customer_id: 11, + raw_name: 'acme', + standard_name: 'ACME 标准客户', + short_code: 'ACME', + input_values: [ + { definition_code: 'customer_code', definition_label: null, raw_value: 'ACME', normalized_value: 'ACME' }, + ], +}; + +function mountPanel(resolution: Record, extraProps: Record = {}) { return mount(ReviewCustomerResolutionPanel, { props: { caseNo: 'CASE-CUSTOMER-1', editable: true, - resolution: { resolved: false, status, raw_name: 'ACME' }, + orderDataVersion: 4, + resolution, + ...extraProps, }, global: { plugins: [i18n], - stubs: { ShippingCustomerConfirmDialog: true }, + // teleport 就地渲染:改绑影响确认弹窗 Teleport 到 body,stub 后断言仍在 wrapper 内可达。 + stubs: { ShippingCustomerConfirmDialog: true, teleport: true }, }, }); } describe('ReviewCustomerResolutionPanel', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(listWorkspaceShippingCustomerOptions).mockResolvedValue([]); + }); + it('唯一候选展示自动确认说明和明确确认入口', () => { - const wrapper = mountPanel('unique_candidate'); + const wrapper = mountPanel({ resolved: false, status: 'unique_candidate', raw_name: 'ACME' }); expect(wrapper.text()).toContain('保存校验时系统会自动确认'); expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选'); }); it('非唯一未确认状态维持人工选择客户入口', () => { - const wrapper = mountPanel('unmatched'); + const wrapper = mountPanel({ resolved: false, status: 'unmatched', raw_name: 'ACME' }); expect(wrapper.text()).not.toContain('保存校验时系统会自动确认'); expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户'); }); + + it('已确认态默认折叠为摘要条,展开仅显示既有识别详情', async () => { + const wrapper = mountPanel(resolvedResolution); + + // 断言意图:摘要条可见(已确认徽标 + 标准客户名),识别详情默认不展开 + expect(wrapper.get('[data-testid="review-customer-resolution-badge"]').text()).toContain('已确认'); + expect(wrapper.text()).toContain('ACME 标准客户'); + expect(wrapper.find('[data-testid="review-customer-resolution-details"]').exists()).toBe(false); + // 断言意图:改绑入口在摘要条上存在 + expect(wrapper.get('[data-testid="review-rebind-customer"]').exists()).toBe(true); + + // 断言意图:chevron 展开后显示既有识别详情(命中输入),不再是整块识别面板 + await wrapper.get('[data-testid="review-customer-resolution-toggle"]').trigger('click'); + expect(wrapper.get('[data-testid="review-customer-resolution-details"]').exists()).toBe(true); + expect(wrapper.text()).toContain('匹配输入'); + }); + + it('rebindAllowed=false 时改绑按钮禁用并以 tooltip 说明原因', () => { + const wrapper = mountPanel({ ...resolvedResolution, rebind_allowed: false }); + + const rebindButton = wrapper.get('[data-testid="review-rebind-customer"]'); + // 断言意图:edit_window.header=false(Excel 已产生/活动 Attempt)时按钮禁用 + expect(rebindButton.attributes('disabled')).toBeDefined(); + // 断言意图:禁用原因经 tooltip 透出,而非静默置灰 + expect(rebindButton.attributes('title')).toContain('撤销'); + }); + + it('选定新客户并确认影响后提交改绑 API 且 emit refreshed', async () => { + vi.mocked(rebindWorkspaceShippingOrderReviewCustomer).mockResolvedValue({ + case: null, + customer_resolution: null, + rebind: { previous_customer_id: 11, customer_id: 42, snapshot_id: 9 }, + }); + const wrapper = mountPanel(resolvedResolution); + + // [STEP 1] 打开复用的客户搜索选择弹窗并选定目标客户 + await wrapper.get('[data-testid="review-rebind-customer"]').trigger('click'); + await flushPromises(); + const selectDialog = wrapper.findComponent(ShippingCustomerConfirmDialog); + expect(selectDialog.exists()).toBe(true); + selectDialog.vm.$emit('confirm', 42); + await flushPromises(); + + // [STEP 2] 影响确认弹窗出现后提交 + await wrapper.get('[data-testid="review-rebind-confirm-submit"]').trigger('click'); + await flushPromises(); + + // 断言意图:携带乐观锁版本调用改绑 API + expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledTimes(1); + expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledWith( + 'CASE-CUSTOMER-1', + { customer_id: 42, expected_order_data_version: 4 }, + ); + // 断言意图:成功 toast + 复用 refreshed 事件走既有刷新链 + expect(messageSpies.success).toHaveBeenCalled(); + expect(wrapper.emitted('refreshed')).toHaveLength(1); + }); }); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue index f731a4b7..e28662cb 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue @@ -1,9 +1,11 @@ diff --git a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue index edae52d5..ff4cb499 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue @@ -2,14 +2,15 @@ * features/admin/modules/agents/components/AgentFormModal.vue * * 用途:应用管理新增/编辑弹窗,集中承载 Agent 基础信息(含启用状态)、Dify/Iframe 配置和常见问题表单。 - * 依赖:agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。 - * 逻辑:父组件控制 visible/isEditing/isSaving 与保存;本组件直接编辑传入的 form(含 is_active),并通过事件通知关闭、保存、增删常见问题。 + * 依赖:element-plus 对话框、agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。 + * 逻辑:父组件控制 visible/isEditing/isSaving 与保存;外壳是 680px 对话框。表单内部字段仍沿用原有输入控件。 */ + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue index 2b5d3685..de2ce1a2 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue @@ -1,11 +1,12 @@ /** * features/admin/modules/agents/components/AgentPermissionModal.vue - * - * 为指定 Agent 批量勾选可访问用户的权限弹窗。 + * 用途:为指定应用勾选可访问用户。 + * 依赖:element-plus、admin.types、agent.types。 + * 逻辑:AgentsPage 传入用户和已选 id;勾选变化交给父组件 togglePermissionUser。 */ - + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue index 7ef7d6f4..3affcf1d 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue @@ -1,11 +1,12 @@ /** * features/admin/modules/agents/components/AgentTestModal.vue - * - * Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。 + * 用途:应用连通性测试弹窗,展示请求地址、输出和分析结果。 + * 依赖:element-plus、agent.types。 + * 逻辑:AgentsPage 传入当前应用和测试结果;重新测试由父组件发起。 */ - + + diff --git a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts index 0eb5e7a2..ac7bf631 100644 --- a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts +++ b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts @@ -4,10 +4,12 @@ * Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。 * 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。 * 权限组启用后拒绝打开按人授权弹窗,提示改到应用权限页的角色包。 + * 删除确认使用 Element MessageBox。 */ import { ref, computed } from 'vue'; import { useI18n } from 'vue-i18n'; +import { ElMessageBox } from 'element-plus'; import { createAdminAgent, deleteAdminAgent, @@ -238,6 +240,7 @@ export function useAgentsAdmin() { const contentProfileOptions = ref([]); const users = ref([]); const rolesConfigured = ref(false); + const rolesChecked = ref(false); const scheduleTasks = ref([]); const trainingExamPdfGuides = ref([]); const isLoading = ref(true); @@ -256,9 +259,6 @@ export function useAgentsAdmin() { const permissionAgent = ref(null); const permissionUserIds = ref([]); - const showDeleteConfirmDialog = ref(false); - const deleteConfirmMessage = ref(''); - let deleteConfirmAction: (() => Promise | void) | null = null; const activeUsers = () => users.value.filter((u) => u.status !== 'pending'); @@ -336,6 +336,8 @@ export function useAgentsAdmin() { } catch (e) { console.error('Error loading permission roles:', e); rolesConfigured.value = false; + } finally { + rolesChecked.value = true; } }; @@ -364,18 +366,25 @@ export function useAgentsAdmin() { } }; + /** + * 进入页面时先拉应用列表,再在后台补齐编辑弹窗要用的目录、用户和排程。 + * 核心逻辑:加载遮罩只等应用列表。权限组、用户、排程和目录在后台拉取,未返回时不盖住表格。 + */ const loadAll = async (): Promise => { isLoading.value = true; - await Promise.all([ + try { + await loadAgents(); + } finally { + isLoading.value = false; + } + void Promise.all([ loadRegistrySchema(), loadIntentRouteOptions(), loadContentProfileOptions(), - loadAgents(), loadUsers(), loadRolesConfigured(), loadScheduleTasks(), ]); - isLoading.value = false; }; const resetForm = (): void => { @@ -405,27 +414,26 @@ export function useAgentsAdmin() { void loadTrainingExamPdfGuides(agent.id); }; - const openDeleteConfirm = ( + /** + * 用 Element 确认框询问后再执行删除。 + * 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。 + * @param message - 确认文案 + * @param action - 用户点确定后执行的删除 + */ + const openDeleteConfirm = async ( message: string, action: () => Promise | void, - ): void => { - deleteConfirmMessage.value = message; - deleteConfirmAction = action; - showDeleteConfirmDialog.value = true; - }; - - const closeDeleteConfirm = (): void => { - showDeleteConfirmDialog.value = false; - deleteConfirmAction = null; - }; - - const confirmDelete = async (): Promise => { - if (!deleteConfirmAction) return; + ): Promise => { try { - await deleteConfirmAction(); - } finally { - closeDeleteConfirm(); + await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }); + } catch { + return; } + await action(); }; /** @@ -613,7 +621,7 @@ export function useAgentsAdmin() { }; const deleteAgent = async (id: number): Promise => { - openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { + await openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { try { await deleteAdminAgent(id); await loadAgents(); @@ -723,6 +731,7 @@ export function useAgentsAdmin() { contentProfileOptions, users, rolesConfigured, + rolesChecked, scheduleTasks, trainingExamPdfGuides, activeUsers, @@ -739,8 +748,6 @@ export function useAgentsAdmin() { showPermissionModal, permissionAgent, permissionUserIds, - showDeleteConfirmDialog, - deleteConfirmMessage, loadAll, resetForm, selectAgent, @@ -758,7 +765,5 @@ export function useAgentsAdmin() { openPermissionModal, togglePermissionUser, savePermissions, - closeDeleteConfirm, - confirmDelete, }; } diff --git a/frontend/src/features/admin/modules/users/UsersPage.vue b/frontend/src/features/admin/modules/users/UsersPage.vue index 18e152cf..4e3c403b 100644 --- a/frontend/src/features/admin/modules/users/UsersPage.vue +++ b/frontend/src/features/admin/modules/users/UsersPage.vue @@ -1,24 +1,43 @@ /** * features/admin/modules/users/UsersPage.vue * 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。 - * 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。 - * 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取;权限组启用后只选角色、关闭按人授权。 + * 依赖:useUsersAdmin、useElementProvider、element-plus、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。 + * 逻辑:路由 /admin/users;本页是 Element Plus 试点,筛选、表格、分页、工具栏和三个业务弹窗走组件库。 + * 删除和改角色用 Element 确认框。列表经 listAdminUsersPage 按页拉取。 */ + + diff --git a/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue index 65ad5bb9..1dd94abe 100644 --- a/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue +++ b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue @@ -1,17 +1,19 @@ /** * features/admin/modules/users/components/BatchEditUserModal.vue * 用途:批量编辑用户部门/角色/状态弹窗。权限组启用后角色下拉读权限组列表。 - * 依赖:admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。 - * 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。 + * 依赖:element-plus、admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。 + * 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。本弹窗属于用户管理 Element Plus 试点。 */ diff --git a/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue index 79901833..06f9f658 100644 --- a/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue +++ b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue @@ -1,9 +1,21 @@ /** * features/admin/modules/users/components/BatchPermissionModal.vue - * 批量分配/移除用户 Agent 权限弹窗。 + * 用途:批量分配、移除或覆盖用户 Agent 权限。 + * 依赖:element-plus、admin.types、user.types。 + * 逻辑:UsersPage 传入已选人数与 Agent 列表;动作为 add / remove / set。本弹窗属于用户管理 Element Plus 试点。 */ diff --git a/frontend/src/features/admin/modules/users/components/UserFormModal.vue b/frontend/src/features/admin/modules/users/components/UserFormModal.vue index 525b7ab8..62117c80 100644 --- a/frontend/src/features/admin/modules/users/components/UserFormModal.vue +++ b/frontend/src/features/admin/modules/users/components/UserFormModal.vue @@ -1,17 +1,30 @@ /** * features/admin/modules/users/components/UserFormModal.vue * 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。 - * 依赖:admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。 - * 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 培训 HR 勾选,角色下拉用旧枚举。 + * 依赖:element-plus、admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。 + * 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 功能权限勾选,角色下拉用旧枚举。 + * 本弹窗属于用户管理 Element Plus 试点。 */ + + diff --git a/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts index ef412f38..bceab23b 100644 --- a/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts +++ b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts @@ -3,10 +3,12 @@ * 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。 * 依赖:admin.api、useMessage、useTableSort、permissionRole.types。 * 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。 - * 权限组启用后创建用户预填默认角色,改角色须确认;批量按人授权入口关闭。 + * 权限组启用后创建用户预填默认角色;删除和改角色用 Element 确认框。批量按人授权入口关闭。 + * Element Plus 表格通过 applyServerSort 写入列排序。 */ import { computed, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; +import { ElMessageBox } from 'element-plus'; import { batchDeleteAdminUsers, batchUpdateAdminPermissions, @@ -68,10 +70,6 @@ export function useUsersAdmin() { const showUserModal = ref(false); const editingUser = ref(createEmptyUserForm()); const originalUserRole = ref('user'); - const showRoleConfirm = ref(false); - const roleConfirmMessage = ref(''); - let pendingUserSave: (() => Promise) | null = null; - let pendingBatchSave: (() => Promise) | null = null; const showBatchEditModal = ref(false); const batchEditForm = ref({ department: '', role: '', status: '' }); @@ -79,9 +77,6 @@ export function useUsersAdmin() { const showBatchPermissionModal = ref(false); const batchPermissionForm = ref({ agent_ids: [], action: 'add' }); - const showDeleteConfirmDialog = ref(false); - const deleteConfirmMessage = ref(''); - let deleteConfirmAction: (() => Promise | void) | null = null; /** 当前页是否已全部选中 */ const allPaginatedUsersSelected = computed( @@ -194,25 +189,41 @@ export function useUsersAdmin() { }, 300); }, { deep: true }); - const openDeleteConfirm = (message: string, action: () => Promise | void): void => { - deleteConfirmMessage.value = message; - deleteConfirmAction = action; - showDeleteConfirmDialog.value = true; - }; - - const closeDeleteConfirm = (): void => { - showDeleteConfirmDialog.value = false; - deleteConfirmAction = null; + /** + * 用 Element 确认框询问后再执行删除。 + * 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。 + * @param message - 确认文案 + * @param action - 用户点确定后执行的删除 + */ + const openDeleteConfirm = async (message: string, action: () => Promise | void): Promise => { + try { + await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }); + } catch { + return; + } + await action(); }; /** - * 执行待确认的删除操作。 - * 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。 + * 用 Element 确认框询问改角色,确定后执行保存。 + * 核心逻辑:与删除确认同一组件,避免一页两种确认框。取消则不保存。 + * @param message - 角色变更说明 + * @param action - 用户点确定后提交 */ - const confirmDelete = async (): Promise => { - const action = deleteConfirmAction; - closeDeleteConfirm(); - if (!action) return; + const confirmRoleThen = async (message: string, action: () => Promise): Promise => { + try { + await ElMessageBox.confirm(message, t('admin.permRoles.userRoleConfirmTitle'), { + type: 'warning', + confirmButtonText: t('admin.save'), + cancelButtonText: t('admin.cancel'), + }); + } catch { + return; + } await action(); }; @@ -296,11 +307,10 @@ export function useUsersAdmin() { : nextRole !== originalUserRole.value; const touchesAdmin = isAdminRoleCode(nextRole) || isAdminRoleCode(originalUserRole.value); if (roleChanged) { - roleConfirmMessage.value = touchesAdmin + const message = touchesAdmin ? t('admin.permRoles.userAdminConfirm') : t('admin.permRoles.userRoleConfirm', { role: nextRole }); - pendingUserSave = persistUser; - showRoleConfirm.value = true; + await confirmRoleThen(message, persistUser); return; } await persistUser(); @@ -348,28 +358,6 @@ export function useUsersAdmin() { } }; - /** - * 确认改角色(含管理员)后再提交。 - */ - const confirmRoleChange = async (): Promise => { - const userSave = pendingUserSave; - const batchSave = pendingBatchSave; - pendingUserSave = null; - pendingBatchSave = null; - showRoleConfirm.value = false; - if (userSave) { - await userSave(); - return; - } - if (batchSave) await batchSave(); - }; - - const closeRoleConfirm = (): void => { - pendingUserSave = null; - pendingBatchSave = null; - showRoleConfirm.value = false; - }; - const cleanRejectedUsers = async (): Promise => { openDeleteConfirm(t('admin.user.confirmClean'), async () => { try { @@ -446,11 +434,10 @@ export function useUsersAdmin() { return; } if (data.role) { - roleConfirmMessage.value = isAdminRoleCode(data.role) + const message = isAdminRoleCode(data.role) ? t('admin.permRoles.userAdminConfirm') : t('admin.permRoles.batchRoleConfirm'); - pendingBatchSave = () => persistBatchEdit(data); - showRoleConfirm.value = true; + await confirmRoleThen(message, () => persistBatchEdit(data)); return; } await persistBatchEdit(data); @@ -504,6 +491,19 @@ export function useUsersAdmin() { scheduleLoadUsers(true); }; + /** + * 按指定列和方向重新查询第一页。 + * 核心逻辑:方向未变时不请求;变更后回到第一页再拉取。 + * @param key - username 或 department,与后端 sort_by 白名单一致 + * @param dir - asc 或 desc + */ + const applyServerSort = (key: UserSortKey, dir: 'asc' | 'desc'): void => { + if (sortKey.value === key && sortDir.value === dir) return; + sortKey.value = key; + sortDir.value = dir; + scheduleLoadUsers(true); + }; + return { users, agents, @@ -530,12 +530,9 @@ export function useUsersAdmin() { batchEditForm, showBatchPermissionModal, batchPermissionForm, - showDeleteConfirmDialog, - deleteConfirmMessage, - showRoleConfirm, - roleConfirmMessage, loadAll, toggleSort, + applyServerSort, openCreateUserModal, openEditUserModal, saveUser, @@ -547,9 +544,5 @@ export function useUsersAdmin() { openBatchPermissionModal, submitBatchEdit, submitBatchPermission, - closeDeleteConfirm, - confirmDelete, - confirmRoleChange, - closeRoleConfirm, }; } diff --git a/frontend/src/features/admin/styles/element-trial.css b/frontend/src/features/admin/styles/element-trial.css new file mode 100644 index 00000000..bf659079 --- /dev/null +++ b/frontend/src/features/admin/styles/element-trial.css @@ -0,0 +1,110 @@ +/** + * features/admin/styles/element-trial.css + * 用途:管理端 Element Plus 的字体、字号、颜色、圆角、控件高度,以及和 Tailwind 共存的修正。 + * 依赖:tokens.css 的 --text-* / --bg-* / --border-*,element-plus 暗色变量,Tailwind preflight。 + * 逻辑:由 UsersPage、AgentsPage、KbAdminPanel 在暗色 CSS 之后引入,所以 html.dark 能盖过 Element 默认暗色。 + * 字号和颜色以本文变量为准。页面不要再用 text-sm / text-muted 改表格和按钮。 + */ + +:root, +html.dark { + --el-color-primary: #0284c7; + --el-color-primary-light-3: #4da3d6; + --el-color-primary-light-5: #81c2e3; + --el-color-primary-light-7: #b4daf0; + --el-color-primary-light-8: #cde6f4; + --el-color-primary-light-9: #e6f3fa; + --el-color-primary-dark-2: #0269a0; + --el-font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif; + --el-font-size-extra-large: 20px; + --el-font-size-large: 18px; + --el-font-size-medium: 16px; + --el-font-size-base: 14px; + --el-font-size-small: 13px; + --el-font-size-extra-small: 12px; + --el-text-color-primary: var(--text-primary); + --el-text-color-regular: var(--text-secondary); + --el-text-color-secondary: var(--text-muted); + --el-text-color-placeholder: var(--text-muted); + --el-text-color-disabled: var(--text-muted); + --el-border-color: var(--border-default); + --el-border-color-light: var(--border-subtle); + --el-border-color-lighter: var(--border-subtle); + --el-bg-color: var(--bg-surface); + --el-bg-color-overlay: var(--bg-surface); + --el-fill-color-blank: var(--bg-surface); + --el-fill-color-light: var(--bg-surface-soft); + --el-border-radius-base: 8px; + --el-component-size: 32px; +} + +.el-button { + display: inline-flex; + align-items: center; + justify-content: center; +} + +.el-button .el-icon, +.el-button svg { + display: inline-flex; + flex: none; +} + +/* Tailwind forms 会给单行输入框内部的 input 加边框。聚焦时左右两边会多出两条蓝线。 + 多行输入框的边框就画在 .el-textarea__inner 上,不能一起清掉。 */ +.el-input__inner, +.el-select__input, +.el-range-input, +.el-input__inner:hover, +.el-select__input:hover, +.el-range-input:hover, +.el-input__inner:focus, +.el-select__input:focus, +.el-range-input:focus { + border: 0; + outline: none; + background-color: transparent; + box-shadow: none; + --tw-ring-shadow: 0 0 #0000; + --tw-ring-offset-shadow: 0 0 #0000; +} + +.el-textarea__inner { + background-color: var(--el-input-bg-color, var(--el-fill-color-blank)); + box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset; +} + +.el-textarea__inner:hover { + box-shadow: 0 0 0 1px var(--el-input-hover-border-color, var(--el-border-color-hover)) inset; +} + +.el-textarea__inner:focus { + outline: none; + box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset; + --tw-ring-shadow: 0 0 #0000; + --tw-ring-offset-shadow: 0 0 #0000; +} + +/* 列表首尾列与页头 32px 对齐;分页贴在表格下方 */ +.hx-admin-table .el-table__cell:first-child .cell { + padding-left: 32px; +} + +.hx-admin-table .el-table__cell:last-child .cell { + padding-right: 32px; +} + +.hx-admin-pager { + display: flex; + justify-content: flex-end; + padding: 12px 32px; + border-top: 1px solid var(--el-border-color-lighter); +} + +/* 表单里的补充说明,字号和颜色走 Element 变量 */ +.hx-element-hint { + margin-top: 4px; + font-size: var(--el-font-size-extra-small); + line-height: 1.4; + color: var(--el-text-color-secondary); +} diff --git a/frontend/src/features/kb/components/DifyHealthDialog.vue b/frontend/src/features/kb/components/DifyHealthDialog.vue index 07db0375..7c66faf5 100644 --- a/frontend/src/features/kb/components/DifyHealthDialog.vue +++ b/frontend/src/features/kb/components/DifyHealthDialog.vue @@ -1,16 +1,20 @@  + + diff --git a/frontend/src/features/kb/components/DifySettingsDialog.vue b/frontend/src/features/kb/components/DifySettingsDialog.vue index d5f5d604..d642a5a6 100644 --- a/frontend/src/features/kb/components/DifySettingsDialog.vue +++ b/frontend/src/features/kb/components/DifySettingsDialog.vue @@ -2,17 +2,34 @@ /** * features/kb/components/DifySettingsDialog.vue * 用途:提供知识库 Dify 连接及默认同步参数的查看、编辑和保存界面。 - * 依赖:Vue 响应式 API、Vue I18n、kb.api 的 Dify 设置读写接口。 - * 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。 + * 依赖:Vue 响应式 API、Element Plus、Vue I18n、kb.api 的 Dify 设置读写接口。 + * 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。表单按连接、检索、分段三块排,密钥默认遮挡;开关行按左标题、开关、右标题、数字四列对齐。 */ -import { reactive, ref, watch } from 'vue'; +import { reactive, ref, useId, watch } from 'vue'; import { useI18n } from 'vue-i18n'; +import { + ElButton, + ElDialog, + ElForm, + ElFormItem, + ElInput, + ElInputNumber, + ElLoading, + ElOption, + ElSelect, + ElSwitch, +} from 'element-plus'; import { getKbDifySettings, updateKbDifySettings } from '../api/kb.api'; const props = defineProps<{ open: boolean }>(); const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>(); const { t } = useI18n(); +const vLoading = ElLoading.directive; +const rerankLabelId = useId(); +const topKLabelId = useId(); +const scoreSwitchLabelId = useId(); +const scoreValueLabelId = useId(); const loading = ref(false); const saving = ref(false); @@ -108,94 +125,243 @@ watch(() => props.open, (open) => { + + diff --git a/frontend/src/features/kb/components/KbAdminPanel.vue b/frontend/src/features/kb/components/KbAdminPanel.vue index 4ee393e1..1cefd037 100644 --- a/frontend/src/features/kb/components/KbAdminPanel.vue +++ b/frontend/src/features/kb/components/KbAdminPanel.vue @@ -2,28 +2,33 @@ /** * features/kb/components/KbAdminPanel.vue * 知识库配置面板(治理面:分组、Dify)。 - * 依赖:kb.api、DifySettingsDialog、DifyHealthDialog、DeleteConfirmDialog、Vue I18n。 - * 逻辑:管理控制台加载知识库分组;分组列表在主表格过滤排序,新增/编辑通过右侧抽屉提交。 + * 依赖:kb.api、Element Plus、DifySettingsDialog、DifyHealthDialog、Vue I18n。 + * 逻辑:管理控制台加载知识库分组;列表、表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。 */ import { computed, onMounted, ref, watch } from 'vue'; import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; +import { CircleCheck, Plus, Search, Setting, Tools } from '@element-plus/icons-vue'; import { - Activity, - Pencil, - Plus, - RefreshCw, - Search, - Settings, - Trash2, - Wrench, -} from 'lucide-vue-next'; + ElAlert, + ElButton, + ElConfigProvider, + ElInput, + ElLoading, + ElMessageBox, + ElPagination, + ElSpace, + ElTable, + ElTableColumn, +} from 'element-plus'; +import 'element-plus/dist/index.css'; +import 'element-plus/theme-chalk/dark/css-vars.css'; +import '@/features/admin/styles/element-trial.css'; +import { useElementProvider } from '@/features/admin/composables/useElementProvider'; import KbGroupDrawer, { type KbGroupFormValue } from './KbGroupDrawer.vue'; import DifyHealthDialog from './DifyHealthDialog.vue'; import DifySettingsDialog from './DifySettingsDialog.vue'; -import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; -import PaginationBar from '@/shared/components/PaginationBar.vue'; import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes'; import { createKbGroup, @@ -35,35 +40,42 @@ import { import { formatDateTime } from '../utils/kb-display.utils'; type GroupFilterMode = 'all' | 'withDocs' | 'empty'; -type GroupSortMode = 'updatedDesc' | 'updatedAsc' | 'docsDesc' | 'docsAsc' | 'nameAsc'; +type GroupSortKey = 'name' | 'document_count' | 'updated_at'; const router = useRouter(); const { t } = useI18n(); +const { elementLocale } = useElementProvider(); +const vLoading = ElLoading.directive; const groups = ref([]); const isSubmitting = ref(false); const isDeleting = ref(false); -const isRefreshing = ref(false); +const isRefreshing = ref(true); const editingGroupId = ref(null); const form = ref({ name: '', description: '' }); const feedback = ref(''); const feedbackType = ref<'success' | 'error' | ''>(''); const settingsDialogOpen = ref(false); const healthDialogOpen = ref(false); -const deleteDialogOpen = ref(false); const drawerOpen = ref(false); -const deletingGroup = ref(null); const searchKeyword = ref(''); const filterMode = ref('all'); -const sortMode = ref('updatedDesc'); +const sortKey = ref('updated_at'); +const sortDir = ref<'asc' | 'desc' | ''>('desc'); const currentPage = ref(1); const pageSize = ref(20); -const filterOptions: GroupFilterMode[] = ['all', 'withDocs', 'empty']; -const sortOptions: GroupSortMode[] = ['updatedDesc', 'updatedAsc', 'docsDesc', 'docsAsc', 'nameAsc']; const pageSizeOptions = [10, 20, 50, 100]; -const totalDocuments = computed(() => groups.value.reduce((total, group) => total + (group.document_count ?? 0), 0)); +/** + * 文档数表头筛选项。 + * 核心逻辑:不放「全部」;Element 筛选面板的重置会清空条件,等同于全部。 + */ +const documentFilters = computed(() => [ + { text: t('kbAdmin.filters.withDocs'), value: 'withDocs' }, + { text: t('kbAdmin.filters.empty'), value: 'empty' }, +]); + const filteredGroups = computed(() => { const keyword = searchKeyword.value.trim().toLowerCase(); const matched = groups.value.filter((group) => { @@ -77,16 +89,17 @@ const filteredGroups = computed(() => { return matchesKeyword && matchesFilter; }); + if (!sortKey.value || !sortDir.value) return matched; return [...matched].sort((a, b) => { - const docsA = a.document_count ?? 0; - const docsB = b.document_count ?? 0; - const updatedA = Date.parse(a.updated_at || '') || 0; - const updatedB = Date.parse(b.updated_at || '') || 0; - if (sortMode.value === 'updatedAsc') return updatedA - updatedB; - if (sortMode.value === 'docsDesc') return docsB - docsA; - if (sortMode.value === 'docsAsc') return docsA - docsB; - if (sortMode.value === 'nameAsc') return a.name.localeCompare(b.name, undefined, { numeric: true }); - return updatedB - updatedA; + let result = 0; + if (sortKey.value === 'name') { + result = a.name.localeCompare(b.name, undefined, { numeric: true }); + } else if (sortKey.value === 'document_count') { + result = (a.document_count ?? 0) - (b.document_count ?? 0); + } else { + result = (Date.parse(a.updated_at || '') || 0) - (Date.parse(b.updated_at || '') || 0); + } + return sortDir.value === 'asc' ? result : -result; }); }); const pagedGroups = computed(() => { @@ -94,19 +107,33 @@ const pagedGroups = computed(() => { return filteredGroups.value.slice(start, start + pageSize.value); }); +/** + * 表格空状态文案。 + * 核心逻辑:一个分组都没有时提示去创建;有分组但筛选后为空时提示调整条件。 + */ +const tableEmptyText = computed(() => ( + groups.value.length === 0 ? t('kbAdmin.groupsEmpty') : t('kbAdmin.filters.emptyResult') +)); + /** 格式化分组更新时间,避免管理台表格直接暴露后端 ISO 时间字符串。 */ const formatGroupUpdatedAt = (value?: string | null) => formatDateTime(value); -/** 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 */ +/** + * 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 + * 核心逻辑:只等分组列表;失败写入页面提示,并用 finally 关掉表格加载态。 + */ const loadData = async () => { isRefreshing.value = true; - const groupsResult = await getKbGroupsSafe(); - if (groupsResult.ok) groups.value = groupsResult.data; - else { - feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed'); - feedbackType.value = 'error'; + try { + const groupsResult = await getKbGroupsSafe(); + if (groupsResult.ok) groups.value = groupsResult.data; + else { + feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed'); + feedbackType.value = 'error'; + } + } finally { + isRefreshing.value = false; } - isRefreshing.value = false; }; /** 重置分组表单到新建状态,关闭抽屉或切换新建时清空当前编辑对象。 */ @@ -162,17 +189,27 @@ const handleSubmitGroup = async () => { await loadData(); }; -/** 打开分组删除确认弹窗,确认前不直接调用删除接口。 */ -const handleDeleteGroup = (group: KbGroup) => { - deletingGroup.value = group; - deleteDialogOpen.value = true; -}; - -/** 确认删除当前选中的分组,并在成功后同步刷新列表与编辑表单状态。 */ -const handleDeleteGroupConfirm = async () => { - if (!deletingGroup.value) return; +/** + * 确认后删除分组,并刷新列表。 + * 核心逻辑:Element 确认框取消会 reject,这里直接返回,不调用删除接口。 + * @param group - 待删除的分组 + */ +const handleDeleteGroup = async (group: KbGroup) => { + try { + await ElMessageBox.confirm( + t('kbAdmin.deleteDialog.message', { name: group.name }), + t('kbAdmin.deleteDialog.title'), + { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }, + ); + } catch { + return; + } isDeleting.value = true; - const result = await deleteKbGroup(deletingGroup.value.id); + const result = await deleteKbGroup(group.id); isDeleting.value = false; if (!result.ok) { feedback.value = result.error || t('kbAdmin.msg.deleteFailed'); @@ -180,15 +217,46 @@ const handleDeleteGroupConfirm = async () => { return; } - if (editingGroupId.value === deletingGroup.value.id) closeDrawer(); + if (editingGroupId.value === group.id) closeDrawer(); feedback.value = t('kbAdmin.msg.deleted'); feedbackType.value = 'success'; - deleteDialogOpen.value = false; - deletingGroup.value = null; await loadData(); }; -watch([searchKeyword, filterMode, sortMode, pageSize], () => { +/** + * 按文档数表头筛选全部分组,并回到第一页。 + * 核心逻辑:筛选发生在分页之前。未选或重置时显示全部;单选时只留有文档或空分组。 + * @param filters - Element 按 column-key 给出的已选值 + */ +function onFilterChange(filters: Record): void { + const selected = filters.document_count ?? []; + if (selected.length === 1 && (selected[0] === 'withDocs' || selected[0] === 'empty')) { + filterMode.value = selected[0]; + } else { + filterMode.value = 'all'; + } + currentPage.value = 1; +} + +/** + * 按表头把筛选后的全部分组重排,并回到第一页。 + * 核心逻辑:排序发生在分页之前,所以翻页后顺序不变。第三次点击表头时 Element 清空排序,列表回到接口原顺序。 + * @param payload.prop - 列字段 + * @param payload.order - ascending、descending 或空 + */ +function onSortChange(payload: { prop: string | null; order: string | null }): void { + const field = payload.prop; + if ((field === 'name' || field === 'document_count' || field === 'updated_at') && payload.order) { + sortKey.value = field; + sortDir.value = payload.order === 'ascending' ? 'asc' : 'desc'; + } else { + sortKey.value = ''; + sortDir.value = ''; + } + currentPage.value = 1; +} + +watch([searchKeyword, pageSize], () => { currentPage.value = 1; }); @@ -200,142 +268,98 @@ defineExpose({ loadData }); + + diff --git a/frontend/src/features/kb/components/KbGroupDrawer.vue b/frontend/src/features/kb/components/KbGroupDrawer.vue index 5c50922d..d665a9ed 100644 --- a/frontend/src/features/kb/components/KbGroupDrawer.vue +++ b/frontend/src/features/kb/components/KbGroupDrawer.vue @@ -1,14 +1,16 @@