""" services/shipping_notice/reservation_service.py 用途:管理冻结订单预约单的注册、库存核验轮次和滚动制单占用。 依赖:ShippingOrderSnapshot、effective_order_view(有效订单值视图)、履约 ORM、统一 AppError。 逻辑:预约身份按「冻结快照 + 冻结后已接受人工修正」的有效值注册;每轮核验追加记录; 只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。 """ from __future__ import annotations from decimal import Decimal, InvalidOperation from typing import Any from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, ShippingOnhandVerification, ShippingOnhandVerificationLine, ShippingOrderSnapshot, ShippingOrderTask, ShippingReservation, ShippingNotice, ) from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id from app.services.shipping_notice.tool_common import log_task_event def _decimal(value: Any) -> Decimal: """将库存与需求数量转为 Decimal;零或负数均不是可履约数量。""" try: result = Decimal(str(value)) except (InvalidOperation, TypeError, ValueError) as exc: raise ValidationError('Reservation quantity is invalid', code='SHIPPING.RESERVATION_INVALID') from exc if result <= 0: raise ValidationError('Reservation quantity must be positive', code='SHIPPING.RESERVATION_INVALID') return result def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]: """ 由有效订单视图(冻结快照 + 已接受人工修正)注册全局预约号;同 PO 的料号/数量 变更按同一 OT 确认修订自动接替,跨任务或已占用预约仍走人工复核/锁定拒绝。 核心逻辑:预约身份(预约号/料号/数量)以 effective_line_facts_for_notice 的有效值为准; 否则就地编辑料号/数量后,重匹配写入的有效值与按冻结列注册的预约不一致, 核验比对必抛 RESERVATION_MISMATCH 使核验轮次无法创建、任务卡死。 行集替换等无法按行对位的场景(ValueError)保守回退冻结快照列, 由行集有效视图特性统一承接。 """ snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None if snapshot is None: raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED') po_number = normalize_po_number(snapshot.customer_po_number).upper() # [BE-有效视图] 延迟导入避免与 export 的模块级循环依赖(export 反向惰性引用本模块)。 from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice try: effective_facts = effective_line_facts_for_notice(task) except ValueError: effective_facts = {} registered: list[ShippingReservation] = [] seen: set[str] = set() for line in snapshot.lines: eff = effective_facts.get(int(line.id)) or {} # 有效事实优先,None(无规则映射/值非法)回退冻结快照列。 effective_reservation_id = eff.get('reservation_id') if eff.get('reservation_id') is not None else line.reservation_id effective_part_number = eff.get('part_number') if eff.get('part_number') is not None else line.part_number effective_qty = eff.get('qty') if eff.get('qty') is not None else line.qty reservation_id = validated_reservation_id(effective_reservation_id) part_number = str(effective_part_number or '').strip() if not reservation_id or not part_number or effective_qty is None: raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID') if reservation_id in seen: raise ConflictError('Reservation is duplicated in the frozen order', code='SHIPPING.RESERVATION_DUPLICATED_IN_ORDER') seen.add(reservation_id) row = ShippingReservation.query.filter_by(reservation_id=reservation_id).one_or_none() if row is None: row = ShippingReservation( task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id, po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(effective_qty), status='pending', ) db.session.add(row) elif not po_number: raise ValidationError( 'Purchase order is required when a reservation is already registered', code='SHIPPING.RESERVATION_PO_REQUIRED', ) elif row.po_number_normalized != po_number: raise ConflictError( 'Reservation is already registered by a different purchase order', code='SHIPPING.RESERVATION_PO_CONFLICT', details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized}, ) elif ( row.task_id != task.id or row.snapshot_line_id != line.id or row.part_number != part_number or row.required_qty != _decimal(effective_qty) ): if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}: raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED') if row.part_number != part_number or row.required_qty != _decimal(effective_qty): # 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version), # Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。 # [BE-有效视图] 编辑料号/数量后的差异在此自动完成接替,核验得以继续。 if row.task_id == task.id: _transfer_confirmed_revision(row, task=task, line=line, part_number=part_number, qty=effective_qty) registered.append(row) continue raise ConflictError( 'Reservation revision requires human confirmation', code='SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED', details={ 'reservation_id': reservation_id, 'registered_task_id': row.task_id, 'previous': {'part_number': row.part_number, 'qty': str(row.required_qty)}, 'proposed': {'part_number': part_number, 'qty': str(_decimal(effective_qty))}, }, ) raise ConflictError('Reservation is already registered by another order version', code='SHIPPING.RESERVATION_ALREADY_REGISTERED') registered.append(row) db.session.flush() return registered def _owner_task(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask: """将 Notice/OT 输入统一解析为该任务所属的 OT(shipping_order_tasks 聚合根)。""" if isinstance(task, ShippingOrderTask): return task order_task_id = getattr(task, 'order_task_id', None) owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id is not None else None if owner is None: raise ConflictError('Shipping notice has no order task', code='SHIPPING.ORDER_TASK_REQUIRED') return owner def _transfer_confirmed_revision( reservation: ShippingReservation, *, task: ShippingOrderTask, line: Any, part_number: str, qty: Any | None = None, ) -> None: """ 同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。 核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``, Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。 Args: reservation: 待接替的未履约预约单。 task: 当前归属 OT(或可解析到 OT 的任务)。 line: 预约对应的冻结快照行(修订后 snapshot_line_id 仍指向该行)。 part_number: 有效料号(已 strip)。 qty: 有效数量;缺省时回退冻结行数量 ``line.qty``(供既有调用方兼容)。 """ owner = _owner_task(task) previous = { 'task_id': reservation.task_id, 'snapshot_line_id': reservation.snapshot_line_id, 'part_number': reservation.part_number, 'qty': str(reservation.required_qty), } # 保留同一 ShippingOrderTask:版本 bump,Reservation/事件仍指向该 OT。 owner.order_data_version = int(owner.order_data_version or 1) + 1 owner.progress_version = int(owner.progress_version or 0) + 1 reservation.task_id = owner.id reservation.snapshot_line_id = line.id reservation.part_number = part_number # [BE-有效视图] 数量以有效值为准;行集替换等回退场景沿用冻结行数量。 reservation.required_qty = _decimal(qty if qty is not None else line.qty) reservation.status = 'pending' reservation.current_artifact_id = None details = { 'reservation_id': reservation.reservation_id, 'previous': previous, 'proposed': { 'task_id': owner.id, 'snapshot_line_id': line.id, 'part_number': part_number, 'qty': str(reservation.required_qty), }, } log_task_event(owner, 'reservation_revision_confirmed', details) def record_inventory_verification( task: ShippingNotice, *, inventory_snapshot_id: int | None, source_config_version: str | None, line_results: list[dict[str, Any]], ) -> ShippingOnhandVerification: """把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。""" reservations = ensure_task_reservations(task) by_key = {row.reservation_id: row for row in reservations} verification = ShippingOnhandVerification( task_id=task.id, onhand_snapshot_id=inventory_snapshot_id, source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)}, ) db.session.add(verification) db.session.flush() available_count = 0 seen_reservation_ids: set[str] = set() for item in line_results: reservation_id = validated_reservation_id(item.get('reservation_id')) part_number = str(item.get('part_number') or '').strip() reservation = by_key.get(reservation_id) # [BE-有效视图] 料号比对两侧归一化(strip + upper):匹配结果与注册值可能仅存在 # 大小写/空白差异,直接比较会造成假阳性 RESERVATION_MISMATCH 阻断核验。 if reservation is None or str(reservation.part_number or '').strip().upper() != str(part_number or '').strip().upper(): raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') required = _decimal(item.get('required_qty')) # [BE-有效视图] 数量权威是按有效订单值视图注册的预约值(非冻结快照列); # 缩量/重复的核验结果不得把短缺行升级为可导出行。 if reservation_id in seen_reservation_ids or required != reservation.required_qty: raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') seen_reservation_ids.add(reservation_id) available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') status = 'available' if available >= required else 'shortage' db.session.add(ShippingOnhandVerificationLine( verification_id=verification.id, reservation_id=reservation.id, required_qty=required, available_qty=available, status=status, detail_json={'line_status': item.get('line_status')}, )) if reservation.status == 'pending' and status == 'available': reservation.status = 'available' available_count += 1 elif reservation.status == 'available' and status == 'shortage': reservation.status = 'pending' verification.result_json = {'line_count': len(line_results), 'available_count': available_count} db.session.flush() return verification def reserve_available_for_artifact( task: ShippingNotice, *, artifact: ShippingExportArtifact, verification: ShippingOnhandVerification, released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, ) -> list[ShippingReservation]: """ 锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。 核心逻辑:默认只消费 ``available`` Reservation;调用方仅可传入从活动 ``release_onhand_shortage`` 决定解析出的冻结行 ID,使该行的 shortage Verification 作为放行审计的一部分绑定到 Artifact,其他 shortage 不得被捎带导出。 Args: task: 当前正式发货任务。 artifact: 已落库但尚未提交的导出 Artifact。 verification: 当前库存核验轮次。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时不得占用集合外行。 Returns: 本次被 Artifact 占用的预约单。 """ released_ids = {int(item) for item in (released_snapshot_line_ids or set())} verification_reservation_ids = {int(line.reservation_id) for line in verification.lines} released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() } if verification_reservation_ids and released_ids else set() verification_lines = { item.reservation_id: item for item in verification.lines if item.status == 'available' or ( item.status == 'shortage' and int(item.reservation_id) in released_reservation_ids ) } rows = ( ShippingReservation.query.filter( ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.status.in_({'available', 'pending'}), ShippingReservation.id.in_(set(verification_lines)), ) .with_for_update().all() ) if not rows: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} selected = [ item for item in rows if item.id in verification_lines and (not selected_ids or int(item.snapshot_line_id) in selected_ids) ] if not selected: raise ConflictError('Current verification has no available reservations', code='SHIPPING.ROLLING_EXPORT_NOT_READY') for reservation in selected: reservation.status = 'artifact_reserved' reservation.current_artifact_id = artifact.id db.session.add(ShippingExportArtifactLine( artifact_id=artifact.id, reservation_id=reservation.id, verification_line_id=verification_lines[reservation.id].id, )) db.session.flush() return selected def current_available_snapshot_line_ids( task: ShippingNotice, *, released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, closed_snapshot_line_ids: set[int] | None = None, ) -> tuple[ShippingOnhandVerification, set[int]]: """ 取得最新核验中可导出的冻结订单行。 核心逻辑:完整满足行始终可导出;短缺行必须同时属于调用方提供的已审计 放行集合。该函数不自行查询人工决定,避免预约层绕开导出服务的活动决定校验。 Args: task: 当前正式发货任务。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。 closed_snapshot_line_ids: 已结案冻结行 ID;无论库存状态一律从可导出集合剔除。 Returns: (最新核验轮次, 本次可导出的冻结订单行 ID)。 """ verification = ( ShippingOnhandVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') .order_by(ShippingOnhandVerification.id.desc()).first() ) if verification is None: raise ConflictError('No inventory verification is available', code='SHIPPING.ROLLING_EXPORT_NOT_READY') released_ids = {int(item) for item in (released_snapshot_line_ids or set())} verification_reservation_ids = {int(line.reservation_id) for line in verification.lines} released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() } if verification_reservation_ids and released_ids else set() reservation_ids = { line.reservation_id for line in verification.lines if line.status == 'available' or ( line.status == 'shortage' and int(line.reservation_id) in released_reservation_ids ) } reservations = ShippingReservation.query.filter( ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(reservation_ids), ShippingReservation.status.in_({'available', 'pending'}), ).all() if reservation_ids else [] selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} closed_ids = {int(item) for item in (closed_snapshot_line_ids or set())} line_ids = { item.snapshot_line_id for item in reservations if not selected_ids or int(item.snapshot_line_id) in selected_ids } - closed_ids if not line_ids: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') return verification, line_ids def _inventory_task_id(task: Any) -> int: """返回库存事实所属 OT ID;正式 Notice 通过 order_task_id 关联 OT。""" linked = getattr(task, 'order_task_id', None) return int(linked) if linked is not None else int(task.id)