"""在途调拨请求停止(取消剩余任务)。 用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销; 原因必填;取消前后状态进入审计。 依赖:models、status、core.errors。 逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消; Run 转取消时其名下匹配(TransferMatching)同步转 cancelled,并按 matching_id 圈定名下 ready 未建单行退役为 cancelled—— 【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配 圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled (阻断行不再占用其圈定的档记录),档记录随即释放、可被后续匹配 重新圈定;取消路径不写档(占用释放由状态判定自然达成)。 """ from __future__ import annotations from datetime import datetime from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import TransferInvoiceItem, TransferMatching, TransferRun from app.services.in_transit_transfer import status as status_machine def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict: """请求停止剩余任务。 Args: run_no: Run 编号。 reason: 取消原因(必填)。 actor_id / request_id: 审计上下文。 Returns: {"run_no": ..., "cancelled_count": ...}。 Raises: ValidationError: 原因为空。 NotFoundError: Run 不存在。 ConflictError: Run 已终态不可取消。 """ reason_value = str(reason or "").strip() if not reason_value: raise ValidationError("reason is required") run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() if run is None: raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") if run.status in { status_machine.TransferRunStatus.SUCCESS.value, status_machine.TransferRunStatus.FAILED.value, status_machine.TransferRunStatus.CANCELLED.value, }: raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE") cancelled = 0 for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no: item.status = status_machine.TransferStatus.CANCELLED.value item.result_code = "cancelled" item.result_message = reason_value cancelled += 1 active = db.session.query(TransferInvoiceItem).filter( TransferInvoiceItem.run_id == run.id, TransferInvoiceItem.status.in_([ status_machine.TransferStatus.EXECUTING.value, status_machine.TransferStatus.READY_TO_EXECUTE.value, ]), ).count() if active == 0: run.status = status_machine.TransferRunStatus.CANCELLED.value # [D17 占用释放 + 可执行行退役(规格 §9)] Run 取消时名下未终态匹配同步 # 转 cancelled,并按 matching_id 圈定其名下 items 退役: # - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定 # 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双 # 执行=同批档记录二次写 ERP); # - blocked 行保留阻断解释(不占执行面),其占用 # 随匹配状态=cancelled 释放(占用判定见 matching_service); # - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。 # 取消路径不写档(占用释放由状态判定自然达成)。 for matching in db.session.query(TransferMatching).filter_by(run_id=run.id).all(): if matching.status in {"success", "failed", "cancelled", "expired"}: continue matching.status = status_machine.TransferRunStatus.CANCELLED.value for item in db.session.query(TransferInvoiceItem).filter_by(matching_id=matching.id).all(): if ( item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no ): item.status = status_machine.TransferStatus.CANCELLED.value item.result_code = "cancelled" item.result_message = reason_value cancelled += 1 run.completed_at = run.completed_at or datetime.utcnow() db.session.commit() return {"run_no": run.run_no, "cancelled_count": cancelled}