"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。 用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果/单投影)。 依赖:contracts、execution_service(serialize_order 内按需延迟引用其行聚合, 避免模块级循环导入:execution_service 顶层引用本模块的 serialize_order)。 逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移; 单(TransferDocument)投影经 serialize_order 统一(Task 11 融合卡调拨单清单 与 Task 17 已执行单查询共用同一契约源)。 """ from __future__ import annotations from typing import Any from app.services.in_transit_transfer.matching_service import item_external_lot_no # --------------------------------------------------------------------------- # 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径) # --------------------------------------------------------------------------- # success=累计产出(含重复提交成功);failed/executing/result_unknown=未完结即待办; # cancelled 不展示(无产生路径,且不在任何分组计数中)。 DOCUMENT_STATUS_GROUPS: dict[str, tuple[str, ...]] = { "success": ("success", "duplicate_success"), "failed": ("business_failed", "technical_failed"), "executing": ("pending", "executing"), "result_unknown": ("result_unknown",), } def order_status_group(status: str) -> str | None: """单状态 → 展示分组键;组外状态(cancelled)返回 None(不展示)。""" for group, statuses in DOCUMENT_STATUS_GROUPS.items(): if status in statuses: return group return None def serialize_summary(summary) -> dict[str, Any]: """匹配摘要序列化。""" return { "matching_id": summary.matching_id, "status": summary.status, "business_date": summary.business_date, "eligible_receipt_date_to": summary.eligible_receipt_date_to, "expires_at": summary.expires_at, "counts": { "file_invoice_count": summary.counts.file_invoice_count, "not_matured_count": summary.counts.not_matured_count, "matched_count": summary.counts.matched_count, "executable_count": summary.counts.executable_count, "blocked_count": summary.counts.blocked_count, # 待查行(文件已落地未查库存)与失效行(blocked_file_removed)透传 # (2026-09-25 counts 契约扩展,键名与 DTO 字段同名)。 "pending_stock_check_count": summary.counts.pending_stock_check_count, "invalid_count": summary.counts.invalid_count, }, "estimated_transfer_quantity": summary.estimated_transfer_quantity, "estimated_external_write_count": summary.estimated_external_write_count, "matching_hash": summary.matching_hash, } def serialize_item(item) -> dict[str, Any]: """明细项序列化(决策 6 十列字段 + 行装饰字段)。 行装饰字段(item_id/checked_at/stale/file_current)由 restore 按 scope 实时视图路径在 DTO 上填齐;匹配快照路径(run_matching)为缺省值 (0/None/False/False),前端按存在性展示。 """ return { "source_code": item.source_code, "material_no": item.material_no, "material_name": item.material_name, "specification": item.specification, "invoice_no": item.invoice_no, "lot_no": item.lot_no, "receipt_date": item.receipt_date, "from_warehouse": item.from_warehouse, "from_quantity": str(item.from_quantity) if item.from_quantity is not None else None, "to_warehouse": item.to_warehouse, "to_quantity": str(item.to_quantity), # 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。 "unit": item.unit, # [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行 # 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。 "external_org": item.external_org, "result": item.result, "reason": item.reason, "raw_lines": [ {"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version} for line in item.raw_lines ], "item_id": item.item_id, "checked_at": item.checked_at, "stale": item.stale, "file_current": item.file_current, } def serialize_source(source) -> dict[str, Any]: """来源进度序列化。""" return { "source_code": source.source_code, "stage": source.stage, "file_no": source.file_no, "file_version": source.file_version, "checksum": source.checksum, "error_code": source.error_code, "error_message": source.error_message, } def serialize_matching_detail(detail: dict[str, Any]) -> dict[str, Any]: """匹配恢复详情(summary + items + sources)。""" return { "summary": serialize_summary(detail["summary"]), "items": [serialize_item(item) for item in detail["items"]], "sources": [serialize_source(source) for source in detail["sources"]], } def serialize_order(doc, items: list) -> dict[str, Any]: """单投影公共序列化(Task 11 融合卡调拨单清单与 Task 17 已执行单查询共用契约源)。 【AI 触发时机】:任何需要把一张 TransferDocument(单)转成前端 JSON 的场景 (GET /runs/{run_no} 的 orders 数组、GET /documents 的单行),禁止再各自拼装。 核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量 Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个 非空原值,行级 invoice_no 随 ERP 写入行同款口径透传(2026-09-29 契约扩充); [STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内 首个非空行级 result_message,成功行/无原因为 None(前端按 「reason ?? 单 error_message」展示)。 Args: doc: TransferDocument ORM 实例。 items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。 Returns: 单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse, status, erp_document_no, error_message, lines}。 """ # 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入; # 运行期 sys.modules 已就绪)。聚合键/序与 ERP 写入行一致。 from app.services.in_transit_transfer.execution_service import _build_order_lines ordered = sorted(items, key=lambda row: row.id) aggregated = _build_order_lines(ordered) name_by_key: dict[tuple[str, str, str, str], str] = {} reason_by_key: dict[tuple[str, str, str, str], str] = {} for item in ordered: # [外部形态] join 键与 _build_order_lines 聚合键同形(批号经行所属匹配 # 快照转换规则派生),否则 WTP 前缀行的品名/原因投影 lookup 会 miss。 key = ( str(item.material_no or "").strip(), item_external_lot_no(item), str(item.from_warehouse or "").strip(), str(item.to_warehouse or "").strip(), ) name = str(item.material_name or "").strip() if name and key not in name_by_key: name_by_key[key] = name # [T13-3] 行级失败/未知原因(result_message)随行组投影;成功行为 None。 message = str(item.result_message or "").strip() if message and key not in reason_by_key: reason_by_key[key] = message return { "doc_no": doc.doc_no, "receipt_date": doc.receipt_date, "from_warehouse": doc.from_warehouse, "to_warehouse": doc.to_warehouse, "status": doc.status, "erp_document_no": doc.erp_document_no, "error_message": doc.error_message, "lines": [ { # 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径 # 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。 "invoice_no": line["invoice_no"], "material_no": line["material_no"], "material_name": name_by_key.get( (line["material_no"], line["lot_no"], line["from_warehouse"], line["to_warehouse"]), "", ), "lot_no": line["lot_no"], "quantity": line["quantity_text"], "unit": line["unit"], # [T13-3 契约] reason=行级 result_message(失败/未知行),成功行 None。 "reason": reason_by_key.get( (line["material_no"], line["lot_no"], line["from_warehouse"], line["to_warehouse"]), ), } for line in aggregated ], } def serialize_executed_order(doc, items: list) -> dict[str, Any]: """已执行单查询投影(Task 17 GET /documents orders 逐键,首页区块数据源)。 在公共单投影(serialize_order)之上补齐查询视图字段:submit_timestamp/ status_group/created_at/run_no/items(invoice 粒度行集——与融合卡的聚合 lines 不同,本视图逐 Invoice 行展示,供展开明细与影响面核对)。 run_no 为 Task 17 契约的必要补充键(契约未列但 result_unknown 行 [重新触发] 必须持 run_no 调 POST /runs/{run_no}/documents/{doc_no}/retrigger)。 """ base = serialize_order(doc, items) return { "doc_no": base["doc_no"], "submit_timestamp": doc.submit_timestamp, "status": base["status"], "status_group": order_status_group(doc.status), "receipt_date": base["receipt_date"], "from_warehouse": base["from_warehouse"], "to_warehouse": base["to_warehouse"], "erp_document_no": base["erp_document_no"], "error_message": base["error_message"], "created_at": doc.created_at.isoformat() if doc.created_at else None, "run_no": doc.run.run_no if doc.run_id and doc.run else None, "items": [ { "invoice_no": item.invoice_no, "material_no": item.material_no, "material_name": item.material_name, # 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端 # deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。 "lot_no": item.lot_no or "", "quantity": item.receipt_quantity, "unit": item.unit or "", } # 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同 # (组键含两者),按 invoice_no 升序、id 兜底稳定排序。 for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id)) ], }