218 lines
11 KiB
Python
218 lines
11 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,
|
|
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: ShippingNotice) -> 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:
|
|
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):
|
|
if task.supersedes_task_id == row.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 _transfer_confirmed_revision(
|
|
reservation: ShippingReservation,
|
|
*, task: ShippingNotice,
|
|
line: Any,
|
|
part_number: str,
|
|
) -> None:
|
|
"""仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。"""
|
|
previous = {
|
|
'task_id': reservation.task_id,
|
|
'snapshot_line_id': reservation.snapshot_line_id,
|
|
'part_number': reservation.part_number,
|
|
'qty': str(reservation.required_qty),
|
|
}
|
|
reservation.task_id = task.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': task.id,
|
|
'snapshot_line_id': line.id,
|
|
'part_number': part_number,
|
|
'qty': str(reservation.required_qty),
|
|
},
|
|
}
|
|
log_task_event(task, 'reservation_revision_confirmed', details)
|
|
parent = db.session.get(ShippingNotice, task.supersedes_task_id)
|
|
if parent is not None:
|
|
log_task_event(parent, 'reservation_revision_superseded', 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) -> list[ShippingReservation]:
|
|
"""锁定本轮全部 available 预约单并写入 Artifact 行;并发第二次制单必须失败。"""
|
|
rows = (
|
|
ShippingReservation.query.filter_by(task_id=task.id, status='available')
|
|
.with_for_update().all()
|
|
)
|
|
if not rows:
|
|
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
|
|
verification_lines = {item.reservation_id: item for item in verification.lines if item.status == 'available'}
|
|
selected = [item for item in rows if item.id in verification_lines]
|
|
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) -> tuple[ShippingInventoryVerification, set[int]]:
|
|
"""取得最新核验中仍可用预约单的快照行;导出只能写入这个完整满足集合。"""
|
|
verification = (
|
|
ShippingInventoryVerification.query.filter_by(task_id=task.id, 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')
|
|
reservation_ids = {line.reservation_id for line in verification.lines if line.status == 'available'}
|
|
reservations = ShippingReservation.query.filter(
|
|
ShippingReservation.task_id == task.id,
|
|
ShippingReservation.id.in_(reservation_ids),
|
|
ShippingReservation.status == 'available',
|
|
).all() if reservation_ids else []
|
|
line_ids = {item.snapshot_line_id for item in reservations}
|
|
if not line_ids:
|
|
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
|
|
return verification, line_ids
|