""" services/shipping_notice/export.py 用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。 依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。 逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板; 导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配; 整单 ODM 裁决依次应用:客户 odm_ids 范围 → 用户选择(OT.chosen_odm_id)→ 唯一可行交集自动收敛;模板消费 odm 字段时生效; Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败; 在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。 订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。 """ from __future__ import annotations import hashlib import json import uuid from datetime import date, datetime from decimal import Decimal from pathlib import Path from typing import Any from zoneinfo import ZoneInfo from flask import current_app from openpyxl import load_workbook from openpyxl.cell.cell import MergedCell from sqlalchemy import func from app import db from app.core.errors import ConflictError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, ShippingNoticeLine, ShippingNoticeLineOnhandMatch, FreightRpaOnhandField, FreightRpaSource, ShippingOrderSnapshot, ShippingOrderField, ShippingNotice, ShippingOrderTask, ShippingCustomer, ) from app.path_utils import resolve_backend_relative_path from app.services.file_assets.storage import file_asset_storage def _released_line_indexes_for_task(order_task_id: int) -> set[int]: """按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。""" from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision rows = ( ShippingOrderReviewLineDecision.query .join( ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id, ) .filter( ShippingOrderReviewCase.confirmed_task_id == int(order_task_id), ShippingOrderReviewLineDecision.is_active.is_(True), ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ShippingOrderReviewLineDecision.line_index.isnot(None), ) .all() ) return {int(row.line_index) for row in rows} def _notice_source_code(task: ShippingNotice) -> str | None: """返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。 匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id, 传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。 已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found (如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性 裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源 (回归 OT-20261027-4BD4CEFF)。 """ task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) if task_id is None: return None task_id = int(task_id) released_line_indexes = _released_line_indexes_for_task(task_id) codes = [ str(row[0]).strip().upper() for row in db.session.query( ShippingNoticeLineOnhandMatch.source_code, ShippingNoticeLineOnhandMatch.match_result, ShippingNoticeLineOnhandMatch.line_index, ).filter( ShippingNoticeLineOnhandMatch.task_id == task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True), ShippingNoticeLineOnhandMatch.source_code.isnot(None), ).all() if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)) ] codes = list(dict.fromkeys(codes)) return codes[0] if len(codes) == 1 else None def _notice_chosen_odm(task: ShippingNotice) -> str | None: """读取当前行级匹配事实上的整单 ODM 用户选择(notice_odm_choice_service 落库)。""" task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) if task_id is None: return None values = [ str(row[0]).strip() for row in db.session.query(ShippingNoticeLineOnhandMatch.chosen_odm_id).filter( ShippingNoticeLineOnhandMatch.task_id == int(task_id), ShippingNoticeLineOnhandMatch.is_current.is_(True), ShippingNoticeLineOnhandMatch.chosen_odm_id.isnot(None), ).distinct().all() if row[0] ] return values[0] if values else None def _notice_inventory_file_id(task: ShippingNotice) -> int | None: """从 Notice 行级匹配读取本次导出的唯一库存文件。 已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时 库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。 """ task_id = getattr(task, 'order_task_id', None) if task_id is None: return None task_id = int(task_id) released_line_indexes = _released_line_indexes_for_task(task_id) ids = [ int(row[0]) for row in db.session.query( ShippingNoticeLineOnhandMatch.onhand_snapshot_id, ShippingNoticeLineOnhandMatch.match_result, ShippingNoticeLineOnhandMatch.line_index, ).filter( ShippingNoticeLineOnhandMatch.task_id == task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True), ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None), ).all() if row[0] is not None and ( row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes) ) ] ids = list(dict.fromkeys(ids)) return ids[0] if len(ids) == 1 else None def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None: """ 确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。 Args: task: 当前发货通知单。 Raises: ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。 """ if task.id is None: return existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() if existing is not None: raise ConflictError( 'A shipping notice can generate only one Excel artifact', code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED', details={ 'task_no': task.task_no, 'business_no': task.business_no, 'artifact_no': existing.artifact_no, }, ) def _storage_root() -> Path: """返回发货通知文件根目录。""" configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip() if configured: return Path(resolve_backend_relative_path(configured)) return Path(current_app.instance_path) / 'shipping_notice' def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice: """返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。""" return notice def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]: """从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。 库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。 """ from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked assert_task_not_supersession_blocked(task) owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task snapshot_id = getattr(owner, 'order_snapshot_id', None) snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于库存匹配的冻结订单快照') fields = (snapshot.schema_version.definition_json or {}).get('fields') or [] header = dict(snapshot.header_values_json or {}) lines = [ dict(line.field_values_json or {}) for line in snapshot.lines ] return header, lines def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None: """返回当前发货通知单编号;履约路径不回退到其他聚合标识。""" if task.business_no: return str(task.business_no).strip() return None def _clear_template_data_rows(ws: Any, start_row: int) -> None: """清除模板数据起始行之后的所有单元格值,保留模板表头与样式。""" for row_index in range(start_row, ws.max_row + 1): for column_index in range(1, ws.max_column + 1): cell = ws.cell(row_index, column_index) if not isinstance(cell, MergedCell): cell.value = None def _system_fact( task: ShippingNotice, key: str, *, excel_business_no: str | None = None, notice_no: str | None = None, notice_line_no: str | None = None, notice_line_warehouse_id: str | None = None, export_date: date | None = None, ) -> Any: """ 读取受控任务事实,模板不能通过任意属性路径访问 ORM。 Args: task: 发货任务。 key: 系统事实键;仅允许白名单内键。 Returns: 对应系统事实值;未知键返回 None。 """ values = { 'task_no': notice_no or task.task_no, 'business_no': notice_no or excel_business_no or task.business_no, 'warehouse_id': notice_line_warehouse_id, 'inventory_source_code': _notice_source_code(task), 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), 'notice_line_no': notice_line_no, } return values.get(key) def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bool: """判断发布模板是否实际消费任务级 ``system_fact:warehouse_id``。 模板将库位作为 ``inventory_field`` 消费时,值来自库存快照或已审计的 短缺放行补录字段;不得额外要求任务级 Warehouse ID。只有模板显式引用 系统事实时才保留该 fail-closed 门禁。 """ return any( isinstance(mapping, dict) and str(mapping.get('source_kind') or '').strip() == 'system_fact' and str(mapping.get('source_key') or '').strip() == 'warehouse_id' for mapping in mappings ) def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None: """ 从表头可写的 Notice 行推导唯一 Warehouse ID。 核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头, 多库位冲突时失败,避免把某一行的库位误写到整单表头。 Args: notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。 Returns: 唯一非空库位码;全部为空时返回 None。 Raises: ValueError: 多行存在多个不同库位。 """ warehouses = { str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper() for line in (notice_lines or []) if str(getattr(line, 'inventory_warehouse_id', None) or '').strip() } if len(warehouses) > 1: raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头') if len(warehouses) == 1: return next(iter(warehouses)) return None def _format_value(value: Any, formatter: str) -> Any: """应用发布契约允许的确定性格式化器。""" if value is None: return '' if formatter == 'upper': return str(value).upper() if formatter == 'lower': return str(value).lower() if formatter == 'date_mmddyyyy': if isinstance(value, (date, datetime)): return value.strftime('%m/%d/%Y') text = str(value).strip() for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'): try: return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y') except ValueError: continue return text if formatter == 'integer': return int(Decimal(str(value))) if formatter == 'decimal': return float(Decimal(str(value))) return str(value) if isinstance(value, (Decimal, date, datetime)) else value def _mapping_value( mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], header_values: dict[str, Any] | None = None, excel_business_no: str | None = None, notice_no: str | None = None, notice_line_no: str | None = None, notice_line_warehouse_id: str | None = None, export_date: date | None = None, field_id_by_code: dict[str, str] | None = None, ) -> Any: """ 按映射来源类型读取值;未知来源已在模板发布时被拒绝。 核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实; 通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。 Args: mapping: 已发布模板映射项。 task: 发货任务。 order_values: 当前行或表头订单字段值(field_id 为键)。 inventory_values: 当前行库存字段值。 header_values: 明细行模式下可回退的表头字段。 field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。 Returns: 经 formatter 处理后的单元格值。 """ kind = mapping['source_kind'] key = mapping['source_key'] if kind == 'order_field': value = order_values.get(key) field = db.session.get(ShippingOrderField, key) if key else None field_code = str(field.field_code or '') if field else '' if value in (None, '') and field_code == 'line_no': value = notice_line_no if value is None and mapping.get('row_mode') == 'line' and header_values is not None: value = header_values.get(key) elif kind == 'inventory_field': value = inventory_values.get(str(key)) elif kind == 'system_fact': value = _system_fact( task, key, excel_business_no=excel_business_no, notice_no=notice_no, notice_line_no=notice_line_no, notice_line_warehouse_id=notice_line_warehouse_id, export_date=export_date, ) else: value = key # 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串; # 尤其金额字段不得由数量/单价等相邻字段隐式推导或伪装为已提供。 if kind == 'order_field' and value is None: return None return _format_value(value, mapping['formatter']) def _match_text(value: Any) -> str: """规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。""" if value is None: return '' if isinstance(value, Decimal): return format(value.normalize(), 'f') return str(value).strip().casefold() def _narrow_inventory_lines_by_wanted_match_keys( inventory_lines: list[dict[str, Any]], *, inventory_field_keys: list[str], wanted_keys: set[tuple[str, ...]], ) -> list[dict[str, Any]]: """ 仅保留与本单导出行 match_keys 命中的库存行。 核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入 逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。 Args: inventory_lines: 活动库存快照行。 inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。 wanted_keys: 本单导出行规范化后的键元组集合。 Returns: 子集库存行;无候选时为空列表。 """ if not inventory_lines or not inventory_field_keys or not wanted_keys: return [] return [ row for row in inventory_lines if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys ] def _wanted_order_match_keys( order_lines: list[dict[str, Any]], *, order_field_ids: list[str], ) -> set[tuple[str, ...]]: """从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。""" wanted: set[tuple[str, ...]] = set() if not order_lines or not order_field_ids: return wanted for order_line in order_lines: key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids) if all(key): wanted.add(key) return wanted def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]: """返回模板直接引用的库存字段 ID,用于多命中一致性验证。""" raw_ids = { str(item['source_key']) for item in mappings if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field' } ids = {int(item) for item in raw_ids if item.isdigit()} if len(ids) != len(raw_ids): raise ValueError('发货模板引用的库存字段无效') rows = FreightRpaOnhandField.query.filter( FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active', ).all() if ids else [] if len(rows) != len(ids): raise ValueError('发货模板引用的库存字段已不存在') return {str(item.id) for item in rows} def _inventory_field_user_label(field_id: str) -> str: """把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。""" normalized = str(field_id or '').strip() if normalized.isdigit(): row = FreightRpaOnhandField.query.filter_by(id=int(normalized)).first() display_name = str(getattr(row, 'display_name', '') or '').strip() if row else '' if display_name: return display_name return f'库存字段(编号 {normalized or "未知"})' def _collapse_inventory_matches( rows: list[dict[str, Any]], required_fields: set[str], *, release_overrides: dict[str, Any] | None = None, ) -> dict[str, Any]: """多库存行仅在模板所需字段值一致时合并;短缺放行仅可覆盖该行已审计字段。""" if not rows: return {} resolved = dict(rows[0]) for field in required_fields: values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))} override = str((release_overrides or {}).get(field) or '').strip() if len(values) > 1: if override: resolved[field] = override continue label = _inventory_field_user_label(field) raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件') if values: resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field))) elif override: resolved[field] = override return resolved def _match_inventory_lines( order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], match_keys: list[dict[str, str]], required_fields: set[str], *, release_overrides_by_line: dict[int, dict[str, Any]] | None = None, released_export_line_indexes: set[int] | None = None, ) -> list[dict[str, Any]]: """按发布匹配键解析库存投影;已审计短缺放行可在导出时使用订单与补录事实。""" if not order_lines: return [] if not match_keys: raise ValueError('库存解析模板缺少订单与库存匹配键') normalized_keys = _normalize_match_keys(match_keys) result: list[dict[str, Any]] = [] for position, order_line in enumerate(order_lines, start=1): expected = [ (_match_text(order_line.get(item['order_field_id'])), item['inventory_field']) for item in normalized_keys ] if any(not value for value, _field in expected): raise ValueError(f'第 {position} 条订单行缺少库存匹配键值') matched = [ row for row in inventory_lines if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected) ] if not matched: # 短缺放行不改写或伪造库存匹配事实。它只授权导出阶段在匹配键 # (例如 Reservation ID)未命中时,以冻结订单字段及已审计补录值 # 写模板;模板不消费库存字段时,空映射也是完整、可审计的输入。 overrides = (release_overrides_by_line or {}).get(position - 1) or {} resolved_overrides = { field: value for field, value in overrides.items() if field in required_fields and _match_text(value) } is_released = (position - 1) in (released_export_line_indexes or set()) if is_released and set(resolved_overrides) == required_fields: result.append(resolved_overrides) continue raise ValueError(f'第 {position} 条订单行没有匹配的库存记录') result.append(_collapse_inventory_matches( matched, required_fields, release_overrides=(release_overrides_by_line or {}).get(position - 1), )) return result def _release_overrides_for_export_lines( *, line_values: list[dict[str, Any]], release_overrides_by_source_line: dict[int, dict[str, Any]], ) -> dict[int, dict[str, Any]]: """ 将冻结订单原始行索引映射为本次 Excel 连续行索引。 核心逻辑:原始首行索引 ``0`` 是有效业务值,不能以 ``or`` 回退为缺失值; 仅传递该行已审计的短缺放行字段,其他行不受影响。 Args: line_values: 已按本次可导出集合筛选的订单行,含 ``__order_line_index``。 release_overrides_by_source_line: 原始冻结订单行索引 → 放行补录字段。 Returns: Excel 连续行索引 → 放行补录字段。 """ overrides: dict[int, dict[str, Any]] = {} for export_index, row in enumerate(line_values): source_index = row.get('__order_line_index') if isinstance(source_index, bool): continue try: normalized_source_index = int(source_index) except (TypeError, ValueError): continue if normalized_source_index in release_overrides_by_source_line: overrides[export_index] = release_overrides_by_source_line[normalized_source_index] return overrides def _header_inventory_values( matched_lines: list[dict[str, Any]], required_fields: set[str], ) -> dict[str, Any]: """Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。""" return _collapse_inventory_matches(matched_lines, required_fields) def _safe_filename(name: str) -> str: """清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。""" cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.') cleaned = cleaned or 'shipment.xlsx' return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx' def _filename( task: ShippingNotice, template: ShippingExcelTemplate, *, excel_business_no: str | None = None, notice_no: str | None = None, ) -> str: """按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。""" pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip() if not pattern: pattern = str(current_app.config.get('SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN') or '').strip() if not pattern: raise ValueError('发货 Excel 文件名规则未配置') now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S') owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task customer_short_code = '' if isinstance(owner, ShippingOrderTask): from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts facts = customer_resolution_facts(owner) customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None customer_short_code = str(getattr(customer, 'short_code', None) or '') values = { 'task_no': notice_no or task.task_no, 'business_no': notice_no or excel_business_no or task.business_no or task.task_no, 'source_code': _notice_source_code(task) or '', 'ts': now, 'date': now[:8], 'customer_short_code': customer_short_code, 'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '', 'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '', } try: return _safe_filename(pattern.format(**values)) except (KeyError, ValueError) as exc: raise ValueError('发货 Excel 文件名规则无效') from exc def _input_checksum( task: ShippingNotice, source: FreightRpaSource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], notice_id: int | None = None, ) -> str: """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该外键。 report_config = source.onhand_report_config payload = { 'task_id': task.id, 'source_id': source.id, 'template_id': template.id, 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, 'parsing_profile_id': report_config.parsing_profile_id if report_config is not None else None, 'inventory_snapshot_id': _notice_inventory_file_id(task), 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, 'notice_id': notice_id, } raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(raw.encode('utf-8')).hexdigest() def _resolve_odm_inventory_field_id() -> int | None: """返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。""" field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first() return int(field.id) if field is not None else None def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, str]]: """ 校验并规范化库存解析模板匹配键为 {order_field_id, inventory_field} 列表。 Raises: ValueError: 匹配键缺失、无效或引用的库存字段已不可用。 """ ids = { int(item.get('inventory_field_id')) for item in match_keys if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit() } catalog = { str(item.id): str(item.id) for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(ids)).all() } normalized_keys: list[dict[str, str]] = [] for item in match_keys: if not isinstance(item, dict): raise ValueError('库存解析模板匹配键无效') field_id = str(item.get('inventory_field_id') or '').strip() inventory_field = catalog.get(field_id) if not inventory_field: raise ValueError('库存解析模板引用的库存字段已不可用') normalized_keys.append({ 'order_field_id': str(item.get('order_field_id') or ''), 'inventory_field': inventory_field, }) return normalized_keys def _per_line_odm_sets( order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], normalized_keys: list[dict[str, str]], odm_key: str, ) -> list[set[str]]: """逐导出行收集命中库存行的 odm 值集合;缺匹配键行与未命中行返回空集。""" sets: list[set[str]] = [] for order_line in order_lines: expected = [ (_match_text(order_line.get(item['order_field_id'])), item['inventory_field']) for item in normalized_keys ] if any(not value for value, _field in expected): sets.append(set()) continue matched = { _match_text(row.get(odm_key)) for row in inventory_lines if all(_match_text(row.get(field)) == value for value, field in expected) } matched.discard('') sets.append(matched) return sets def _intersect_odm_sets(sets: list[set[str]]) -> set[str]: """各行命中 odm 集合的交集;未命中行(空集)不参与约束,全部为空返回空集。""" active = [item for item in sets if item] if not active: return set() return set.intersection(*active) def _adjudicate_notice_odm( *, line_values: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], match_keys: list[dict[str, Any]], odm_field_id: int | None, snapshot: ShippingOrderSnapshot, chosen_odm_raw: str | None, ) -> dict[str, Any]: """ 整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。 逻辑:各行命中 odm 交集恰一个值(唯一可行解)时直接收敛并跳过客户 odm_ids 白名单(2026-10-20 白名单降级);多值时客户 ODM ID 范围非空先过滤,用户选择 (OT.chosen_odm_id)次之;范围排除全部命中或选择已失效时抛 ValueError。 Returns: {'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选, 'whitelist_applied': 是否应用了客户范围, 'chosen_odm_id': 用户选择(展示值)} Raises: ValueError: 范围排除全部命中,或用户选择在当前库存中已不存在。 """ result = { 'inventory_lines': inventory_lines, 'feasible_odm_ids': [], 'per_line_odm_ids': [], 'whitelist_applied': False, 'chosen_odm_id': None, } if odm_field_id is None: return result odm_key = str(odm_field_id) # 归一化值 → 原始展示值:候选/已选回显保留库存行原样大小写。 odm_display: dict[str, str] = {} for row in inventory_lines: raw = str(row.get(odm_key) or '').strip() if raw: odm_display.setdefault(_match_text(raw), raw) customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None customer_odm_ids = [ _match_text(value) for value in (customer.odm_ids or []) if _match_text(value) ] if customer is not None else [] chosen_odm = _match_text(chosen_odm_raw) if str(chosen_odm_raw or '').strip() else None result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None normalized_keys = _normalize_match_keys(match_keys) pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key) # [STEP] 唯一命中优先(2026-10-20 白名单降级):各行命中的 ODM 交集恰一个值时 # 直接取用,不再套客户 odm_ids 白名单——客户主数据与库存文件的口径漂移不应 # 拦下「Excel 里只有一个 ODM」的确定事实(回归 OT-20261017-184D440D)。 unique_feasible = _intersect_odm_sets(pre_odm_sets) unique_hit = len(unique_feasible) == 1 if customer_odm_ids and not unique_hit: result['whitelist_applied'] = True scope = set(customer_odm_ids) inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope] # 范围把原本有命中的行全部排除时,必须给出指向客户数据的可行动错误, # 避免回落成误导性的「没有匹配的库存记录」。 if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)): raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件') elif unique_hit: # 唯一命中即唯一可行解:绕过白名单直接收敛,多值时白名单才参与收敛。 inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in unique_feasible] # 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。 scoped_sets = ( _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key) if (customer_odm_ids and not unique_hit) else pre_odm_sets ) if chosen_odm: inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm] if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)): raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择') result['inventory_lines'] = inventory_lines result['per_line_odm_ids'] = [ sorted(odm_display.get(value, value) for value in line_set) for line_set in scoped_sets ] result['feasible_odm_ids'] = sorted( odm_display.get(value, value) for value in _intersect_odm_sets( _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key), ) ) return result def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: """ 汇集发货 Excel 导出匹配所需的只读输入;不物化、不写库。 【AI 触发时机】:generate_shipment_excel 的行匹配准备,以及工作台整单 ODM 候选投影(notice_odm_choice_service)复用,保证两者消费同一份匹配事实。 Returns: source/template/snapshot/header_values/line_values/inventory_lines/ match_keys/line_inventory_fields/header_inventory_fields/verification/ selected_snapshot_line_ids/release_overrides_by_line/released_export_line_indexes。 """ from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, ) # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 source_code = str(_notice_source_code(task) or '').strip().upper() source = FreightRpaSource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: source = None if source is None: raise ValueError('库存源不存在或已停用,不能生成发货 Excel') template = source.excel_template if template is None or template.status != 'published': raise ValueError('库存源未绑定已发布的发货 Excel 模板') # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 report_config = source.onhand_report_config profile = report_config.parsing_profile if report_config is not None else None if profile is None or profile.status != 'published': raise ValueError('库存源未绑定已发布的库存解析模板') definition = template.definition_json or {} mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] if not mappings: raise ValueError('发货 Excel 模板没有已发布的字段映射') source_notice = _source_notice_for_order_facts(task) owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice snapshot_id = getattr(owner, 'order_snapshot_id', None) snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于导出的冻结订单快照') from app.services.shipping_notice.effective_order_view import effective_order_field_values header_values, all_line_values = effective_order_field_values(task) profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else [] line_inventory_fields = _inventory_fields_by_mode(mappings, 'line') header_inventory_fields = _inventory_fields_by_mode(mappings, 'header') # [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取, # 只能补模板行级库存字段,不能污染快照或任务级库存输入。 # [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是 # 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空, # 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。 from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision order_task_id_for_decisions = int( getattr(source_notice, 'order_task_id', None) or source_notice.id ) release_overrides_by_source_line: dict[int, dict[str, Any]] = {} released_source_line_indexes: set[int] = set() if source_notice.id is not None: release_rows = ( ShippingOrderReviewLineDecision.query .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) .filter( ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions, ShippingOrderReviewLineDecision.is_active.is_(True), ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) for decision in release_rows: values = dict(decision.snapshot_json or {}).get('release_field_values') if isinstance(values, dict) and decision.line_index is not None: source_line_index = int(decision.line_index) released_source_line_indexes.add(source_line_index) release_overrides_by_source_line[source_line_index] = { str(key): value for key, value in values.items() } released_snapshot_line_ids = { int(line.id) for source_index, line in enumerate(snapshot.lines) if source_index in release_overrides_by_source_line } # [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存, # 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。 closed_snapshot_line_ids = set() if source_notice.id is not None: closed_rows = ( ShippingOrderReviewLineDecision.query .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) .filter( ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions, ShippingOrderReviewLineDecision.is_active.is_(True), ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable', ) .all() ) closed_snapshot_line_ids = { int(snapshot.lines[int(decision.line_index)].id) for decision in closed_rows if decision.line_index is not None and 0 <= int(decision.line_index) < len(snapshot.lines) } selected_snapshot_line_ids = { int(row.snapshot_line_id) for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all() if row.snapshot_line_id is not None } try: verification, available_line_ids = current_available_snapshot_line_ids( source_notice, released_snapshot_line_ids=released_snapshot_line_ids, selected_snapshot_line_ids=selected_snapshot_line_ids or None, closed_snapshot_line_ids=closed_snapshot_line_ids, ) except ConflictError: raise # [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。 line_values = [] for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)): if line.id not in available_line_ids: continue row = dict(values) row['__order_line_index'] = source_index row['__snapshot_line_id'] = int(line.id) line_values.append(row) from app.services.shipping_notice.onhand_file_store import resolve_inventory_lines_for_execution # [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part) # 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。 inventory_lines = resolve_inventory_lines_for_execution(source_notice) if (line_inventory_fields or header_inventory_fields) and match_keys and line_values: match_field_ids = { int(item.get('inventory_field_id')) for item in match_keys if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit() } catalog = { str(item.id): str(item.id) for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(match_field_ids)).all() } if match_field_ids else {} order_field_ids: list[str] = [] inventory_field_keys: list[str] = [] for item in match_keys: if not isinstance(item, dict): continue inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip()) if not inv_key: continue order_field_ids.append(str(item.get('order_field_id') or '')) inventory_field_keys.append(inv_key) if order_field_ids and inventory_field_keys: wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids) inventory_lines = _narrow_inventory_lines_by_wanted_match_keys( inventory_lines, inventory_field_keys=inventory_field_keys, wanted_keys=wanted_keys, ) release_overrides_by_line = _release_overrides_for_export_lines( line_values=line_values, release_overrides_by_source_line=release_overrides_by_source_line, ) released_export_line_indexes = { export_index for export_index, row in enumerate(line_values) if isinstance(row.get('__order_line_index'), int) and not isinstance(row.get('__order_line_index'), bool) and int(row['__order_line_index']) in released_source_line_indexes } return { 'source': source, 'template': template, 'snapshot': snapshot, 'mappings': mappings, 'source_notice': source_notice, 'header_values': header_values, 'line_values': line_values, 'inventory_lines': inventory_lines, 'match_keys': match_keys, 'line_inventory_fields': line_inventory_fields, 'header_inventory_fields': header_inventory_fields, 'verification': verification, 'released_snapshot_line_ids': released_snapshot_line_ids, 'selected_snapshot_line_ids': selected_snapshot_line_ids, 'release_overrides_by_line': release_overrides_by_line, 'released_export_line_indexes': released_export_line_indexes, } def generate_shipment_excel( task: ShippingNotice, ) -> tuple[str, str, ShippingExportArtifact]: """ 按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。 【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。 Args: chosen_odm_id: 整单 ODM ID 用户选择(本次生成的请求参数,不落库); 多 ODM 冲突时由工作台下发候选后随 Gate 动作传入,仅当其在当前库存命中时生效。 Returns: (绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。 Raises: ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。 AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。 """ from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked # OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。 from app.models import ShippingOrderTask if isinstance(task, ShippingOrderTask): from app.services.shipping_notice.shipping_notice_creation_service import ( create_shipping_notice_after_inventory_gate, ) task = create_shipping_notice_after_inventory_gate(task) if not task_is_active(task): raise ValueError('已作废或归档的任务不能生成发货 Excel') assert_task_not_supersession_blocked(task) assert_notice_has_no_export_artifact(task) inputs = prepare_export_match_inputs(task) source = inputs['source'] # s18 起解析方案绑定归 onhand_report_config 配置行;Artifact 审计外键同样取自配置行。 report_config = source.onhand_report_config template = inputs['template'] snapshot = inputs['snapshot'] mappings = inputs['mappings'] source_notice = inputs['source_notice'] header_values = inputs['header_values'] line_values = inputs['line_values'] match_keys = inputs['match_keys'] line_inventory_fields = inputs['line_inventory_fields'] header_inventory_fields = inputs['header_inventory_fields'] inventory_lines = inputs['inventory_lines'] verification = inputs['verification'] released_snapshot_line_ids = inputs['released_snapshot_line_ids'] selected_snapshot_line_ids = inputs['selected_snapshot_line_ids'] release_overrides_by_line = inputs['release_overrides_by_line'] released_export_line_indexes = inputs['released_export_line_indexes'] export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date() # [STEP 3.5] 整单 ODM 裁决:客户 ODM ID 范围 → 用户选择 → 唯一可行交集自动收敛。 odm_field_id = ( _resolve_odm_inventory_field_id() if (line_inventory_fields or header_inventory_fields) else None ) adjudication = _adjudicate_notice_odm( line_values=line_values, inventory_lines=inventory_lines, match_keys=match_keys, odm_field_id=odm_field_id, snapshot=snapshot, chosen_odm_raw=_notice_chosen_odm(task), ) inventory_lines = adjudication['inventory_lines'] matched_inventory_lines = _match_inventory_lines( line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields, release_overrides_by_line=release_overrides_by_line, released_export_line_indexes=released_export_line_indexes, ) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values] header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields) # [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、 # 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。 from app.services.shipping_notice.order_line_no_resolver import field_id_by_code_from_definition field_id_by_code = field_id_by_code_from_definition( snapshot.schema_version.definition_json if snapshot.schema_version is not None else None, ) if not task.business_no: from app.services.shipping_notice.business_numbering_service import assign_notice_business_number assign_notice_business_number(task) excel_business_no = _excel_business_no(task, export_date=export_date) filename = _filename(task, template, excel_business_no=excel_business_no) artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}' directory_key = task.task_no directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key directory.mkdir(parents=True, exist_ok=True) path = directory / f'{artifact_no}_{filename}' template_bytes = file_asset_storage.get_bytes(template.storage_key) if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum: raise ValueError('发货 Excel 模板文件缺失或校验失败') try: path.write_bytes(template_bytes) wb = load_workbook(path) try: data_start_rows = { str(sheet): min(int(item['start_row']) for item in mappings if item['sheet'] == sheet) for sheet in {str(item['sheet']) for item in mappings} } for sheet, start_row in data_start_rows.items(): _clear_template_data_rows(wb[sheet], start_row) # [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。 notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), ).all() header_warehouse_id: str | None = None header_warehouse_resolved = False for mapping in mappings: ws = wb[mapping['sheet']] start_row = int(mapping['start_row']) column = int(mapping['target_column']) if mapping['row_mode'] == 'header': # PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。 mapping_warehouse_id = None if _template_requires_system_warehouse_id([mapping]): if not header_warehouse_resolved: header_warehouse_id = _unique_notice_warehouse_id(notice_lines) header_warehouse_resolved = True if not header_warehouse_id: raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头') mapping_warehouse_id = header_warehouse_id ws.cell(start_row, column).value = _mapping_value( mapping, task=task, order_values=header_values, inventory_values=header_inventory, excel_business_no=excel_business_no, export_date=export_date, notice_line_no=None, notice_line_warehouse_id=mapping_warehouse_id, field_id_by_code=field_id_by_code, ) continue row_count = max(len(line_values), 1) for index in range(row_count): order_line = line_values[index] if index < len(line_values) else {} inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {} ws.cell(start_row + index, column).value = _mapping_value( mapping, task=task, order_values=order_line, inventory_values=inventory_line, header_values=header_values, notice_line_no=( int(notice_lines[index].line_no) if index < len(notice_lines) and notice_lines[index].line_no is not None else None ), notice_line_warehouse_id=( notice_lines[index].inventory_warehouse_id if index < len(notice_lines) else None ), excel_business_no=excel_business_no, export_date=export_date, field_id_by_code=field_id_by_code, ) wb.save(path) finally: wb.close() content = path.read_bytes() # 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice, # 因而不得在此处替换或追加当前 Notice 的 Artifact。 artifact = ShippingExportArtifact( artifact_no=artifact_no, task_id=task.id, template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, inventory_parsing_profile_id=report_config.parsing_profile_id if report_config is not None else None, inventory_snapshot_id=_notice_inventory_file_id(task), input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, notice_id=int(task.id), ), file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(), file_size=len(content), status='ready', ) db.session.add(artifact) db.session.flush() from app.services.shipping_notice.reservation_service import reserve_available_for_artifact reserve_available_for_artifact( source_notice, artifact=artifact, verification=verification, released_snapshot_line_ids=released_snapshot_line_ids, selected_snapshot_line_ids=selected_snapshot_line_ids or None, ) return str(path), filename, artifact except Exception: if path.is_file(): path.unlink() raise