feat(shipping-order): 增加客户事实、编辑窗口与正式通知创建服务

This commit is contained in:
hugo committed 2026-09-04 22:00:27 +08:00
1 parent 4e8b2f8db2
commit bffcd55b40
17 files changed
+738 -486

No files matched your search

@@ -23,7 +23,7 @@ from app.models import (
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingOrderTask,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
@@ -62,10 +62,19 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
'shipping_notices': (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == customer.id,
)
.distinct()
.count()
),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
@@ -25,6 +25,8 @@ from app.models import (
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
ShippingOrderTask,
ShippingCustomerShadowResolution,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -144,7 +146,16 @@ def serialize_customer(
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
'notice_count': notice_count if notice_count is not None else (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == record.id,
)
.distinct()
.count()
),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
@@ -174,8 +185,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
items、total、page、page_size、pages。
"""
notice_counts = (
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.group_by(ShippingNotice.customer_id)
db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id)
.filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None))
.group_by(ShippingCustomerShadowResolution.confirmed_customer_id)
.subquery()
)
identifier_counts = (
@@ -0,0 +1,76 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
"""按 OT、Notice 或 Candidate 读取正式客户识别结果,不回读 bill_to 或解析摘要。"""
candidate_id = getattr(task, 'id', None) if isinstance(task, ShippingOrderCandidate) else getattr(task, 'candidate_id', None)
if candidate_id is None:
order_task_id = getattr(task, 'order_task_id', None)
order_task = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
candidate_id = getattr(order_task, 'candidate_id', None)
if candidate_id is None:
return None
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(candidate_id)).one_or_none()
def resolution_for_extraction(extraction_id: int | None) -> ShippingCustomerShadowResolution | None:
"""按当前 Extraction 找到关联 Candidate 的唯一客户识别结果。"""
if extraction_id is None:
return None
candidate = ShippingOrderCandidate.query.filter_by(order_extraction_id=int(extraction_id)).one_or_none()
return resolution_for_task(candidate) if candidate is not None else None
def customer_resolution_facts(task: Any) -> dict[str, Any]:
"""返回流程 Gate 所需的最小客户确认事实,缺失时 fail-closed。"""
resolution = resolution_for_task(task)
if resolution is None:
return {'customer_id': None, 'status': None, 'resolution': None}
return {
'customer_id': resolution.confirmed_customer_id,
'status': resolution.status,
'resolution': resolution,
}
def confirm_customer_resolution(
task: Any,
*,
customer_id: int,
actor_id: int | None,
method: str,
reason: str | None = None,
) -> ShippingCustomerShadowResolution:
"""确认当前识别结果的客户;人工或自动确认均保留原始证据、规则和候选快照。"""
resolution = resolution_for_task(task)
if resolution is None:
raise ConflictError('Customer resolution is required before confirmation', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
resolution.confirmed_customer_id = int(customer.id)
resolution.confirmation_method = str(method)
resolution.confirmation_reason = str(reason or '').strip() or None
resolution.confirmed_by_id = actor_id
resolution.confirmed_at = datetime.utcnow()
resolution.status = 'confirmed'
db.session.flush()
return resolution
@@ -0,0 +1,182 @@
"""
services/shipping_notice/order_edit_window_service.py
用途:确认后、Excel 生成前的订单编辑窗谓词(设计 D10 / §3.1)。集中判定哪些头字段/行字段允许编辑,
前端 fail-closed 渲染,后端保存守卫复用同一谓词。
依赖:ShippingNotice / ShippingExportArtifact / ShippingOrderReviewWaveLine / progress_workflow。
逻辑(§3.1 矩阵):
header = 该订单**任一通知**无 Export Artifact 且无活动 Gate Attempt;
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制,D10)。
编辑窗谓词收敛在单一服务,避免「用户不修改原始订单」原则被扩大解释(D12)。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingNotice, ShippingOrderTask
from app.models.shipping_excel_template import ShippingExportArtifact
# 导出产物一旦落库即视为 Excel 已生成(锁定边界 D7);上传中/已上传同属生成后。
_ARTIFACT_LOCK_STATUSES = frozenset({'ready', 'uploading', 'uploaded', 'succeeded', 'success'})
def _notice_has_export_artifact(notice: ShippingNotice) -> bool:
"""该通知是否已生成导出产物(Excel)。"""
if getattr(notice, 'id', None) is None:
return False
row = (
ShippingExportArtifact.query
.filter(ShippingExportArtifact.task_id == int(notice.id))
.order_by(ShippingExportArtifact.id.desc())
.first()
)
return bool(row is not None and str(row.status or '') in _ARTIFACT_LOCK_STATUSES)
def _notice_has_active_attempt(notice: ShippingNotice) -> bool:
"""该通知是否有活动 Gate Attempt(库存 RPA / 匹配 queued|running)。"""
from app.services.shipping_notice.progress_workflow import _has_active_gate_attempts
task = db_session_get(ShippingOrderTask, int(notice.order_task_id)) if getattr(notice, 'order_task_id', None) else None
return bool(_has_active_gate_attempts(task)) if task is not None else False
def _order_notices(notice: ShippingNotice) -> list[ShippingNotice]:
"""同一订单(同 order_task_id)下的全部通知(含波次);无 OT 指针时退回本通知。"""
order_task_id = getattr(notice, 'order_task_id', None)
if not order_task_id:
return [notice]
rows = list(
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(order_task_id))
.order_by(ShippingNotice.id.asc())
.all()
)
return rows or [notice]
def order_has_active_attempt(order_task: ShippingNotice) -> bool:
"""订单级活动 Attempt 判定:该订单**任一通知**有活动 Gate Attempt(§3.1 header 谓词)。"""
return any(_notice_has_active_attempt(n) for n in _order_notices(order_task))
def _review_case_id_for_notice(notice: ShippingNotice) -> int | None:
"""回读该通知所属复核 Case(经 ConfirmedRevision);无则 None。"""
from app.models import ShippingOrderReviewConfirmedRevision, ShippingOrderTask
task_id = getattr(notice, 'order_task_id', None)
if task_id is None:
return None
row = (
ShippingOrderReviewConfirmedRevision.query
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task_id))
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
.first()
)
return int(row.case_id) if row is not None else None
def _wave_line_to_notice_map(review_case_id: int | None) -> dict[str, int]:
"""复核 Case 下的 snapshot_line_id -> 波次通知 task_id 映射。"""
if review_case_id is None:
return {}
from app.models import ShippingOrderReviewWaveLine
rows = ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(review_case_id)).all()
return {
str(row.snapshot_line_id): int(row.task_id)
for row in rows
if row.snapshot_line_id is not None
}
def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
"""该订单可编辑范围内的全部冻结行身份(以 Snapshot 行为准,波次行并入)。"""
from app.models.shipping_notice_line import ShippingNoticeLine
notice_id = getattr(notice, 'id', None)
if notice_id is None:
return []
keys: list[str] = []
for item in (
ShippingNoticeLine.query
.filter(ShippingNoticeLine.notice_id == int(notice_id))
.order_by(ShippingNoticeLine.position.asc())
.all()
):
key = str(getattr(item, 'snapshot_line_id', '') or '').strip()
if key:
keys.append(key)
review_case_id = _review_case_id_for_notice(notice)
if review_case_id is not None:
for key in _wave_line_to_notice_map(review_case_id):
if key not in keys:
keys.append(key)
return sorted(set(keys), key=lambda value: int(value))
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
"""
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
header = 该订单全部通知(含波次)无 Export Artifact 且无活动 Gate Attempt。
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
Args:
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
Returns:
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
"""
notices = _order_notices(order_task)
order_busy = any(_notice_has_active_attempt(n) for n in notices)
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
header = (not header_has_excel) and (not order_busy)
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
lines: dict[str, bool] = {}
for snapshot_line_id in _order_snapshot_line_ids(order_task):
wave_task_id = wave_notice_map.get(snapshot_line_id)
if wave_task_id is None:
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
lines[snapshot_line_id] = not order_busy
continue
wave_notice = next((n for n in notices if int(getattr(n, 'id', 0)) == int(wave_task_id)), None)
wave_notice = wave_notice or db_session_get(ShippingNotice, int(wave_task_id))
lines[snapshot_line_id] = (
(not _notice_has_export_artifact(wave_notice)) and (not order_busy)
if wave_notice is not None else False
)
return {'header': header, 'lines': lines}
def db_session_get(model: Any, pk: int) -> Any:
"""最小 Session get 封装,避免模块顶部导入 db 形成循环。"""
from app import db
return db.session.get(model, int(pk))
def assert_field_editable(scope: dict[str, Any], *, field: dict[str, Any], snapshot_line_id: str | None = None) -> bool:
"""
保存守卫辅助:按谓词判断单个头字段/行字段是否可编辑。
Args:
scope: editable_scope 结果。
field: 目标字段描述(含 scope='header' 或 scope='line')。
snapshot_line_id: line 作用域时必填;None 视为 header。
Returns:
bool:可编辑返回 True;应被 SHIPPING.EDIT_WINDOW_FIELD_LOCKED 拒绝时返回 False。
"""
if str((field or {}).get('scope') or '').strip() == 'line':
if not snapshot_line_id:
return False
return bool(scope.get('lines', {}).get(snapshot_line_id))
return bool(scope.get('header'))
@@ -0,0 +1,160 @@
"""
backend/app/services/shipping_notice/shipping_notice_creation_service.py
用途:在库存准备与匹配门禁通过后创建正式 ShippingNotice。
依赖:ShippingOrderTask、ShippingOrderSnapshot、ShippingNoticeLine、库存匹配事实。
逻辑:OT/Snapshot 承载复核与库存准备;本模块是首次创建正式 Notice 的唯一入口,
创建 NoticeLine 后才允许进入 Excel 导出。
"""
from __future__ import annotations
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingCustomer,
ShippingNotice,
ShippingNoticeLine,
ShippingOrderTask,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.tool_common import generate_task_no
def create_shipping_notice_after_inventory_gate(
order_task: ShippingOrderTask,
*,
snapshot_line_ids: set[int] | None = None,
source_type: str = "inventory_gate",
) -> ShippingNotice:
"""
库存门禁通过后创建或复用正式发货通知。
【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。
不得在接收解析或订单复核确认阶段调用。
Args:
order_task: 已冻结订单快照的 OT。
snapshot_line_ids: 可选的本次通知行集合;为空表示整单。
source_type: Notice 来源标记。
Returns:
已 flush 的正式 ShippingNotice。
Raises:
ConflictError: OT、Snapshot、客户或库存门禁事实不完整。
"""
if order_task is None or order_task.id is None:
raise ConflictError("Order task is required before creating a shipping notice", code="SHIPPING.ORDER_TASK_REQUIRED")
snapshot_id = getattr(order_task, "order_snapshot_id", None)
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
if snapshot is None:
raise ConflictError("Order snapshot is required before creating a shipping notice", code="SHIPPING.ORDER_SNAPSHOT_REQUIRED")
customer_id = int(snapshot.customer_id or 0)
if not customer_id:
raise ConflictError("Confirmed customer is required before creating a shipping notice", code="SHIPPING.CUSTOMER_REQUIRED")
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None or customer.status != 'active':
raise ConflictError("Confirmed customer is unavailable", code="SHIPPING.CUSTOMER_REQUIRED")
selected_ids = {int(item) for item in (snapshot_line_ids or set())}
if selected_ids and not selected_ids.issubset({int(line.id) for line in snapshot.lines}):
raise ConflictError("Selected snapshot lines are invalid", code="SHIPPING.SNAPSHOT_LINE_INVALID")
existing = (
ShippingNotice.query
.filter_by(order_task_id=int(order_task.id))
.order_by(ShippingNotice.id.desc())
.first()
)
if existing is not None:
existing_lines = {
int(line.snapshot_line_id)
for line in ShippingNoticeLine.query.filter_by(notice_id=int(existing.id)).all()
if line.snapshot_line_id is not None
}
if not selected_ids or existing_lines == selected_ids:
return existing
raise ConflictError(
"An existing shipping notice already owns a different snapshot line set",
code="SHIPPING.NOTICE_LINE_SET_CONFLICT",
)
# 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时,
# OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink
fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(order_task.id), is_current=True,
).all()
target_ids = selected_ids or {int(line.id) for line in snapshot.lines}
by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task
released_ids = _released_snapshot_line_ids_for_task(order_task)
if not target_ids or any(
int(line_id) not in by_line
or (
not (
str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched'
and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready'
)
and int(line_id) not in released_ids
)
for line_id in target_ids
):
raise ConflictError(
"Inventory matching must pass before creating a shipping notice",
code="SHIPPING.INVENTORY_GATE_NOT_PASSED",
)
inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {}
for snapshot_line_id in target_ids:
match = by_line[int(snapshot_line_id)]
inventory_file = (
db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id))
if match.inventory_snapshot_id is not None
else None
)
link = (
ShippingTaskInventoryLink.query.filter_by(
task_id=int(order_task.id),
inventory_file_id=int(inventory_file.id),
matched_source_code=match.inventory_source_code,
is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
if inventory_file is not None
else None
)
inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = {
'inventory_source_code': match.inventory_source_code,
'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None,
'inventory_warehouse_id': (
str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper()
or str(getattr(inventory_file, 'warehouse_id', '') or '').strip().upper()
or None
),
}
source_codes = sorted({
str(fact['inventory_source_code'] or '').strip().upper()
for fact in inventory_facts_by_snapshot_line_id.values()
if str(fact['inventory_source_code'] or '').strip()
})
notice = ShippingNotice(
task_no=generate_task_no(),
order_task_id=int(order_task.id),
user_id=order_task.user_id,
conversation_id=order_task.conversation_id,
source_type=str(source_type or "inventory_gate"),
source_intake_id=order_task.intake_id,
source_candidate_id=order_task.candidate_id,
)
db.session.add(notice)
db.session.flush()
replace_notice_lines_from_snapshot(
notice_id=int(notice.id),
snapshot=snapshot,
snapshot_line_ids=selected_ids,
inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
)
return notice