337 lines
16 KiB
Python
337 lines
16 KiB
Python
"""
|
||
services/shipping_notice/reservation_service.py
|
||
|
||
用途:管理冻结订单预约单的注册、库存核验轮次和滚动制单占用。
|
||
依赖:ShippingOrderSnapshot、履约 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,
|
||
ShippingInventoryVerification,
|
||
ShippingInventoryVerificationLine,
|
||
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]:
|
||
"""由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。"""
|
||
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()
|
||
registered: list[ShippingReservation] = []
|
||
seen: set[str] = set()
|
||
for line in snapshot.lines:
|
||
reservation_id = validated_reservation_id(line.reservation_id)
|
||
part_number = str(line.part_number or '').strip()
|
||
if not reservation_id or not part_number or line.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(line.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(line.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(line.qty):
|
||
# 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version),
|
||
# Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。
|
||
if row.task_id == task.id:
|
||
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number)
|
||
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(line.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,
|
||
) -> None:
|
||
"""
|
||
同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。
|
||
|
||
核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``,
|
||
Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。
|
||
"""
|
||
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
|
||
reservation.required_qty = _decimal(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]],
|
||
) -> ShippingInventoryVerification:
|
||
"""把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。"""
|
||
reservations = ensure_task_reservations(task)
|
||
by_key = {row.reservation_id: row for row in reservations}
|
||
verification = ShippingInventoryVerification(
|
||
task_id=task.id, inventory_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)
|
||
if reservation is None or reservation.part_number != part_number:
|
||
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
|
||
required = _decimal(item.get('required_qty'))
|
||
# The frozen order is the quantity authority. A reduced or duplicate result
|
||
# must not turn an insufficient reservation into an exportable line.
|
||
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(ShippingInventoryVerificationLine(
|
||
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: ShippingInventoryVerification,
|
||
released_snapshot_line_ids: set[int] | None = None,
|
||
selected_snapshot_line_ids: set[int] | None = None,
|
||
) -> list[ShippingReservation]:
|
||
"""
|
||
锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。
|
||
|
||
核心逻辑:默认只消费 ``available`` Reservation;调用方仅可传入从活动
|
||
``release_inventory_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,
|
||
) -> tuple[ShippingInventoryVerification, set[int]]:
|
||
"""
|
||
取得最新核验中可导出的冻结订单行。
|
||
|
||
核心逻辑:完整满足行始终可导出;短缺行必须同时属于调用方提供的已审计
|
||
放行集合。该函数不自行查询人工决定,避免预约层绕开导出服务的活动决定校验。
|
||
|
||
Args:
|
||
task: 当前正式发货任务。
|
||
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
|
||
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。
|
||
|
||
Returns:
|
||
(最新核验轮次, 本次可导出的冻结订单行 ID)。
|
||
"""
|
||
verification = (
|
||
ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed')
|
||
.order_by(ShippingInventoryVerification.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())}
|
||
line_ids = {
|
||
item.snapshot_line_id for item in reservations
|
||
if not selected_ids or int(item.snapshot_line_id) in selected_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)
|