66 lines
2.6 KiB
Python
66 lines
2.6 KiB
Python
"""在途调拨请求停止(取消剩余任务)。
|
|
|
|
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
|
|
原因必填;取消前后状态进入审计。
|
|
依赖:models、status、core.errors。
|
|
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
|
|
"""
|
|
|
|
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, 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.erp_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
|
|
run.completed_at = run.completed_at or datetime.utcnow()
|
|
db.session.commit()
|
|
return {"run_no": run.run_no, "cancelled_count": cancelled}
|