feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
hugo committed 2026-08-26 02:47:07 +08:00
1 parent 7cfd5d167e
commit 1e5aedb9ed
235 files changed
+11394 -9613

No files matched your search

@@ -2,8 +2,8 @@
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、
依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
order_review_projection(任务中心 STP retry 动作投影)。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
@@ -34,7 +34,6 @@ from app import db
from app.core.errors import ValidationError
from app.models import (
FileAsset,
ShippingCase,
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingInventoryVerification,
@@ -46,10 +45,13 @@ from app.models import (
ShippingOrderProcessingRunIntake,
ShippingOrderLine,
ShippingOrderReviewCase,
ShippingOrderSnapshot,
ShippingOrderReviewStream,
ShippingOrderSubmission,
ShippingReservation,
ShippingNotice,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingTaskEvent,
ShippingUploadAttempt,
)
@@ -83,6 +85,7 @@ from app.services.shipping_notice.task_order_field_editor import (
current_line_field_values_or_empty,
current_order_field_display_or_empty,
)
from app.services.shipping_notice.po_number import normalize_po_number
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
@@ -130,12 +133,11 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = {
}
def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]:
"""裁决建单前 Review Case 的生命周期查看入口。
def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""复用统一生命周期投影裁决 Review Case 的当前阶段与入口。
只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、
已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在
而获得订单复核、库存准备或通知完成入口。
当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。
此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。
"""
candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
@@ -144,11 +146,23 @@ def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[s
)
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
if not is_current_reviewable_candidate(candidate):
return []
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True)
has_candidate_context = is_current_reviewable_candidate(candidate)
if has_candidate_context:
return project_lifecycle(
current_gate=None,
blocking_reason=None,
has_candidate_context=True,
processing_stage='waiting_review',
)
return project_lifecycle(
current_gate=None,
blocking_reason=None,
has_candidate_context=False,
has_intake_parse_context=False,
processing_stage='document_parsing',
)
class TaskProjection(str, Enum):
@@ -211,33 +225,16 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]
def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
"""按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。"""
"""按 task_no、business_no 或数字主键精确查找 Notice。"""
value = str(task_ref or "").strip()
if not value:
return None
task = ShippingNotice.query.filter_by(task_no=value).first()
if task:
return task
case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first()
if case is not None:
visited: set[int] = set()
while case.id not in visited:
visited.add(int(case.id))
replacement = (
db.session.query(ShippingCase)
.filter_by(replaces_case_id=case.id)
.order_by(ShippingCase.id.desc())
.first()
)
if replacement is None:
break
case = replacement
return (
db.session.query(ShippingNotice)
.filter_by(shipping_case_id=case.id)
.order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc())
.first()
)
task = ShippingNotice.query.filter_by(business_no=value.upper()).first()
if task:
return task
if value.isdigit():
return db.session.get(ShippingNotice, int(value))
return None
@@ -385,9 +382,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
header = current_header_field_values_or_empty(task)
payload: dict[str, Any] = {
"task_no": task.task_no,
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"business_no": task.business_no,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
@@ -396,9 +391,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
"customer_code": header.get('customer_code'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
"customer_id": task.customer_id,
"customer_name_snapshot": task.customer_name_snapshot,
"customer_short_code_snapshot": task.customer_short_code_snapshot,
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
"po_number": header.get('po_number'),
"required_date": header.get('required_date'),
@@ -535,18 +530,16 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
data = {
"id": task.id,
"task_no": task.task_no,
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"business_no": task.business_no,
"source_type": task.source_type,
"source_file_name": task.source_file_name,
"source_file_type": task.source_file_type,
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
"customer_id": task.customer_id,
"customer_name_snapshot": task.customer_name_snapshot,
"customer_short_code_snapshot": task.customer_short_code_snapshot,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
@@ -608,7 +601,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
"po_number": header.get('po_number'),
"required_date": header.get('required_date'),
"step_payload": step_payload,
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": current_line_field_values_or_empty(task),
@@ -701,7 +693,6 @@ def _todo_category_from_task_row(
ui = resolve_task_ui_state_from_fields(
review_status=getattr(row, "review_status", None),
pending_human_reason=getattr(row, "pending_human_reason", None),
shipping_case_id=getattr(row, "shipping_case_id", None),
customer_resolution_status=getattr(row, "customer_resolution_status", None),
order_snapshot_id=getattr(row, "order_snapshot_id", None),
inventory_lines_json=getattr(row, "inventory_lines_json", None),
@@ -797,6 +788,41 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
}
def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""
投影发货通知列表需要的项次、料号、数量与当前库存事实。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、
`is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。
"""
if task.id is None:
return []
matches_by_line_key = {
str(item.line_key): item
for item in ShippingNoticeLineInventoryMatch.query.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
).all()
if item.line_key
}
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
return [{
'line_no': (item.field_values_json or {}).get('line_no') or item.position,
'part_number': item.part_number,
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
'reservation_id': item.reservation_id,
'shipment_qty': str(item.required_qty) if item.required_qty is not None else None,
'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
} for item in rows]
def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None:
"""
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
@@ -888,6 +914,7 @@ def _enrich_task_center_fields(
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
data["recent_event"] = _latest_task_event_summary(task)
data["artifact_summary"] = _artifact_summary_for_task(task)
data['notice_line_summary'] = _notice_line_summary_for_task(task)
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
@@ -1055,20 +1082,103 @@ def get_task_visible_to_user(
return task
def list_freight_notice_groups_for_task(
task: ShippingNotice,
*,
user_id: int,
is_admin: bool = False,
) -> dict[str, Any]:
"""
按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。
核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的
Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未
分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。
Args:
task: 当前订单工作台已授权读取的正式 Notice。
user_id: 当前用户;非管理员仅返回其创建的 Notice。
is_admin: 管理员只读可见范围。
Returns:
包含 PO 及一行一个 business_no 的货代上传聚合投影。
"""
po_number = _notice_po_number(task)
if not po_number:
return {'po_number': None, 'items': [], 'reason': 'po_missing'}
candidates = ShippingNotice.query.filter(
ShippingNotice.deleted_at.is_(None),
ShippingNotice.lifecycle_status == 'active',
ShippingNotice.business_no.isnot(None),
)
if not is_admin:
candidates = candidates.filter(ShippingNotice.user_id == int(user_id))
items: list[dict[str, Any]] = []
for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all():
if _notice_po_number(notice) != po_number:
continue
business_no = str(notice.business_no or '').strip()
if not business_no:
continue
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
from app.services.shipping_notice.ui_state import build_task_ui_state
actions = (build_task_ui_state(notice).get('actions') or {})
available_actions = [
str(action.get('code')).strip()
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip()
]
items.append({
'business_no': business_no,
'po_number': po_number,
'upload_status': notice.upload_status,
'export_file_name': notice.export_file_name,
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
})
return {
'po_number': po_number,
'items': items,
'reason': None if items else 'no_business_notice',
}
def _notice_po_number(notice: ShippingNotice) -> str:
"""读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。"""
header = current_header_field_values_or_empty(notice)
for field_code in ('customer_po_number', 'po_number'):
normalized = normalize_po_number(header.get(field_code))
if normalized:
return normalized
snapshot = None
if notice.order_snapshot_id:
snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id)
if snapshot:
for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')):
normalized = normalize_po_number(value)
if normalized:
return normalized
candidate = (
db.session.get(ShippingOrderCandidate, notice.source_candidate_id)
if notice.source_candidate_id else None
)
normalized = normalize_po_number(getattr(candidate, 'po_number', None))
return normalized
def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool:
"""待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。"""
"""待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。"""
needle = str(customer or "").strip().lower()
if not needle:
return True
case = task.shipping_case
candidates: list[str] = []
if case is not None:
for value in (
getattr(case, "customer_name_snapshot", None),
getattr(case, "customer_short_code_snapshot", None),
):
if value:
candidates.append(str(value))
for value in (task.customer_name_snapshot, task.customer_short_code_snapshot):
if value:
candidates.append(str(value))
if task.source_file_name:
candidates.append(str(task.source_file_name))
header = current_header_field_values_or_empty(task)
@@ -1133,7 +1243,19 @@ def serialize_review_case_todo(
del is_admin
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
lifecycle_entries = _review_case_lifecycle_entries(case)
lifecycle = _review_case_lifecycle_projection(case)
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified')
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES
stage_index = next(
(index for index, item in enumerate(LIFECYCLE_STAGES)
if item.get('code') == lifecycle_stage),
0,
)
stage_definition = next(
(item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage),
{'code': lifecycle_stage, 'label': '状态待同步'},
)
source_name = None
if document is not None:
source_name = str(getattr(document, "filename", None) or "").strip() or None
@@ -1191,18 +1313,19 @@ def serialize_review_case_todo(
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
"created_at": case.created_at.isoformat() if case.created_at else None,
"ui_state": {
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
# [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case
# 状态或待办类别补造订单复核权限。
"lifecycle_stage": "order_review" if lifecycle_entries else None,
"stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)},
# [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影;
# 前端不得按 Case 状态或待办类别补造订单复核权限。
"lifecycle_stage": lifecycle_stage,
"lifecycle_entries": lifecycle_entries,
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
"intake_parse_authorized": lifecycle_stage == "intake_parse",
"checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']},
"todo": {"title": current_todo, "message": current_todo},
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
"reason": {"code": f"review_case_{case.status}", "message": current_todo},
"lifecycle_status": "active",
"process_gate": None,
"checkpoint_code": "order_review",
"checkpoint_code": lifecycle_stage,
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
"summary": {
"title": "待人工复核",
@@ -1524,11 +1647,7 @@ def _task_todo_category_sql_expr():
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
(
db.and_(
ShippingNotice.shipping_case_id.isnot(None),
db.or_(
ShippingNotice.customer_resolution_status.is_(None),
ShippingNotice.customer_resolution_status != "confirmed",
),
ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")),
),
literal("exception"),
),
@@ -1633,10 +1752,10 @@ def _todo_tasks_base_query(
if task_no:
q = q.filter(ShippingNotice.task_no == str(task_no).strip())
if customer_needle:
q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingNotice.shipping_case_id).filter(
q = q.filter(
db.or_(
ShippingCase.customer_name_snapshot.ilike(customer_like),
ShippingCase.customer_short_code_snapshot.ilike(customer_like),
ShippingNotice.customer_name_snapshot.ilike(customer_like),
ShippingNotice.customer_short_code_snapshot.ilike(customer_like),
ShippingNotice.source_file_name.ilike(customer_like),
)
)