feat(shipping-notice): 落地字段资产治理与唯一 Schema,自动建单随版本冻结
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b7307fc573
commit
3a1dbf7ce5
144 files changed
+15167
-4480
No files matched your search
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力。
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
|
||||
仅严格门禁通过的 Candidate 可物化 Task(缺字段/低置信/缺证据/重复冲突 → 拒绝)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,10 +21,55 @@ from app.services.shipping_notice.duplicate_detection import apply_duplicate_res
|
||||
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
||||
|
||||
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
评估 Candidate 是否通过 STP 严格建单门禁(不抛异常)。
|
||||
|
||||
核心逻辑:仅对 automatic 接受态施加严格门禁(缺字段、阻断冲突、低置信、缺证据、
|
||||
未解决重复)。人工复核确认(acceptance_mode=manual)不走 STP 直通门禁。
|
||||
|
||||
Args:
|
||||
candidate: 待评估订单候选。
|
||||
|
||||
Returns:
|
||||
(是否通过, 失败原因码列表)。
|
||||
"""
|
||||
if str(candidate.acceptance_mode or '') != 'automatic':
|
||||
return True, []
|
||||
reasons: list[str] = []
|
||||
if str(candidate.validation_status or '') != 'ready':
|
||||
reasons.append('incomplete_fields')
|
||||
if candidate.conflicts_json:
|
||||
reasons.append('blocking_conflict')
|
||||
missing = list(candidate.missing_fields_json or [])
|
||||
if missing:
|
||||
reasons.append('incomplete_fields')
|
||||
evidence = candidate.evidence_json
|
||||
if evidence is None or (isinstance(evidence, list) and len(evidence) == 0):
|
||||
reasons.append('missing_evidence')
|
||||
try:
|
||||
confidence = float(candidate.confidence) if candidate.confidence is not None else None
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
if confidence is not None and confidence < 0.85:
|
||||
reasons.append('low_confidence')
|
||||
dup_status = str(candidate.duplicate_status or 'unchecked')
|
||||
if dup_status not in _STP_DUPLICATE_OK:
|
||||
if str(candidate.duplicate_resolution or '') != 'open_existing':
|
||||
reasons.append('duplicate_conflict')
|
||||
return not reasons, sorted(set(reasons))
|
||||
|
||||
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
|
||||
"""统一履约门禁:只有已接受、当前且无阻断问题的 Candidate 才能建单。"""
|
||||
"""
|
||||
统一履约门禁:已接受、当前、无阻断;automatic 候选额外通过 STP 严格门禁。
|
||||
|
||||
Raises:
|
||||
ConflictError: 接受态、选中态、版本、消费态或 STP 严格门禁失败。
|
||||
"""
|
||||
if str(candidate.candidate_status or '') != 'accepted':
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED',
|
||||
@@ -40,6 +86,14 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选仍有字段冲突或未完成审核',
|
||||
)
|
||||
# [STEP] STP 严格门禁仅约束自动直通;人工确认建单已由复核草稿校验背书。
|
||||
passed, reason_codes = evaluate_candidate_stp_gate(candidate)
|
||||
if not passed:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_STP_GATE_FAILED',
|
||||
message='订单候选未通过直通建单严格门禁',
|
||||
details={'reason_codes': reason_codes},
|
||||
)
|
||||
|
||||
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
|
||||
@@ -16,7 +16,6 @@ from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref, get_task_for_user
|
||||
from app.services.shipping_notice.shipping_turn_context import resolve_shipping_task_no
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
@@ -48,6 +47,24 @@ def _require_task(ctx: TurnContext):
|
||||
return task
|
||||
|
||||
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG = (
|
||||
"该操作已迁移至工作台「我的待办」任务处理页,请从侧栏进入任务处理后再操作。"
|
||||
)
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE = "SHIPPING.CHAT_FULFILLMENT_WRITE_DISABLED"
|
||||
|
||||
|
||||
def _reject_chat_fulfillment_write() -> None:
|
||||
"""
|
||||
拒绝 Chat Turn 履约写路径,引导用户改走任务工作台。
|
||||
|
||||
核心逻辑:STP 验收要求货代上传、Excel 生成、库存匹配等写操作仅在工作台执行。
|
||||
"""
|
||||
raise ValidationError(
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG,
|
||||
code=_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
|
||||
|
||||
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
|
||||
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
|
||||
lines = [_tool_result_message(result) or "操作已完成。"]
|
||||
@@ -248,16 +265,10 @@ class ShippingGenerateExcelAction:
|
||||
action_type = "shipping.generate_excel"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "generate_excel", "label": "生成发货 Excel..."})
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no, "event_source": "chat_turn"})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "generate_excel failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = "\n".join(filter(None, [_tool_result_message(result), f"任务编号:{task.task_no}"]))
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "generate_excel"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingFreezeOrderAction:
|
||||
@@ -300,48 +311,20 @@ class ShippingRetryUploadAction:
|
||||
action_type = "shipping.retry_upload"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "retry_upload", "label": "重试上传货代..."})
|
||||
result = shipping_tools.upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "retry_upload",
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "retry_upload failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or "已触发重试上传。"
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "retry_upload"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingMatchInventoryAction:
|
||||
action_type = "shipping.match_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "match_inventory", "label": "匹配库存..."})
|
||||
result = shipping_tools.match_inventory({
|
||||
"task_id": task.task_no,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "match_inventory failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
payload = _match_result_payload(task.task_no, result)
|
||||
content = _tool_result_message(result) or "库存匹配已完成。"
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "shipping-match-result",
|
||||
"payload": payload,
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "match_inventory"})
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingConfirmInventorySourceAction:
|
||||
@@ -384,30 +367,9 @@ class ShippingMarkManualUploadedAction:
|
||||
evidence_asset_no = str(payload.get("evidence_asset_no") or "").strip()
|
||||
if not evidence_asset_no:
|
||||
raise ValidationError("evidence_asset_no is required", code="SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "mark_manual_uploaded", "label": "确认手工上传..."})
|
||||
result = shipping_tools.upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "manual_confirm",
|
||||
"event_source": "chat_turn",
|
||||
"operator_id": int(ctx.user_id),
|
||||
"evidence_asset_no": evidence_asset_no,
|
||||
"artifact_id": payload.get("artifact_id"),
|
||||
"freight_ref_no": str(payload.get("freight_ref_no") or "").strip(),
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "mark_manual_uploaded failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or f"好的,任务 {task.task_no} 已确认完成,无需再处理。"
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "text",
|
||||
"payload": {"shipping_actions_used": True},
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "mark_manual_uploaded"})
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
|
||||
@@ -17,7 +17,7 @@ from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
|
||||
|
||||
LAYOUT_PARSER_NAME = 'mineru'
|
||||
@@ -156,6 +156,27 @@ def schedule_layout_version(
|
||||
source_hash = str(document.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
return None
|
||||
# Identical files from the same owner reuse a completed layout rather than waiting for MinerU again.
|
||||
owner_id = db.session.query(ShippingNoticeIntake.user_id).filter(
|
||||
ShippingNoticeIntake.id == document.intake_id,
|
||||
).scalar()
|
||||
if not force:
|
||||
reusable_from_owner = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == owner_id,
|
||||
ShippingNoticeDocument.content_hash == source_hash,
|
||||
ShippingDocumentLayoutVersion.parser_key == current_layout_parser_key(),
|
||||
ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.finished_at.desc(), ShippingDocumentLayoutVersion.id.desc())
|
||||
.first()
|
||||
)
|
||||
if reusable_from_owner is not None:
|
||||
document.current_layout_version_id = reusable_from_owner.id
|
||||
return reusable_from_owner
|
||||
active = ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id == int(document.id),
|
||||
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
|
||||
|
||||
@@ -0,0 +1,625 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/field_asset_service.py
|
||||
|
||||
用途:货代字段资产治理——列表/详情、扩展创建与弃用恢复、标准只读校验、审计写入。
|
||||
依赖:ShippingOrderField、standard_field_registry、ShippingOrderSchemaAuditEvent、db。
|
||||
逻辑:由 admin 字段资产 API 与 Schema 采用校验调用;禁止物理删除与标准字段弃用;
|
||||
禁止将 mail/context 类编码登记为订单字段资产。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models.shipping_order_schema import ShippingOrderField, ShippingOrderSchemaAuditEvent
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
STANDARD_FIELD_SPECS,
|
||||
assert_registry_consistent,
|
||||
get_standard_field,
|
||||
is_standard_field_code,
|
||||
standard_field_codes,
|
||||
)
|
||||
|
||||
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]*$')
|
||||
FIELD_TYPES = frozenset({'string', 'decimal', 'integer', 'date', 'boolean', 'enum'})
|
||||
FORBIDDEN_CONTEXT_CODES = frozenset({
|
||||
'sender_email', 'sender_domain', 'from_email', 'from_domain',
|
||||
'mail_from', 'mail_domain',
|
||||
})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""将可空时间转换为 API ISO 字符串。"""
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def _append_audit(
|
||||
*,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
field_id: str | None,
|
||||
schema_id: int | None = None,
|
||||
before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
summary: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入追加式字段资产审计事件。"""
|
||||
db.session.add(ShippingOrderSchemaAuditEvent(
|
||||
schema_id=schema_id,
|
||||
field_id=field_id,
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
before_snapshot_json=before,
|
||||
after_snapshot_json=after,
|
||||
change_summary_json=summary or {},
|
||||
request_id=request_id,
|
||||
))
|
||||
|
||||
|
||||
def asset_payload(field: ShippingOrderField, *, adoption_index: dict[str, list[dict[str, Any]]] | None = None) -> dict[str, Any]:
|
||||
"""序列化字段资产身份与治理元数据,不含版本级识别规则。"""
|
||||
storage = _storage_descriptor(field)
|
||||
adoptions = list((adoption_index or {}).get(field.id) or [])
|
||||
return {
|
||||
'id': field.id,
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'field_category': field.field_category,
|
||||
'collection_mode': field.collection_mode,
|
||||
'asset_kind': field.asset_kind,
|
||||
'storage_mode': field.storage_mode,
|
||||
'storage_column': field.storage_column,
|
||||
'storage_table': storage['storage_table'],
|
||||
'storage_path': storage['storage_path'],
|
||||
'storage_kind': storage['storage_kind'],
|
||||
'semantic_description': field.semantic_description,
|
||||
'display_name_default': field.display_name_default,
|
||||
'fulfillment_role': field.fulfillment_role,
|
||||
'display_sequence': int(field.display_sequence or 0),
|
||||
'status': field.status,
|
||||
'published_once': bool(field.published_once),
|
||||
'retired_reason': field.retired_reason,
|
||||
'retired_at': _iso(field.retired_at),
|
||||
'restored_at': _iso(field.restored_at),
|
||||
'created_at': _iso(field.created_at),
|
||||
'updated_at': _iso(field.updated_at),
|
||||
'adoption_summary': {
|
||||
'total': len(adoptions),
|
||||
'published': sum(1 for item in adoptions if item.get('status') == 'published'),
|
||||
'draft': sum(1 for item in adoptions if item.get('status') == 'draft'),
|
||||
'retired': sum(1 for item in adoptions if item.get('status') == 'retired'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_adoption_index() -> dict[str, list[dict[str, Any]]]:
|
||||
"""一次扫描 Schema 版本,生成 field_id → 采用摘要索引,供列表页展示。"""
|
||||
from app.models.shipping_order_schema import ShippingOrderSchemaVersion
|
||||
|
||||
index: dict[str, list[dict[str, Any]]] = {}
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['draft', 'published', 'retired']),
|
||||
).all():
|
||||
family = version.schema
|
||||
for item in (version.definition_json or {}).get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
field_id = str(item.get('field_id') or '')
|
||||
if not field_id:
|
||||
continue
|
||||
index.setdefault(field_id, []).append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_id': version.schema_id,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
})
|
||||
return index
|
||||
|
||||
|
||||
def _storage_descriptor(field: ShippingOrderField) -> dict[str, str]:
|
||||
"""
|
||||
生成管理员可读的存储落点说明。
|
||||
|
||||
核心逻辑:typed_column → Snapshot 固定列;标准 json_only → Snapshot JSON(系统预置);
|
||||
扩展 → Snapshot JSON(扩展)。与「全部标准都是物理列」不同:仅投影子集为 typed。
|
||||
"""
|
||||
if field.storage_mode == 'typed_column' and field.storage_column:
|
||||
table = (
|
||||
'shipping_order_snapshots'
|
||||
if field.scope == 'header'
|
||||
else 'shipping_order_snapshot_lines'
|
||||
)
|
||||
return {
|
||||
'storage_kind': 'typed_column',
|
||||
'storage_table': table,
|
||||
'storage_path': f'{table}.{field.storage_column}',
|
||||
}
|
||||
json_column = 'header_values_json' if field.scope == 'header' else 'field_values_json'
|
||||
table = (
|
||||
'shipping_order_snapshots'
|
||||
if field.scope == 'header'
|
||||
else 'shipping_order_snapshot_lines'
|
||||
)
|
||||
kind = 'standard_json' if field.asset_kind == 'system_standard' else 'extension_json'
|
||||
return {
|
||||
'storage_kind': kind,
|
||||
'storage_table': table,
|
||||
'storage_path': f'{table}.{json_column}[{field.field_code}]',
|
||||
}
|
||||
|
||||
|
||||
def ensure_standard_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
"""
|
||||
确保 57 项标准资产已落库;缺失则补齐;已存在则强制校验锁定属性与注册表一致。
|
||||
|
||||
Returns:
|
||||
本次新插入的标准字段数量。
|
||||
|
||||
Raises:
|
||||
ConflictError: 库中标准字段的 scope/type/storage/履约角色与注册表不一致。
|
||||
"""
|
||||
assert_registry_consistent()
|
||||
existing = {
|
||||
row.field_code: row
|
||||
for row in ShippingOrderField.query.filter_by(asset_kind='system_standard').all()
|
||||
}
|
||||
inserted = 0
|
||||
for sequence, spec in enumerate(STANDARD_FIELD_SPECS.values(), start=1):
|
||||
row = existing.get(spec.field_code)
|
||||
if row is not None:
|
||||
# [STEP] 注册表是唯一事实:已存在行必须与锁定属性一致,禁止静默沿用脏数据。
|
||||
mismatches: list[str] = []
|
||||
if row.scope != spec.scope:
|
||||
mismatches.append(f'scope={row.scope!r}!={spec.scope!r}')
|
||||
if row.value_type != spec.value_type:
|
||||
mismatches.append(f'value_type={row.value_type!r}!={spec.value_type!r}')
|
||||
if row.storage_mode != spec.storage_mode:
|
||||
mismatches.append(f'storage_mode={row.storage_mode!r}!={spec.storage_mode!r}')
|
||||
if (row.storage_column or None) != (spec.storage_column or None):
|
||||
mismatches.append(f'storage_column={row.storage_column!r}!={spec.storage_column!r}')
|
||||
if (row.fulfillment_role or None) != (spec.fulfillment_role or None):
|
||||
mismatches.append(f'fulfillment_role={row.fulfillment_role!r}!={spec.fulfillment_role!r}')
|
||||
if row.status != 'active':
|
||||
mismatches.append(f'status={row.status!r}!=active')
|
||||
if mismatches:
|
||||
raise ConflictError(
|
||||
f'Standard field {spec.field_code} diverges from registry',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_DRIFT',
|
||||
details={'field_code': spec.field_code, 'mismatches': mismatches},
|
||||
)
|
||||
# 显示名/语义允许由运维同步刷新为注册表文案(非身份属性)。
|
||||
row.display_name_default = spec.display_name
|
||||
row.semantic_description = spec.semantic_description
|
||||
row.display_sequence = sequence
|
||||
continue
|
||||
db.session.add(ShippingOrderField(
|
||||
field_code=spec.field_code,
|
||||
scope=spec.scope,
|
||||
value_type=spec.value_type,
|
||||
field_category='order_header' if spec.scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction',
|
||||
asset_kind='system_standard',
|
||||
storage_mode=spec.storage_mode,
|
||||
storage_column=spec.storage_column,
|
||||
semantic_description=spec.semantic_description,
|
||||
display_name_default=spec.display_name,
|
||||
fulfillment_role=spec.fulfillment_role,
|
||||
display_sequence=sequence,
|
||||
status='active',
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
inserted += 1
|
||||
if inserted:
|
||||
db.session.flush()
|
||||
return inserted
|
||||
|
||||
|
||||
def list_assets(
|
||||
*,
|
||||
q: str | None = None,
|
||||
asset_kind: str | None = None,
|
||||
status: str | None = None,
|
||||
scope: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""列出字段资产,支持搜索与筛选。"""
|
||||
ensure_standard_assets_seeded()
|
||||
query = ShippingOrderField.query
|
||||
if asset_kind in {'system_standard', 'extension'}:
|
||||
query = query.filter_by(asset_kind=asset_kind)
|
||||
if status in {'active', 'retired'}:
|
||||
query = query.filter_by(status=status)
|
||||
if scope in {'header', 'line'}:
|
||||
query = query.filter_by(scope=scope)
|
||||
needle = str(q or '').strip().lower()
|
||||
if needle:
|
||||
like = f'%{needle}%'
|
||||
query = query.filter(or_(
|
||||
func.lower(ShippingOrderField.field_code).like(like),
|
||||
func.lower(func.coalesce(ShippingOrderField.display_name_default, '')).like(like),
|
||||
func.lower(func.coalesce(ShippingOrderField.semantic_description, '')).like(like),
|
||||
))
|
||||
rows = query.order_by(
|
||||
ShippingOrderField.asset_kind.desc(),
|
||||
ShippingOrderField.display_sequence,
|
||||
ShippingOrderField.field_code,
|
||||
).all()
|
||||
adoption_index = _build_adoption_index()
|
||||
return {
|
||||
'items': [asset_payload(item, adoption_index=adoption_index) for item in rows],
|
||||
'standard_count': sum(1 for item in rows if item.asset_kind == 'system_standard'),
|
||||
'extension_count': sum(1 for item in rows if item.asset_kind == 'extension'),
|
||||
'locked_standard_codes': sorted(standard_field_codes()),
|
||||
}
|
||||
|
||||
|
||||
def get_asset(field_id: str) -> dict[str, Any]:
|
||||
"""读取单个字段资产详情,并附带跨 Schema 族的采用摘要(published/draft/retired)。"""
|
||||
from app.models.shipping_order_schema import ShippingOrderSchemaVersion
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
payload = asset_payload(field)
|
||||
adoptions: list[dict[str, Any]] = []
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['draft', 'published', 'retired']),
|
||||
).order_by(ShippingOrderSchemaVersion.version.desc()).all():
|
||||
fields = (version.definition_json or {}).get('fields') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in fields if isinstance(item, dict)):
|
||||
family = version.schema
|
||||
adoptions.append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_id': version.schema_id,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
'schema_display_name': family.display_name if family is not None else None,
|
||||
})
|
||||
payload['adoptions'] = adoptions
|
||||
return payload
|
||||
|
||||
|
||||
def create_extension(
|
||||
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
新建扩展字段资产。
|
||||
|
||||
Raises:
|
||||
ValidationError: 编码非法、撞标准码、伪造 typed 映射或上下文编码。
|
||||
ConflictError: field_code 冲突。
|
||||
"""
|
||||
code = str(data.get('field_code') or '').strip().lower()
|
||||
scope = str(data.get('scope') or '').strip().lower()
|
||||
value_type = str(data.get('value_type') or '').strip().lower()
|
||||
display_name = str(data.get('display_name') or data.get('display_name_default') or '').strip()
|
||||
semantic = str(data.get('semantic_description') or '').strip() or None
|
||||
if not FIELD_CODE_RE.fullmatch(code):
|
||||
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if code in FORBIDDEN_CONTEXT_CODES or code.startswith('mail_') or code.startswith('sender_'):
|
||||
raise ValidationError(
|
||||
'Context/mail identifiers cannot be registered as order field assets',
|
||||
code='SHIPPING.FIELD_ASSET_CONTEXT_FORBIDDEN',
|
||||
)
|
||||
if is_standard_field_code(code):
|
||||
raise ValidationError(
|
||||
'Cannot create extension that collides with a system standard field_code',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_CODE',
|
||||
)
|
||||
if scope not in {'header', 'line'} or value_type not in FIELD_TYPES:
|
||||
raise ValidationError('scope or value_type is invalid', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if not display_name:
|
||||
raise ValidationError('display_name is required', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
if data.get('storage_mode') == 'typed_column' or data.get('storage_column'):
|
||||
raise ValidationError(
|
||||
'Extension fields cannot map to typed snapshot columns',
|
||||
code='SHIPPING.FIELD_ASSET_TYPED_FORBIDDEN',
|
||||
)
|
||||
next_sequence = (db.session.query(func.max(ShippingOrderField.display_sequence)).scalar() or 0) + 1
|
||||
field = ShippingOrderField(
|
||||
field_code=code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
field_category='order_header' if scope == 'header' else 'order_line',
|
||||
collection_mode='llm_extraction',
|
||||
asset_kind='extension',
|
||||
storage_mode='json_only',
|
||||
storage_column=None,
|
||||
semantic_description=semantic,
|
||||
display_name_default=display_name,
|
||||
display_sequence=next_sequence,
|
||||
status='active',
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(field)
|
||||
try:
|
||||
db.session.flush()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('field_code already exists', code='SHIPPING.FIELD_ASSET_CONFLICT') from exc
|
||||
payload = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_created',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
after=payload,
|
||||
summary={'field_code': code, 'scope': scope, 'value_type': value_type},
|
||||
)
|
||||
db.session.commit()
|
||||
return payload
|
||||
|
||||
|
||||
def update_extension(
|
||||
field_id: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更新扩展字段的显示属性;不可改 scope/type/code。
|
||||
|
||||
核心逻辑:要求 expected_updated_at 与当前 updated_at 一致,避免并发覆盖。
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError('System standard fields are read-only', code='SHIPPING.FIELD_ASSET_STANDARD_READONLY')
|
||||
expected = data.get('expected_updated_at')
|
||||
if expected is None or not str(expected).strip():
|
||||
raise ValidationError(
|
||||
'expected_updated_at is required',
|
||||
code='SHIPPING.FIELD_ASSET_LOCK_REQUIRED',
|
||||
details={'field': 'expected_updated_at'},
|
||||
)
|
||||
current = _iso(field.updated_at)
|
||||
if str(expected).strip() != current:
|
||||
raise ConflictError(
|
||||
'Field asset was changed by another user',
|
||||
code='SHIPPING.FIELD_ASSET_VERSION_CONFLICT',
|
||||
details={'expected_updated_at': expected, 'current_updated_at': current},
|
||||
)
|
||||
before = asset_payload(field)
|
||||
if 'display_name' in data or 'display_name_default' in data:
|
||||
name = str(data.get('display_name') or data.get('display_name_default') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('display_name is required', code='SHIPPING.FIELD_ASSET_INVALID')
|
||||
field.display_name_default = name
|
||||
if 'semantic_description' in data:
|
||||
field.semantic_description = str(data.get('semantic_description') or '').strip() or None
|
||||
for locked in ('field_code', 'scope', 'value_type', 'storage_mode', 'storage_column', 'asset_kind'):
|
||||
if locked in data and str(data.get(locked)) not in {None, '', getattr(field, locked)}:
|
||||
raise ConflictError(
|
||||
f'{locked} is immutable after creation',
|
||||
code='SHIPPING.FIELD_ASSET_IMMUTABLE',
|
||||
)
|
||||
field.updated_at = datetime.utcnow()
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_updated',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={'field_code': field.field_code},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def retire_extension(
|
||||
field_id: str,
|
||||
*,
|
||||
reason: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
confirm_impact: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
弃用扩展字段;标准字段拒绝。
|
||||
|
||||
核心逻辑:先跑影响分析;存在阻断下游时必须 confirm_impact=True 才允许弃用,
|
||||
并将影响摘要写入审计,满足弃用前可追溯。
|
||||
"""
|
||||
from app.services.shipping_notice.field_impact_analysis import analyze_field_impact
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError(
|
||||
'System standard fields cannot be retired; unadopt in Schema instead',
|
||||
code='SHIPPING.FIELD_ASSET_STANDARD_NO_RETIRE',
|
||||
)
|
||||
note = str(reason or '').strip()
|
||||
if not note:
|
||||
raise ValidationError('retire reason is required', code='SHIPPING.FIELD_ASSET_RETIRE_REASON_REQUIRED')
|
||||
if field.status == 'retired':
|
||||
return asset_payload(field)
|
||||
|
||||
impact = analyze_field_impact(field_id)
|
||||
if impact['blocking_items'] and not confirm_impact:
|
||||
raise ConflictError(
|
||||
'Extension field is still referenced by downstream configuration; confirm impact to retire',
|
||||
code='SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED',
|
||||
details=impact,
|
||||
)
|
||||
|
||||
before = asset_payload(field)
|
||||
field.status = 'retired'
|
||||
field.retired_reason = note
|
||||
field.retired_by_id = actor_id
|
||||
field.retired_at = datetime.utcnow()
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_retired',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={
|
||||
'field_code': field.field_code,
|
||||
'reason': note,
|
||||
'confirm_impact': bool(confirm_impact),
|
||||
'blocking_count': impact['blocking_count'],
|
||||
'blocking_kinds': impact['blocking_kinds'],
|
||||
'blocking_items': impact['blocking_items'],
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def restore_extension(
|
||||
field_id: str,
|
||||
*,
|
||||
reason: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""恢复已弃用扩展字段。"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.asset_kind != 'extension':
|
||||
raise ConflictError('System standard fields cannot be restored via retire flow', code='SHIPPING.FIELD_ASSET_STANDARD_READONLY')
|
||||
note = str(reason or '').strip()
|
||||
if not note:
|
||||
raise ValidationError('restore reason is required', code='SHIPPING.FIELD_ASSET_RESTORE_REASON_REQUIRED')
|
||||
if field.status == 'active':
|
||||
return asset_payload(field)
|
||||
before = asset_payload(field)
|
||||
field.status = 'active'
|
||||
field.restored_by_id = actor_id
|
||||
field.restored_at = datetime.utcnow()
|
||||
field.retired_reason = None
|
||||
after = asset_payload(field)
|
||||
_append_audit(
|
||||
event_type='extension_restored',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=field.id,
|
||||
before=before,
|
||||
after=after,
|
||||
summary={'field_code': field.field_code, 'reason': note},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def require_adoptable_asset(field_id: str) -> ShippingOrderField:
|
||||
"""
|
||||
Schema 草稿采用前校验:资产存在且 active;标准与扩展均可,retired 拒绝。
|
||||
|
||||
Raises:
|
||||
NotFoundError / ConflictError
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
if field.status != 'active':
|
||||
raise ConflictError(
|
||||
'Retired field assets cannot be adopted into a new draft',
|
||||
code='SHIPPING.FIELD_ASSET_NOT_ADOPTABLE',
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
def reorder_assets(
|
||||
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""保存全局字段资产目录顺序。"""
|
||||
ordered_ids = data.get('field_ids')
|
||||
if not isinstance(ordered_ids, list) or not ordered_ids or len(set(map(str, ordered_ids))) != len(ordered_ids):
|
||||
raise ValidationError('field_ids must be a unique non-empty list', code='SHIPPING.FIELD_ASSET_ORDER_INVALID')
|
||||
fields = ShippingOrderField.query.filter_by(status='active').all()
|
||||
by_id = {field.id: field for field in fields}
|
||||
normalized_ids = [str(field_id) for field_id in ordered_ids]
|
||||
if set(normalized_ids) != set(by_id):
|
||||
raise ValidationError('field_ids must contain all active assets', code='SHIPPING.FIELD_ASSET_ORDER_INVALID')
|
||||
before = [{'field_id': field.id, 'display_sequence': field.display_sequence} for field in fields]
|
||||
for sequence, field_id in enumerate(normalized_ids, start=1):
|
||||
by_id[field_id].display_sequence = sequence
|
||||
_append_audit(
|
||||
event_type='extension_updated',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
field_id=None,
|
||||
before={'fields': before},
|
||||
after={'fields': [
|
||||
{'field_id': field_id, 'display_sequence': index}
|
||||
for index, field_id in enumerate(normalized_ids, start=1)
|
||||
]},
|
||||
summary={'action': 'reorder'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'items': [asset_payload(by_id[field_id]) for field_id in normalized_ids]}
|
||||
|
||||
|
||||
def forbid_physical_delete() -> None:
|
||||
"""
|
||||
拒绝物理删除字段资产;扩展字段应走 retire,标准字段应取消 Schema 采用。
|
||||
|
||||
Raises:
|
||||
ConflictError: 始终抛出,供 legacy delete API 与 admin DELETE 路由使用。
|
||||
"""
|
||||
raise ConflictError(
|
||||
'Field assets cannot be physically deleted; retire extensions instead',
|
||||
code='SHIPPING.FIELD_ASSET_DELETE_FORBIDDEN',
|
||||
)
|
||||
|
||||
|
||||
def list_asset_audits(field_id: str, *, limit: int = 50) -> dict[str, Any]:
|
||||
"""
|
||||
读取单字段相关审计事件(含 Schema 采用相关事件中带 field_id 的记录)。
|
||||
|
||||
核心逻辑:补充操作人展示名,便于管理端审计时间线追溯。
|
||||
"""
|
||||
from app.models import User
|
||||
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Field asset not found', code='SHIPPING.FIELD_ASSET_NOT_FOUND')
|
||||
rows = (
|
||||
ShippingOrderSchemaAuditEvent.query
|
||||
.filter_by(field_id=field_id)
|
||||
.order_by(ShippingOrderSchemaAuditEvent.created_at.desc())
|
||||
.limit(max(1, min(int(limit or 50), 200)))
|
||||
.all()
|
||||
)
|
||||
actor_ids = {row.actor_id for row in rows if row.actor_id}
|
||||
actors = {
|
||||
user.id: (user.real_name or user.username)
|
||||
for user in User.query.filter(User.id.in_(actor_ids)).all()
|
||||
} if actor_ids else {}
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'items': [
|
||||
{
|
||||
'id': row.id,
|
||||
'event_type': row.event_type,
|
||||
'actor_id': row.actor_id,
|
||||
'actor_display_name': actors.get(row.actor_id) if row.actor_id else None,
|
||||
'request_id': row.request_id,
|
||||
'before': row.before_snapshot_json,
|
||||
'after': row.after_snapshot_json,
|
||||
'change_summary': row.change_summary_json or {},
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/field_impact_analysis.py
|
||||
|
||||
用途:汇总字段资产在下游配置与历史运行中的引用,供弃用提示与 Schema 发布门禁使用。
|
||||
依赖:库存路由/解析档案、文档模板、Excel 模板、履约策略、身份规则、提取观测表。
|
||||
逻辑:由 field_asset_service / order_schema.publish 调用;返回对象级阻断明细
|
||||
(id/名称/版本/状态/引用位置/处理入口),published/draft 配置引用为阻断,
|
||||
已完成 Run 仅作历史只读提示,不阻断发布。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.models.shipping_identity_rule import (
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityRuleSet,
|
||||
)
|
||||
|
||||
|
||||
def _ref(
|
||||
*,
|
||||
kind: str,
|
||||
object_id: str | int,
|
||||
display_name: str,
|
||||
status: str,
|
||||
version: int | str | None = None,
|
||||
reference_path: str,
|
||||
admin_path: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""组装统一的下游引用对象载荷。"""
|
||||
payload: dict[str, Any] = {
|
||||
'kind': kind,
|
||||
'object_id': object_id,
|
||||
'display_name': display_name,
|
||||
'status': status,
|
||||
'version': version,
|
||||
'reference_path': reference_path,
|
||||
'admin_path': admin_path,
|
||||
}
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _profile_reference_paths(profile: ShippingOrderDocumentProfile, field_id: str) -> list[str]:
|
||||
"""返回文档模板内引用该字段的位置描述列表。"""
|
||||
definition = profile.definition_json or {}
|
||||
paths: list[str] = []
|
||||
for index, rule in enumerate(definition.get('column_rules', []) or []):
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
for target in rule.get('target_fields', []) or []:
|
||||
if isinstance(target, dict) and str(target.get('field_id') or '') == field_id:
|
||||
paths.append(f'column_rules[{index}].target_fields')
|
||||
for table_index, table_region in enumerate(definition.get('table_regions', []) or []):
|
||||
if not isinstance(table_region, dict):
|
||||
continue
|
||||
for layout_kind in ('header_layouts', 'line_layouts'):
|
||||
for layout_index, layout in enumerate(table_region.get(layout_kind) or []):
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for region_index, field_region in enumerate(layout.get('field_regions', []) or []):
|
||||
if isinstance(field_region, dict) and str(field_region.get('field_id') or '') == field_id:
|
||||
paths.append(
|
||||
f'table_regions[{table_index}].{layout_kind}[{layout_index}]'
|
||||
f'.field_regions[{region_index}]'
|
||||
)
|
||||
return paths
|
||||
|
||||
|
||||
def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回仍会阻断配置变更的下游对象明细(draft/published 配置)。
|
||||
|
||||
不含已结束 Extraction/Run;那些只出现在 analyze_field_impact 的 historical 段。
|
||||
"""
|
||||
references: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] 库存路由条件
|
||||
routing_rows = (
|
||||
db.session.query(ShippingInventoryRoutingRuleCondition, ShippingInventoryRoutingRule)
|
||||
.join(ShippingInventoryRoutingRule)
|
||||
.filter(
|
||||
ShippingInventoryRoutingRuleCondition.order_field_id == field_id,
|
||||
ShippingInventoryRoutingRule.status.in_(['draft', 'published']),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for condition, rule in routing_rows:
|
||||
references.append(_ref(
|
||||
kind='inventory_routing_rule',
|
||||
object_id=rule.id,
|
||||
display_name=rule.rule_name or rule.rule_code or f'Rule #{rule.id}',
|
||||
status=rule.status,
|
||||
version=rule.version,
|
||||
reference_path=f'conditions[id={condition.id}].order_field_id',
|
||||
admin_path='/admin/shipping-inventory?section=routing',
|
||||
extra={'rule_code': rule.rule_code},
|
||||
))
|
||||
|
||||
# [STEP 2] 库存解析档案 match_keys
|
||||
for profile in ShippingInventoryParsingProfile.query.filter(
|
||||
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
for index, item in enumerate((profile.definition_json or {}).get('match_keys', []) or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('order_field_id') or '') != field_id:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='inventory_parsing_profile',
|
||||
object_id=profile.id,
|
||||
display_name=profile.display_name or profile.profile_code,
|
||||
status=profile.status,
|
||||
version=getattr(profile, 'version', None),
|
||||
reference_path=f'definition.match_keys[{index}].order_field_id',
|
||||
admin_path='/admin/shipping-inventory?section=parsing',
|
||||
extra={'profile_code': profile.profile_code},
|
||||
))
|
||||
|
||||
# [STEP 3] 订单文档模板
|
||||
for profile in ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
paths = _profile_reference_paths(profile, field_id)
|
||||
if not paths:
|
||||
continue
|
||||
code = getattr(profile, 'profile_code', None) or str(profile.id)
|
||||
references.append(_ref(
|
||||
kind='order_document_profile',
|
||||
object_id=profile.id,
|
||||
display_name=getattr(profile, 'display_name', None) or code,
|
||||
status=profile.status,
|
||||
version=getattr(profile, 'version', None),
|
||||
reference_path='; '.join(paths),
|
||||
admin_path=f'/admin/shipping-order-document-profiles/{code}/versions/{getattr(profile, "version", 1)}',
|
||||
extra={'profile_code': code},
|
||||
))
|
||||
|
||||
# [STEP 4] Excel 导出模板 mappings
|
||||
for template in ShippingExcelTemplate.query.filter(
|
||||
ShippingExcelTemplate.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
hit_paths: list[str] = []
|
||||
for index, item in enumerate((template.definition_json or {}).get('mappings', []) or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id:
|
||||
hit_paths.append(f'definition.mappings[{index}].source_key')
|
||||
if not hit_paths:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='excel_template',
|
||||
object_id=template.id,
|
||||
display_name=template.display_name or template.template_code,
|
||||
status=template.status,
|
||||
version=template.version,
|
||||
reference_path='; '.join(hit_paths),
|
||||
admin_path='/admin/shipping-inventory?section=excel',
|
||||
extra={'template_code': template.template_code},
|
||||
))
|
||||
|
||||
# [STEP 5] 履约策略 field_bindings
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
hit_paths: list[str] = []
|
||||
for index, item in enumerate((policy.definition_json or {}).get('field_bindings', []) or []):
|
||||
if isinstance(item, dict) and str(item.get('field_id') or '') == field_id:
|
||||
role = item.get('role') or item.get('purpose') or index
|
||||
hit_paths.append(f'definition.field_bindings[{index}]({role})')
|
||||
if not hit_paths:
|
||||
continue
|
||||
references.append(_ref(
|
||||
kind='fulfillment_policy',
|
||||
object_id=policy.id,
|
||||
display_name=getattr(policy, 'display_name', None) or f'Policy #{policy.id}',
|
||||
status=policy.status,
|
||||
version=getattr(policy, 'version', None),
|
||||
reference_path='; '.join(hit_paths),
|
||||
admin_path='/admin/shipping-inventory?section=fulfillment',
|
||||
))
|
||||
|
||||
# [STEP 6] 客户识别定义 / 规则集
|
||||
for definition in ShippingIdentityDefinition.query.filter_by(
|
||||
context_field_id=field_id, status='active',
|
||||
).all():
|
||||
references.append(_ref(
|
||||
kind='identity_definition',
|
||||
object_id=definition.id,
|
||||
display_name=definition.display_name or definition.definition_code,
|
||||
status=definition.status,
|
||||
version=None,
|
||||
reference_path='context_field_id',
|
||||
admin_path='/admin/shipping-identity-rules',
|
||||
extra={'definition_code': definition.definition_code},
|
||||
))
|
||||
for rule_set in ShippingIdentityRuleSet.query.filter(
|
||||
ShippingIdentityRuleSet.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
for index, item in enumerate((rule_set.definition_json or {}).get('definitions', []) or []):
|
||||
if isinstance(item, dict) and str(item.get('context_field_id') or '') == field_id:
|
||||
references.append(_ref(
|
||||
kind='identity_rule_set',
|
||||
object_id=rule_set.id,
|
||||
display_name=f'Identity RuleSet v{rule_set.version}',
|
||||
status=rule_set.status,
|
||||
version=rule_set.version,
|
||||
reference_path=f'definition.definitions[{index}].context_field_id',
|
||||
admin_path='/admin/shipping-identity-rules',
|
||||
))
|
||||
|
||||
return references
|
||||
|
||||
|
||||
def list_field_runtime_reference_kinds(field_id: str) -> list[str]:
|
||||
"""
|
||||
返回仍会阻断配置变更的下游 kind 列表(兼容旧调用方)。
|
||||
|
||||
不含已结束 Extraction/Run;那些只出现在 analyze_field_impact 的 historical 段。
|
||||
"""
|
||||
kinds: list[str] = []
|
||||
for item in list_field_runtime_references(field_id):
|
||||
kind = str(item.get('kind') or '')
|
||||
if kind and kind not in kinds:
|
||||
kinds.append(kind)
|
||||
return kinds
|
||||
|
||||
|
||||
def _historical_run_hint(field_id: str) -> dict[str, Any]:
|
||||
"""统计历史观测/裁决/值引用;仅提示,不阻断。"""
|
||||
observation_count = db.session.query(ShippingOrderFieldObservation.id).filter_by(field_id=field_id).count()
|
||||
decision_count = db.session.query(ShippingOrderFieldDecision.id).filter_by(field_id=field_id).count()
|
||||
value_count = db.session.query(ShippingOrderFieldValue.id).filter_by(field_id=field_id).count()
|
||||
schema_version_count = 0
|
||||
schema_versions: list[dict[str, Any]] = []
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.status.in_(['published', 'retired']),
|
||||
).all():
|
||||
fields = (version.definition_json or {}).get('fields') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in fields if isinstance(item, dict)):
|
||||
schema_version_count += 1
|
||||
family = version.schema
|
||||
schema_versions.append({
|
||||
'schema_version_id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'schema_code': family.schema_code if family is not None else None,
|
||||
'schema_display_name': family.display_name if family is not None else None,
|
||||
})
|
||||
return {
|
||||
'observation_count': observation_count,
|
||||
'decision_count': decision_count,
|
||||
'value_count': value_count,
|
||||
'immutable_schema_version_count': schema_version_count,
|
||||
'immutable_schema_versions': schema_versions,
|
||||
'blocks_publish': False,
|
||||
}
|
||||
|
||||
|
||||
def analyze_field_impact(field_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
单字段影响分析:阻断类下游对象明细 + 历史只读提示。
|
||||
|
||||
Returns:
|
||||
field_id、blocking_items、blocking_kinds、historical、can_unadopt / can_retire_extension。
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
blocking_items = list_field_runtime_references(field_id)
|
||||
blocking_kinds: list[str] = []
|
||||
for item in blocking_items:
|
||||
kind = str(item.get('kind') or '')
|
||||
if kind and kind not in blocking_kinds:
|
||||
blocking_kinds.append(kind)
|
||||
historical = _historical_run_hint(field_id)
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field.field_code if field is not None else None,
|
||||
'blocking_items': blocking_items,
|
||||
'blocking_kinds': blocking_kinds,
|
||||
'blocking_count': len(blocking_items),
|
||||
'historical': historical,
|
||||
'can_unadopt': not blocking_items,
|
||||
'can_retire_extension': (
|
||||
field is not None
|
||||
and field.asset_kind == 'extension'
|
||||
and not blocking_items
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[str]) -> dict[str, Any]:
|
||||
"""
|
||||
Schema 发布前:对「上一 published 已启用、本草稿取消采用」的字段做门禁汇总。
|
||||
|
||||
Returns:
|
||||
blocked 字段 map(含 kinds + items)、warnings、历史只读提示。
|
||||
blocked 结构:{ field_id: { kinds: [...], items: [...] } },并附 blocked_field_ids 便于前端。
|
||||
"""
|
||||
omitted = previous_field_ids - next_field_ids
|
||||
blocked: dict[str, dict[str, Any]] = {}
|
||||
warnings: list[dict[str, Any]] = []
|
||||
for field_id in sorted(omitted):
|
||||
impact = analyze_field_impact(field_id)
|
||||
if impact['blocking_items']:
|
||||
blocked[field_id] = {
|
||||
'field_id': field_id,
|
||||
'field_code': impact['field_code'],
|
||||
'kinds': list(impact['blocking_kinds']),
|
||||
'items': list(impact['blocking_items']),
|
||||
}
|
||||
elif impact['historical']['observation_count'] or impact['historical']['immutable_schema_version_count']:
|
||||
warnings.append({
|
||||
'field_id': field_id,
|
||||
'field_code': impact['field_code'],
|
||||
'historical': impact['historical'],
|
||||
'severity': 'info',
|
||||
})
|
||||
return {
|
||||
'omitted_field_ids': sorted(omitted),
|
||||
'blocked': blocked,
|
||||
'blocked_field_ids': sorted(blocked.keys()),
|
||||
'warnings': warnings,
|
||||
'can_publish': not blocked,
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
services/shipping_notice/fulfillment_policy_registry.py
|
||||
|
||||
用途:管理货代字段能力绑定与版本化滚动履约策略。
|
||||
依赖:订单 Schema、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
依赖:唯一发货订单 Schema、字段资产、履约策略模型与统一 AppError。
|
||||
逻辑:策略使用稳定 field_id 绑定货代能力;核心能力仅允许系统标准行字段;
|
||||
发布策略前必须存在已发布 Schema,且绑定字段已被采用;
|
||||
冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,9 +18,16 @@ from typing import Any
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingFulfillmentPolicy, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.standard_field_registry import (
|
||||
DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
FULFILLMENT_CORE_FIELD_CODES,
|
||||
)
|
||||
|
||||
|
||||
SHIP_AVAILABLE_ROLLING_V1 = 'SHIP_AVAILABLE_ROLLING_V1'
|
||||
_CORE_CAPABILITIES = frozenset({
|
||||
'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity',
|
||||
})
|
||||
_CAPABILITIES = {
|
||||
'fulfillment.reservation_identity': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
'fulfillment.part_number': {'scope': 'line', 'value_type': 'string', 'required': True},
|
||||
@@ -42,7 +51,15 @@ def capability_catalog() -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _schema() -> ShippingOrderSchema:
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
"""
|
||||
读取唯一发货订单 Schema(STANDARD_SHIPPING_NOTICE),兼容历史 SHIPPING_ORDER。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Schema 尚未初始化。
|
||||
"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code=DEFAULT_SCHEMA_FAMILY_CODE).one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
raise NotFoundError('Shipping order schema is not initialized', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND')
|
||||
return schema
|
||||
@@ -53,8 +70,8 @@ def _checksum(definition: dict[str, Any]) -> str:
|
||||
return hashlib.sha256(json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定,拒绝 scope/type 漂移。"""
|
||||
def _field_bindings(raw: Any, **_ignored: Any) -> list[dict[str, Any]]:
|
||||
"""校验能力与稳定 field_id 的一对一绑定;核心能力仅允许系统标准行字段。"""
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('field_bindings must be a list', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
seen_capabilities: set[str] = set()
|
||||
@@ -68,11 +85,25 @@ def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
spec = _CAPABILITIES.get(capability)
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if (
|
||||
spec is None or field is None or field.schema_id != schema_id or field.status != 'active'
|
||||
spec is None or field is None or field.status != 'active'
|
||||
or field.scope != spec['scope'] or field.value_type != spec['value_type']
|
||||
or capability in seen_capabilities or field_id in seen_fields
|
||||
):
|
||||
raise ValidationError('field capability binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID')
|
||||
expected_code = _CANONICAL_FIELD_CODES.get(capability)
|
||||
if capability in _CORE_CAPABILITIES:
|
||||
if field.asset_kind != 'system_standard' or field.field_code not in FULFILLMENT_CORE_FIELD_CODES:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capabilities require system standard line fields',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'field_code': field.field_code},
|
||||
)
|
||||
if expected_code and field.field_code != expected_code:
|
||||
raise ValidationError(
|
||||
'Core fulfillment capability must bind the canonical standard field',
|
||||
code='SHIPPING.FULFILLMENT_FIELD_INVALID',
|
||||
details={'capability_code': capability, 'expected': expected_code},
|
||||
)
|
||||
seen_capabilities.add(capability)
|
||||
seen_fields.add(field_id)
|
||||
bindings.append({
|
||||
@@ -91,7 +122,7 @@ def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]:
|
||||
return sorted(bindings, key=lambda item: item['capability_code'])
|
||||
|
||||
|
||||
def _definition(raw: dict[str, Any], *, schema_id: int) -> dict[str, Any]:
|
||||
def _definition(raw: dict[str, Any], **_ignored: Any) -> dict[str, Any]:
|
||||
"""生成可发布的受控策略定义,策略仅支持滚动发货语义。"""
|
||||
policy_code = str(raw.get('policy_code') or SHIP_AVAILABLE_ROLLING_V1).strip()
|
||||
if policy_code != SHIP_AVAILABLE_ROLLING_V1:
|
||||
@@ -101,10 +132,27 @@ def _definition(raw: dict[str, Any], *, schema_id: int) -> dict[str, Any]:
|
||||
'fulfillment_mode': 'ship_available_rolling',
|
||||
'requires_confirmed_customer': True,
|
||||
'allows_partial_reservation': False,
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings'), schema_id=schema_id),
|
||||
'field_bindings': _field_bindings(raw.get('field_bindings')),
|
||||
}
|
||||
|
||||
|
||||
def list_field_references(field_id: str) -> list[dict[str, Any]]:
|
||||
"""列出仍绑定该字段的履约策略版本,供影响分析使用。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for policy in ShippingFulfillmentPolicy.query.filter(
|
||||
ShippingFulfillmentPolicy.status.in_(['draft', 'published']),
|
||||
).all():
|
||||
bindings = (policy.definition_json or {}).get('field_bindings') or []
|
||||
if any(str(item.get('field_id') or '') == field_id for item in bindings if isinstance(item, dict)):
|
||||
items.append({
|
||||
'kind': 'fulfillment_policy',
|
||||
'policy_id': policy.id,
|
||||
'version': policy.version,
|
||||
'status': policy.status,
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]:
|
||||
"""序列化策略版本,前端只能拿到已验证定义与版本状态。"""
|
||||
return {
|
||||
@@ -116,13 +164,19 @@ def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]:
|
||||
|
||||
|
||||
def get_state() -> dict[str, Any]:
|
||||
"""读取货代履约策略管理状态及当前发布版本。"""
|
||||
"""读取唯一发货订单 Schema 的货代履约策略管理状态及当前发布版本。"""
|
||||
schema = _schema()
|
||||
policies = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).all()
|
||||
return {'capabilities': capability_catalog(), 'policies': [_payload(item) for item in policies]}
|
||||
return {
|
||||
'schema_code': schema.schema_code,
|
||||
'capabilities': capability_catalog(),
|
||||
'policies': [_payload(item) for item in policies],
|
||||
}
|
||||
|
||||
|
||||
def create_draft(raw: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
def create_draft(
|
||||
raw: dict[str, Any], *, actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建下一策略草稿;未发布策略不得参与冻结。"""
|
||||
schema = _schema()
|
||||
latest = db.session.query(ShippingFulfillmentPolicy.version).filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).first()
|
||||
@@ -136,34 +190,44 @@ def create_draft(raw: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]
|
||||
return _payload(policy)
|
||||
|
||||
|
||||
def publish(policy_id: int, *, actor_id: int | None, expected_lock_version: int | None) -> dict[str, Any]:
|
||||
"""发布策略并退役旧版本;策略字段必须存在于当前发布 Schema。"""
|
||||
def publish(
|
||||
policy_id: int, *, actor_id: int | None, expected_lock_version: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""发布策略并退役旧版本;策略字段必须存在于当前已发布 Schema。"""
|
||||
policy = db.session.get(ShippingFulfillmentPolicy, policy_id)
|
||||
if policy is None:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
schema = _schema()
|
||||
if policy.schema_id != schema.id:
|
||||
raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND')
|
||||
if policy.status != 'draft' or expected_lock_version != policy.lock_version:
|
||||
raise ConflictError('Fulfillment policy has changed', code='SHIPPING.FULFILLMENT_POLICY_CONFLICT')
|
||||
definition = _definition(dict(policy.definition_json or {}), schema_id=policy.schema_id)
|
||||
published_schema = ShippingOrderSchemaVersion.query.filter_by(
|
||||
schema_id=policy.schema_id, status='published',
|
||||
).one_or_none()
|
||||
if published_schema is not None:
|
||||
enabled_field_ids = {
|
||||
str(config.get('field_id'))
|
||||
for config in (published_schema.definition_json or {}).get('fields') or []
|
||||
if config.get('enabled', True)
|
||||
}
|
||||
missing_field_ids = sorted(
|
||||
str(binding['field_id'])
|
||||
for binding in definition['field_bindings']
|
||||
if str(binding['field_id']) not in enabled_field_ids
|
||||
if published_schema is None:
|
||||
raise ConflictError(
|
||||
'Fulfillment policy requires a published schema version',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_SCHEMA_REQUIRED',
|
||||
details={'schema_id': policy.schema_id},
|
||||
)
|
||||
enabled_field_ids = {
|
||||
str(config.get('field_id'))
|
||||
for config in (published_schema.definition_json or {}).get('fields') or []
|
||||
if config.get('enabled', True)
|
||||
}
|
||||
missing_field_ids = sorted(
|
||||
str(binding['field_id'])
|
||||
for binding in definition['field_bindings']
|
||||
if str(binding['field_id']) not in enabled_field_ids
|
||||
)
|
||||
if missing_field_ids:
|
||||
raise ValidationError(
|
||||
'Fulfillment policy fields must be included in the published schema',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'field_ids': missing_field_ids},
|
||||
)
|
||||
if missing_field_ids:
|
||||
raise ValidationError(
|
||||
'Fulfillment policy fields must be included in the published schema',
|
||||
code='SHIPPING.FULFILLMENT_POLICY_INVALID',
|
||||
details={'field_ids': missing_field_ids},
|
||||
)
|
||||
current = ShippingFulfillmentPolicy.query.filter_by(schema_id=policy.schema_id, status='published').one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if current is not None:
|
||||
@@ -176,7 +240,7 @@ def publish(policy_id: int, *, actor_id: int | None, expected_lock_version: int
|
||||
|
||||
|
||||
def published_policy() -> ShippingFulfillmentPolicy:
|
||||
"""取得当前可执行策略;没有发布版本时 fail closed。"""
|
||||
"""取得唯一 Schema 当前可执行策略;没有发布版本时 fail closed。"""
|
||||
schema = _schema()
|
||||
policy = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id, status='published').one_or_none()
|
||||
if policy is None:
|
||||
|
||||
@@ -4,7 +4,9 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、动态订单字段、tool_common、tool_response。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取。
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取;
|
||||
STP:auto_progress / try_auto_chain_after_match 止于 Excel 待人工上传;
|
||||
无论 AUTO_UPLOAD 开关为何值,自动链均不调用 upload_to_freight。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -154,6 +156,7 @@ def _auto_generate_excel_enabled() -> bool:
|
||||
|
||||
|
||||
def _auto_upload_enabled() -> bool:
|
||||
"""读取货代自动上传开关;STP 自动链已忽略该开关,仅保留配置探测/兼容读取。"""
|
||||
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)
|
||||
|
||||
|
||||
@@ -221,10 +224,10 @@ def try_auto_chain_after_match(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
匹配成功后自动串联 Excel 导出与货代上传(Hxops chat fallback 链)。
|
||||
匹配成功后自动串联 Excel 导出,并停在待人工上传(STP)。
|
||||
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;若自动上传开关开启,
|
||||
继续触发 RPA 上传。失败、超时或缺少 RPA 配置时转人工接管。
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;无论
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,首期硬禁止自动货代 RPA 上传。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
@@ -241,9 +244,11 @@ def try_auto_chain_after_match(
|
||||
|
||||
result = match_result
|
||||
from app.services.shipping_notice.tool_common import merge_tool_payload
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
|
||||
tool_payload = merge_tool_payload(task, payload)
|
||||
|
||||
# [STEP 1] 低风险:匹配成功后自动生成 Excel。
|
||||
if _auto_generate_excel_enabled():
|
||||
db.session.refresh(task)
|
||||
if not task.export_file_path and match_completed(task):
|
||||
@@ -252,15 +257,23 @@ def try_auto_chain_after_match(
|
||||
return gen
|
||||
result = prepend_tool_message(gen, str(result.get("message") or ""))
|
||||
|
||||
if _auto_upload_enabled():
|
||||
db.session.refresh(task)
|
||||
if task.export_file_path and task.process_status != "uploaded":
|
||||
up = upload_to_freight({**tool_payload, "mode": "auto"})
|
||||
if up.get("status") == "failed":
|
||||
return up
|
||||
result = prepend_tool_message(up, str(result.get("message") or ""))
|
||||
if up.get("status") in {"running", "needs_human"}:
|
||||
return {**up, "message": result.get("message", up.get("message", ""))}
|
||||
# [STEP 2] STP 硬停:Excel 就绪后进入 wait_manual_upload;绝不调用 upload_to_freight。
|
||||
# 即便 _auto_upload_enabled() 为 True 也不得突破(首期无货代 RPA 自动上传)。
|
||||
db.session.refresh(task)
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
):
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=str(result.get("message") or "发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。"),
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
@@ -616,16 +629,16 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将已生成的发货 Excel 上传至货代系统,或标记人工上传完成。
|
||||
【AI 触发时机】:Excel 已生成且用户确认上传/重试 RPA 时调用;mode=manual_confirm 用于手工上传收口。
|
||||
登记人工货代上传完成(首期唯一上传收口)。
|
||||
【AI 触发时机】:禁止调用;仅工作台 mark-manual-uploaded 以 mode=manual_confirm 调用。
|
||||
|
||||
核心逻辑:补齐 export → manual_confirm 直接 UPLOADED → auto/retry_upload 走 RPA 触发与超时重试。
|
||||
核心逻辑:首期硬拒绝 auto/retry_upload(不触发货代 RPA);manual_confirm 校验凭据后标记 UPLOADED。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;mode 可选 auto / retry_upload / manual_confirm;manual_confirm 可传 freight_ref_no。
|
||||
payload: 须含 task_id;mode 必须为 manual_confirm;须传 evidence_asset_no。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: status 可为 ok / running / needs_human / failed。
|
||||
dict[str, Any]: status 可为 ok / failed。
|
||||
"""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
@@ -666,14 +679,26 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return gen
|
||||
|
||||
# [STEP 2] 区分人工确认与 RPA 上传两种路径。
|
||||
# 首期 STP:仅允许 manual_confirm(外部货代上传后登记凭据);禁止 auto/retry_upload 触发 RPA。
|
||||
artifact_id = payload.get('artifact_id')
|
||||
try:
|
||||
artifact_id = int(artifact_id) if artifact_id is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task))
|
||||
|
||||
# manual_confirm 需要私有回执;auto/retry_upload 走 Artifact 尝试和回调。
|
||||
mode = str(payload.get("mode") or "auto").strip().lower()
|
||||
if mode != "manual_confirm":
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="首期不支持货代 RPA 自动上传。请下载 Excel,在货代系统人工上传后,于任务处理工作台提交截图/PDF 凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
stop_agent_turn=True,
|
||||
next_required_action="请在任务处理工作台使用「登记人工上传」。",
|
||||
)
|
||||
|
||||
# manual_confirm 需要私有回执;auto/retry_upload 已在上方拒绝。
|
||||
if mode == "manual_confirm":
|
||||
operator_id = payload.get('operator_id')
|
||||
try:
|
||||
@@ -971,9 +996,16 @@ def run_auto_progress_fulfillment_steps(
|
||||
payload: dict[str, Any],
|
||||
steps: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""auto_progress 中匹配→导出→上传编排;有早停响应时返回 dict,否则返回 None。"""
|
||||
"""
|
||||
auto_progress 中匹配→导出编排;有早停响应时返回 dict,否则返回 None。
|
||||
|
||||
核心逻辑:自动匹配与生成 Excel;Phase 0 STP 硬禁止自动货代上传(含 RPA),
|
||||
停在 wait_manual_upload。无论 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,
|
||||
本函数永不调用 upload_to_freight;货代 RPA 上传不在自动链范围内。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
|
||||
# [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。
|
||||
# 这是履约侧串联的起点,失败或需人审时必须立即早停返回。
|
||||
if _auto_match_enabled() and not match_completed(task):
|
||||
matched = match_inventory({"task_id": task.task_no, **(payload or {})})
|
||||
if matched.get("status") != "ok":
|
||||
@@ -981,19 +1013,28 @@ def run_auto_progress_fulfillment_steps(
|
||||
steps.append("库存匹配")
|
||||
|
||||
# [STEP 2] 匹配完成后按配置自动生成 Excel。
|
||||
# 只在尚未生成导出文件时触发,避免重复导出覆盖人工下载链路。
|
||||
if _auto_generate_excel_enabled() and match_completed(task) and not task.export_file_path:
|
||||
gen = generate_excel({"task_id": task.task_no})
|
||||
if gen.get("status") != "ok":
|
||||
return gen
|
||||
steps.append("生成发货 Excel")
|
||||
|
||||
# [STEP 3] 最后根据配置尝试自动上传货代。
|
||||
# 上传会返回 running/needs_human 等早停状态,因此这里直接把结果上抛给 auto_progress。
|
||||
if _auto_upload_enabled() and task.export_file_path and task.process_status != "uploaded":
|
||||
up = upload_to_freight({"task_id": task.task_no, "mode": "auto"})
|
||||
if up.get("status") == "running":
|
||||
steps.append("触发 RPA 上传")
|
||||
return up
|
||||
# [STEP 3] STP 停点:Excel 已生成则进入 wait_manual_upload。
|
||||
# AUTO_UPLOAD 分支已硬禁用,绝不 enqueue 货代 RPA。
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
):
|
||||
steps.append("等待人工上传货代")
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请下载后在货代系统上传,并提交截图/PDF 凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
return None
|
||||
@@ -772,10 +772,14 @@ def run_intake_parse(
|
||||
is_profile_sample = str(locked.purpose or '') == 'order_document_profile_sample'
|
||||
schema_definition: dict[str, Any] = {'fields': []}
|
||||
if not is_profile_sample:
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.order_schema.runtime import published_version
|
||||
|
||||
try:
|
||||
schema_version = published_version()
|
||||
schema_definition = dict(schema_version.definition_json or {})
|
||||
except ConflictError:
|
||||
schema_definition = {'fields': []}
|
||||
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
schema_definition = dict(schema_version.definition_json or {}) if schema_version is not None else {'fields': []}
|
||||
# [STEP 2] shipping_notice 上传阶段只落快览摘要;模板样本用途保留文档/布局持久化。
|
||||
if is_profile_sample:
|
||||
persist_info = persist_intake_documents(
|
||||
@@ -785,6 +789,14 @@ def run_intake_parse(
|
||||
uploaded_storage_keys=uploaded_storage_keys,
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
# 模板样本必须先具备可用布局才可进入向导;同内容文件会在此同步复用已有布局。
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
layout_versions = schedule_document_layouts(
|
||||
ShippingNoticeDocument.query.filter_by(intake_id=locked.id).all(),
|
||||
created_by_id=locked.user_id,
|
||||
)
|
||||
persist_info['layout_version_count'] = len(layout_versions)
|
||||
|
||||
tech_summary = intake_result_to_structured_summary(result)
|
||||
tech_summary['document_count'] = persist_info.get('document_count')
|
||||
|
||||
@@ -16,7 +16,12 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingNoticeDocument, ShippingOrderDocumentProfileEditLease, ShippingOrderDocumentProfileSample
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
@@ -54,12 +59,17 @@ def _initial_definition(main_table_id: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _new_profile_code() -> str:
|
||||
"""生成新模板族的服务端系统编码,避免客户端命名参与解析、版本和审计主键。"""
|
||||
return f"ODP-{datetime.utcnow():%Y%m%d}-{secrets.token_hex(6).upper()}"
|
||||
|
||||
|
||||
def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
以单事务完成创建向导。
|
||||
|
||||
Args:
|
||||
data: 模板身份、已解析样本文档、主表格、Schema 和浏览器会话身份。
|
||||
data: 模板名称、已解析样本文档、主表格、Schema 和浏览器会话身份;系统编码由服务端生成。
|
||||
actor_id: 当前管理员主键。
|
||||
|
||||
Returns:
|
||||
@@ -83,10 +93,16 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
raise ValidationError('Selected main table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
for _attempt in range(3):
|
||||
profile_code = _new_profile_code()
|
||||
if ShippingOrderDocumentProfile.query.filter_by(profile_code=profile_code).first() is None:
|
||||
break
|
||||
else:
|
||||
raise ConflictError('Could not allocate order document profile code', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS')
|
||||
try:
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': data.get('profile_code'),
|
||||
'profile_code': profile_code,
|
||||
'display_name': data.get('display_name'),
|
||||
'schema_version_id': schema_version_id,
|
||||
'definition': _initial_definition(table_id),
|
||||
@@ -104,7 +120,7 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id, event_type='wizard_created', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id},
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id, 'profile_code': profile_code},
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
token = secrets.token_urlsafe(32)
|
||||
|
||||
@@ -1481,17 +1481,22 @@ def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, An
|
||||
raise ValidationError('Coordinate reconstruction could not produce a table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc
|
||||
|
||||
|
||||
def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""仅列出模板工作台专用样本;普通发货历史附件不得混入下拉框。"""
|
||||
def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""仅列出当前管理员可标注的专用样本,并按内容哈希收敛重复上传。"""
|
||||
if actor_id is None:
|
||||
return []
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
rows = ShippingNoticeDocument.query.join(
|
||||
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
|
||||
).filter(
|
||||
ShippingNoticeDocument.document_type.in_({'attachment', 'email_body'}),
|
||||
ShippingNoticeIntake.purpose == 'order_document_profile_sample',
|
||||
ShippingNoticeIntake.user_id == int(actor_id),
|
||||
ShippingNoticeIntake.parse_status == 'parsed',
|
||||
ShippingNoticeDocument.current_layout_version_id.is_not(None),
|
||||
).order_by(ShippingNoticeDocument.created_at.desc()).limit(safe_limit * 4).all()
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_content_hashes: set[str] = set()
|
||||
for document in rows:
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
|
||||
@@ -1499,6 +1504,10 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if layout.get('status') != 'ready' or not tables:
|
||||
continue
|
||||
content_hash = str(document.content_hash or '').strip().lower()
|
||||
# 同一内容只显示最新可用文档,避免同名/同附件重复占据选择器。
|
||||
if content_hash and content_hash in seen_content_hashes:
|
||||
continue
|
||||
intake = db.session.get(ShippingNoticeIntake, document.intake_id)
|
||||
if intake is None:
|
||||
continue
|
||||
@@ -1524,6 +1533,8 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
'can_delete': delete_block_reason is None,
|
||||
'delete_block_reason': delete_block_reason,
|
||||
})
|
||||
if content_hash:
|
||||
seen_content_hashes.add(content_hash)
|
||||
if len(result) >= safe_limit:
|
||||
break
|
||||
return result
|
||||
|
||||
@@ -586,6 +586,30 @@ def persist_order_extraction_result(
|
||||
or candidate.duplicate_resolution == 'open_existing'
|
||||
)
|
||||
):
|
||||
# STP:automatic 候选须再过严格门禁才物化 Task;失败则降为 provisional 待复核。
|
||||
if candidate.candidate_status == 'accepted' and candidate.acceptance_mode == 'automatic':
|
||||
from app.services.shipping_notice.candidate_service import evaluate_candidate_stp_gate
|
||||
passed, stp_reasons = evaluate_candidate_stp_gate(candidate)
|
||||
if not passed:
|
||||
candidate.candidate_status = 'provisional'
|
||||
candidate.acceptance_mode = None
|
||||
candidate.accepted_at = None
|
||||
candidate.acceptance_reason = None
|
||||
candidate.acceptance_policy_version = None
|
||||
candidate.selected = False
|
||||
reasons.extend(stp_reasons)
|
||||
pending_item = {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'order_index': index,
|
||||
'source_intake_no': intake_no,
|
||||
'po_number': candidate.po_number,
|
||||
'reasons': sorted(set(reasons)),
|
||||
'missing_fields': list(candidate.missing_fields_json or []),
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
continue
|
||||
auto_candidates.append(candidate)
|
||||
else:
|
||||
if candidate.candidate_status != 'accepted' and candidate.validation_status == 'ready' and not auto_create_enabled:
|
||||
@@ -957,3 +981,159 @@ def submit_order_extraction_run_result(
|
||||
flag_modified(run, 'auto_freeze_policy_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def submit_order_extraction_unit_result(
|
||||
*,
|
||||
run: Any,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。
|
||||
|
||||
核心逻辑:仅锁定本 Unit 的 Intake/Document,复用 persist_order_extraction_result;
|
||||
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
|
||||
|
||||
Args:
|
||||
run: 所属 ShippingOrderExtractionRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderExtractionUnit。
|
||||
orders: 该 Unit 合并邮件补充后的订单数组。
|
||||
|
||||
Returns:
|
||||
与 submit_order_extraction_run_result 同形的业务摘要(作用域为本 Unit)。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
unit_intake_id = int(unit.intake_id)
|
||||
unit_document_id = int(unit.document_id)
|
||||
scoped_snapshots = []
|
||||
for item in snapshot_intakes:
|
||||
if not isinstance(item, dict) or int(item.get('intake_id') or 0) != unit_intake_id:
|
||||
continue
|
||||
docs = [
|
||||
document for document in (item.get('documents') or [])
|
||||
if isinstance(document, dict) and int(document.get('document_id') or 0) == unit_document_id
|
||||
]
|
||||
scoped = dict(item)
|
||||
scoped['documents'] = docs
|
||||
scoped_snapshots.append(scoped)
|
||||
if not scoped_snapshots:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Unit Intake 不在 Run 快照中')
|
||||
|
||||
frozen_context_by_intake = {
|
||||
int(item['intake_id']): dict(item.get('deterministic_context') or {})
|
||||
for item in scoped_snapshots
|
||||
if str(item.get('intake_id') or '').isdigit()
|
||||
}
|
||||
frozen_layout_candidates_by_document = {
|
||||
int(document['document_id']): list(document.get('layout_schema_candidates') or [])
|
||||
for intake in scoped_snapshots
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
frozen_evidence_text_by_document = {
|
||||
int(document['document_id']): (
|
||||
frozen_document_text_for_parser(document) or str(document.get('extracted_text') or '')
|
||||
)
|
||||
for intake in scoped_snapshots
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
intake = db.session.get(ShippingNoticeIntake, unit_intake_id)
|
||||
document = db.session.get(ShippingNoticeDocument, unit_document_id)
|
||||
if intake is None or document is None or int(document.intake_id) != unit_intake_id:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Unit Intake/Document 不存在')
|
||||
if int(intake.user_id) != int(run.user_id):
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.FORBIDDEN', message='Unit Intake 不属于 Run 用户')
|
||||
|
||||
# 幂等:本 Unit 候选已消费建单则直接回放,避免重复建批。
|
||||
consumed = ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.primary_document_id == unit_document_id,
|
||||
ShippingNoticeCandidate.consumed_task_id.isnot(None),
|
||||
).all()
|
||||
if consumed:
|
||||
task_nos = sorted({
|
||||
str(task.task_no)
|
||||
for task in ShippingTask.query.filter(
|
||||
ShippingTask.id.in_([int(row.consumed_task_id) for row in consumed])
|
||||
).all()
|
||||
})
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [{'task_no': task_no} for task_no in task_nos],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [],
|
||||
'non_shipping_orders': [],
|
||||
'created_count': len(task_nos),
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
'created_with_missing_fields_count': 0,
|
||||
'idempotent_replay': True,
|
||||
'unit_id': int(unit.id),
|
||||
}
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
return result
|
||||
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
intake_nos=[str(intake.intake_no)],
|
||||
lock=True,
|
||||
allow_consumed=False,
|
||||
)
|
||||
current_documents = [row for row in _load_documents(current_intakes, lock=True) if int(row.id) == unit_document_id]
|
||||
if len(current_intakes) != 1 or len(current_documents) != 1:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED', message='Unit 源数据已变化')
|
||||
|
||||
for intake_snapshot in scoped_snapshots:
|
||||
frozen_context = dict(intake_snapshot.get('deterministic_context') or {})
|
||||
if canonical_mail_context(current_intakes[0]) != frozen_context:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的邮件上下文已变化',
|
||||
)
|
||||
for frozen in intake_snapshot.get('documents') or []:
|
||||
if not isinstance(frozen, dict):
|
||||
continue
|
||||
doc = current_documents[0]
|
||||
if (
|
||||
str(doc.content_hash or '') != str(frozen.get('content_hash') or '')
|
||||
or str(doc.extracted_text or '') != str(frozen.get('extracted_text') or '')
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的附件内容已变化',
|
||||
)
|
||||
|
||||
result = persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=current_intakes,
|
||||
documents=current_documents,
|
||||
current_snapshot=str(run.input_snapshot_hash),
|
||||
request_id=f'{run.run_no}:unit:{int(unit.id)}',
|
||||
orders=orders,
|
||||
run_id=int(run.id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='deterministic_order_parser',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
auto_create_enabled=bool(((run.auto_freeze_policy_json or {}).get('enabled', False))),
|
||||
)
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
request_id=str(run.run_no),
|
||||
result=result,
|
||||
)
|
||||
db.session.commit()
|
||||
return result
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_run_service.py
|
||||
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run。
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
|
||||
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run;
|
||||
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -430,8 +432,11 @@ def _build_snapshot(
|
||||
'user_id': user_id,
|
||||
'owner_agent_id': owner_agent_id,
|
||||
'conversation_id': conversation_id,
|
||||
# 冻结族编码 + 版本 + checksum,保证历史 Run 在资产解耦后仍可按契约回放。
|
||||
'schema': {
|
||||
'schema_version_id': schema_version.id,
|
||||
'schema_code': schema_version.schema.schema_code if schema_version.schema else None,
|
||||
'family_code': schema_version.schema.schema_code if schema_version.schema else None,
|
||||
'version': schema_version.version,
|
||||
'checksum': schema_version.checksum,
|
||||
'extraction_contract': dify_contract(schema_version),
|
||||
@@ -1891,6 +1896,48 @@ def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
|
||||
|
||||
def progress_ready_extraction_unit(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 STP 触发下游 auto_progress。
|
||||
|
||||
核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit;建批路径由编排器
|
||||
调用 progress_workflow.auto_progress;若仅打开既有任务则不重复推进。
|
||||
|
||||
Args:
|
||||
run: 所属抽取 Run。
|
||||
unit: 已 candidate_ready 的 Unit。
|
||||
orders: 该 Unit 订单数组。
|
||||
|
||||
Returns:
|
||||
Unit 级落库摘要(含 created / pending_orders)。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_unit_result
|
||||
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders)
|
||||
# 建批编排器会异步调用同一 auto_progress;此处仅为无编排器的已创建任务兜底同步推进。
|
||||
created = list(result.get('created') or [])
|
||||
if created and not result.get('batch_no') and not result.get('idempotent_replay'):
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
for item in created:
|
||||
task_no = str(item.get('task_no') or '').strip()
|
||||
if not task_no:
|
||||
continue
|
||||
try:
|
||||
auto_progress({'task_id': task_no, 'source': 'system'})
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
'STP auto_progress failed after unit persist run=%s unit=%s task=%s',
|
||||
run.run_no, getattr(unit, 'id', None), task_no,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
"""
|
||||
通用 Job 超时回收后同步领域 Run,避免 Job 已 queued/failed 而 Run 永久 running。
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及旧 Workflow 输入兼容函数。
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
|
||||
依赖:MinerU 紧凑快照、订单 Profile、Schema 校验、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决确定性解析或人工复核;旧 Workflow 函数将在阶段 1 移除,不参与新订单主链。
|
||||
逻辑:Worker 先调用本模块裁决确定性解析或人工复核,并输出 route_decision/reason_codes;
|
||||
仅严格门禁通过才可直通建单;旧 Workflow 函数将在阶段 1 移除,不参与新订单主链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,6 +38,10 @@ class DeterministicRouteResult:
|
||||
|
||||
AI 触发时机:无需调用。此对象仅在 HXOPS Worker 判断已批准模板能否确定性解析
|
||||
时创建,禁止包含文档正文、字段值、坐标、Prompt 或 Provider 凭据。
|
||||
|
||||
decision 必含 STP 裁决字段:
|
||||
- route_decision: straight_through | needs_review
|
||||
- reason_codes: 严格门禁原因码列表(与 fallback_reason_codes 对齐并可能增补)
|
||||
"""
|
||||
|
||||
execution_mode: Literal['deterministic', 'review_required', 'skipped']
|
||||
@@ -44,6 +49,60 @@ class DeterministicRouteResult:
|
||||
decision: dict[str, Any]
|
||||
|
||||
|
||||
def _apply_stp_route_adjudication(
|
||||
decision: dict[str, Any],
|
||||
*,
|
||||
execution_mode: Literal['deterministic', 'review_required', 'skipped'],
|
||||
orders: list[dict[str, Any]],
|
||||
) -> DeterministicRouteResult:
|
||||
"""
|
||||
在路由结果上写入明确的 STP 裁决:straight_through | needs_review。
|
||||
|
||||
核心逻辑:严格门禁——缺字段、低置信、缺证据、未批准自动建单、无自动接受标记、
|
||||
或非 deterministic 执行态 → needs_review;仅干净直通可 straight_through。
|
||||
重复冲突在 Candidate 落库阶段再拦,不在本函数臆造。
|
||||
|
||||
Args:
|
||||
decision: 路由决策字典(就地写入 route_decision / reason_codes)。
|
||||
execution_mode: deterministic | review_required | skipped。
|
||||
orders: 本轮产出订单(用于检查 _hxops_acceptance)。
|
||||
|
||||
Returns:
|
||||
带 STP 字段的 DeterministicRouteResult。
|
||||
"""
|
||||
reason_codes = [str(code) for code in (decision.get('fallback_reason_codes') or []) if str(code).strip()]
|
||||
has_acceptance = any(
|
||||
isinstance(order, dict) and order.get('_hxops_acceptance') == 'approved_deterministic_profile_v1'
|
||||
for order in orders
|
||||
)
|
||||
|
||||
# [STEP 1] 非确定性执行一律人工复核。
|
||||
if execution_mode != 'deterministic':
|
||||
if not reason_codes:
|
||||
reason_codes.append('review_required' if execution_mode == 'review_required' else 'skipped')
|
||||
decision['fallback_reason_codes'] = reason_codes
|
||||
decision['reason_codes'] = list(reason_codes)
|
||||
decision['route_decision'] = 'needs_review'
|
||||
return DeterministicRouteResult(execution_mode=execution_mode, orders=orders, decision=decision)
|
||||
|
||||
# [STEP 2] 严格门禁:模板未批准 / 已有原因码 / 无自动接受标记 → needs_review。
|
||||
if not bool(decision.get('auto_create_approved')) and 'profile_auto_create_not_approved' not in reason_codes:
|
||||
reason_codes.append('profile_auto_create_not_approved')
|
||||
if not has_acceptance and not reason_codes:
|
||||
reason_codes.append('acceptance_marker_missing')
|
||||
if reason_codes or not has_acceptance or not bool(decision.get('auto_create_approved')):
|
||||
decision['fallback_reason_codes'] = reason_codes
|
||||
decision['reason_codes'] = list(reason_codes)
|
||||
decision['route_decision'] = 'needs_review'
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
|
||||
# [STEP 3] 全部严格门禁通过 → 直通。
|
||||
decision['fallback_reason_codes'] = []
|
||||
decision['reason_codes'] = []
|
||||
decision['route_decision'] = 'straight_through'
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
|
||||
|
||||
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""从 Run 快照定位单元,并在必要时补读当前 ready layout。"""
|
||||
return resolve_unit_runtime_snapshot(run, unit)
|
||||
@@ -899,10 +958,11 @@ def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[d
|
||||
|
||||
|
||||
def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult:
|
||||
"""计算单元的模板路由并返回仅含脱敏诊断的结构化结果。
|
||||
"""计算单元的模板路由并返回含 STP 裁决的脱敏结构化结果。
|
||||
|
||||
AI 触发时机:无需调用。Worker 在每个 Unit 执行前调用;只有唯一、已批准、
|
||||
完整且符合冻结 Schema 的模板解析可走 deterministic,其余均明确进入人工复核。
|
||||
完整且符合冻结 Schema 的模板解析可走 deterministic + straight_through,
|
||||
其余均明确 needs_review(decision.route_decision / reason_codes)。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -936,14 +996,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if profile_result.get('blocking'):
|
||||
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else []
|
||||
decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues]
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也必须人工复核。
|
||||
if not tables:
|
||||
decision['fallback_reason_codes'] = ['business_table_not_found']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
if len(tables) != 1:
|
||||
decision['fallback_reason_codes'] = ['multiple_business_tables']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
selected = tables[0]
|
||||
decision.update({
|
||||
'selected_profile_code': selected.get('profile_code'),
|
||||
@@ -969,13 +1029,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if orders is not None:
|
||||
decision['fallback_reason_codes'] = [reason_code]
|
||||
decision['parsed_table_count'] = 1
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
# 不完整字段仍可产出草稿订单,但 STP 严格门禁必须 needs_review。
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
reason_code = review_reason or reason_code
|
||||
if orders is None:
|
||||
if reason_code == 'row_needs_review':
|
||||
decision['review_details'] = _profile_row_review_details(selected)
|
||||
decision['fallback_reason_codes'] = [reason_code or 'business_table_not_found']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['business_table_count'] = 1
|
||||
decision['matched_table_count'] = 1
|
||||
@@ -986,7 +1047,7 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
if isinstance(order, dict):
|
||||
order.pop('_hxops_acceptance', None)
|
||||
decision['fallback_reason_codes'] = ['profile_auto_create_not_approved']
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
|
||||
|
||||
def _profile_row_review_details(table: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/shipping_notice/order_extraction_workspace_projection.py
|
||||
|
||||
用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。
|
||||
依赖:ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、冻结 snapshot 和 Unit 结果 JSON。
|
||||
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要和可操作按钮都在这里统一裁剪与组装。
|
||||
依赖:ShippingNoticeCandidate、ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、
|
||||
冻结 snapshot 和 Unit 结果 JSON。
|
||||
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要、重复订单 open_existing 入口
|
||||
与可操作按钮都在这里统一裁剪与组装。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +14,7 @@ from collections import Counter
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
@@ -213,26 +216,66 @@ def _current_activity_reason_codes(event: ShippingOrderExtractionProgressEvent |
|
||||
return sorted(code for code in codes if code)
|
||||
|
||||
|
||||
def _run_available_actions(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> list[str]:
|
||||
"""根据 Run 与 Unit 事实返回用户可见操作,前端不得自行推断。"""
|
||||
def _open_existing_document_ids(run: ShippingOrderExtractionRun) -> set[int]:
|
||||
"""返回本轮已判定 open_existing 且带目标任务号的 PDF document_id 集合。"""
|
||||
return {
|
||||
int(document_id)
|
||||
for document_id, duplicate in _duplicate_projection_by_document(run).items()
|
||||
if (
|
||||
str(duplicate.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(duplicate.get('existing_task_no') or '').strip()
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _run_available_actions(
|
||||
run: ShippingOrderExtractionRun,
|
||||
units: list[ShippingOrderExtractionUnit],
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> list[str]:
|
||||
"""根据 Run 与 Unit 事实返回用户可见操作;纯 open_existing 不暴露人工复核入口。"""
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
|
||||
actions = ['view_details']
|
||||
if run.status in {'review_required', 'partially_completed'} or any(unit.status == 'review_required' for unit in units):
|
||||
needs_manual_review = any(
|
||||
str(unit.status or '') == 'review_required'
|
||||
and int(unit.document_id) not in open_ids
|
||||
for unit in units
|
||||
)
|
||||
# 无 Unit 时保留历史行为:Run 状态为复核态则仍可进复核。
|
||||
if not units and run.status in {'review_required', 'partially_completed'}:
|
||||
needs_manual_review = True
|
||||
if needs_manual_review:
|
||||
actions.append('enter_manual_review')
|
||||
if run.status == 'failed' or any(unit.status == 'failed' for unit in units):
|
||||
actions.append('retry_failed_attachments')
|
||||
return actions
|
||||
|
||||
|
||||
def _unresolved_review_document_count(run: ShippingOrderExtractionRun) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case,候选已生成但未确认也必须计入。"""
|
||||
def _unresolved_review_document_count(
|
||||
run: ShippingOrderExtractionRun,
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case;open_existing 已关联任务的 PDF 不计复核。"""
|
||||
resolved_statuses = {'confirmed', 'non_order', 'superseded'}
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else set()
|
||||
return len({
|
||||
int(case.document_id)
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if str(case.status or '') not in resolved_statuses
|
||||
if (
|
||||
str(case.status or '') not in resolved_statuses
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
def _result_opened_existing_count(run: ShippingOrderExtractionRun) -> int:
|
||||
"""从 Run.result_json 读取已打开已有任务数。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
return max(0, int(result.get('opened_existing_count') or 0))
|
||||
|
||||
|
||||
def _planned_document_count(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> int:
|
||||
"""布局等待期尚无 Unit 时,使用冻结选择计划展示用户已选附件数量。"""
|
||||
if units:
|
||||
@@ -242,8 +285,58 @@ def _planned_document_count(run: ShippingOrderExtractionRun, units: list[Shippin
|
||||
return max(0, int(selection.get('selected_attachment_count') or 0))
|
||||
|
||||
|
||||
def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
"""按单元状态返回详情项可见操作。"""
|
||||
def _duplicate_projection_by_document(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
按 PDF 汇总本轮 Candidate 的重复订单决策,供右侧处理面分流 open_existing。
|
||||
|
||||
核心逻辑:同一 Document 可能有多 Candidate;优先取带目标任务号的 open_existing。
|
||||
"""
|
||||
if getattr(run, 'id', None) is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
)
|
||||
by_doc: dict[int, dict[str, Any]] = {}
|
||||
for candidate in rows:
|
||||
document_id = int(candidate.primary_document_id or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
resolution = str(candidate.duplicate_resolution or '').strip() or None
|
||||
task_no = str(candidate.duplicate_target_task_no or '').strip().upper() or None
|
||||
status = str(candidate.duplicate_status or '').strip() or None
|
||||
payload = {
|
||||
'duplicate_resolution': resolution,
|
||||
'existing_task_no': task_no,
|
||||
'duplicate_status': status,
|
||||
}
|
||||
current = by_doc.get(document_id)
|
||||
# [STEP] 有明确 open_existing + 任务号时覆盖弱结果,保证前端能跳转已有任务。
|
||||
if resolution == 'open_existing' and task_no:
|
||||
by_doc[document_id] = payload
|
||||
elif current is None:
|
||||
by_doc[document_id] = payload
|
||||
return by_doc
|
||||
|
||||
|
||||
def _document_available_actions(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
duplicate: dict[str, Any] | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
按单元状态与重复决策返回详情项可见操作。
|
||||
|
||||
核心逻辑:open_existing 且已有任务号时优先暴露 open_existing,不再映射为人工复核入口。
|
||||
"""
|
||||
dup = duplicate if isinstance(duplicate, dict) else {}
|
||||
if (
|
||||
str(dup.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(dup.get('existing_task_no') or '').strip()
|
||||
):
|
||||
return ['open_existing', 'view_evidence']
|
||||
if unit.status == 'candidate_ready':
|
||||
return ['view_evidence', 'review_candidate']
|
||||
if unit.status == 'review_required':
|
||||
@@ -251,6 +344,34 @@ def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
return []
|
||||
|
||||
|
||||
def _document_reason_code(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
duplicate: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
选择面向用户的原因码;重复打开已有任务时优先暴露 duplicate_status。
|
||||
|
||||
Args:
|
||||
unit: 抽取单元。
|
||||
duplicate: 文档级重复投影。
|
||||
|
||||
Returns:
|
||||
原因码字符串,无则 None。
|
||||
"""
|
||||
dup = duplicate if isinstance(duplicate, dict) else {}
|
||||
if (
|
||||
str(dup.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(dup.get('existing_task_no') or '').strip()
|
||||
):
|
||||
return (
|
||||
str(unit.reason_code or '').strip()
|
||||
or str(dup.get('duplicate_status') or '').strip()
|
||||
or 'duplicate_open_existing'
|
||||
)
|
||||
return unit.reason_code or ('technical_failure' if unit.status == 'failed' else None)
|
||||
|
||||
|
||||
def _planned_layout_documents(
|
||||
run: ShippingOrderExtractionRun,
|
||||
documents: dict[int, dict[str, Any]],
|
||||
@@ -288,6 +409,9 @@ def _planned_layout_documents(
|
||||
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
|
||||
'reason_code': None,
|
||||
'review_details': [],
|
||||
'duplicate_resolution': None,
|
||||
'existing_task_no': None,
|
||||
'duplicate_status': None,
|
||||
'available_actions': [],
|
||||
'activity_event_code': 'layout_parsing_completed' if completed else 'layout_parsing_started' if started else None,
|
||||
'started_at': (started.occurred_at or started.received_at or started.created_at).isoformat() + 'Z' if started else None,
|
||||
@@ -364,7 +488,8 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
"""
|
||||
构建工作台按 PDF 展示的详情列表。
|
||||
|
||||
AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败”时使用。
|
||||
AI 触发时机:当工作台详情抽屉或聊天卡需要回答“哪份 PDF 成功、用了什么模板、为什么失败、
|
||||
是否应打开已有任务”时使用。
|
||||
"""
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
documents = _snapshot_documents(run)
|
||||
@@ -374,10 +499,12 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
profiles_by_key = _snapshot_profiles(run)
|
||||
field_codes = _schema_field_codes(run)
|
||||
route_by_unit = _latest_route_decisions(run)
|
||||
duplicates_by_doc = _duplicate_projection_by_document(run)
|
||||
items: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
orders = _orders_from_unit(unit)
|
||||
document = documents.get(int(unit.document_id), {})
|
||||
duplicate = duplicates_by_doc.get(int(unit.document_id), {})
|
||||
items.append({
|
||||
'unit_id': int(unit.id),
|
||||
'document_id': int(unit.document_id),
|
||||
@@ -392,9 +519,12 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
'line_count': _line_count(orders),
|
||||
'profile': _profile_projection(unit, route_by_unit=route_by_unit, profiles_by_key=profiles_by_key),
|
||||
'email_supplement': _email_supplement_projection(unit, event_map, field_codes=field_codes),
|
||||
'reason_code': unit.reason_code or ('technical_failure' if unit.status == 'failed' else None),
|
||||
'reason_code': _document_reason_code(unit, duplicate=duplicate),
|
||||
'review_details': list((unit.result_json or {}).get('review_details') or []),
|
||||
'available_actions': _document_available_actions(unit),
|
||||
'duplicate_resolution': duplicate.get('duplicate_resolution'),
|
||||
'existing_task_no': duplicate.get('existing_task_no'),
|
||||
'duplicate_status': duplicate.get('duplicate_status'),
|
||||
'available_actions': _document_available_actions(unit, duplicate=duplicate),
|
||||
'activity_event_code': None,
|
||||
'started_at': getattr(unit, 'started_at', None).isoformat() + 'Z' if getattr(unit, 'started_at', None) else None,
|
||||
'last_activity_at': getattr(unit, 'last_activity_at', None).isoformat() + 'Z' if getattr(unit, 'last_activity_at', None) else None,
|
||||
@@ -413,6 +543,7 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
documents = _snapshot_documents(run)
|
||||
_, current_event = _latest_progress_events(run)
|
||||
status_counter = Counter(str(unit.status or '') for unit in units)
|
||||
open_existing_doc_ids = _open_existing_document_ids(run)
|
||||
current_activity = None
|
||||
if run.status in {'queued', 'processing'}:
|
||||
if str(run.phase or '') == 'waiting_layout':
|
||||
@@ -444,10 +575,19 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'selection_batch': int(pending_unit.selection_batch or 0) or None,
|
||||
'reason_codes': [],
|
||||
}
|
||||
review_document_count = max(
|
||||
status_counter.get('review_required', 0),
|
||||
_unresolved_review_document_count(run),
|
||||
review_units = sum(
|
||||
1
|
||||
for unit in units
|
||||
if str(unit.status or '') == 'review_required' and int(unit.document_id) not in open_existing_doc_ids
|
||||
)
|
||||
open_existing_units = sum(
|
||||
1 for unit in units if int(unit.document_id) in open_existing_doc_ids
|
||||
)
|
||||
review_document_count = max(
|
||||
review_units,
|
||||
_unresolved_review_document_count(run, open_existing_doc_ids=open_existing_doc_ids),
|
||||
)
|
||||
opened_existing_count = max(open_existing_units, _result_opened_existing_count(run))
|
||||
return {
|
||||
'summary': {
|
||||
'total_documents': _planned_document_count(run, units),
|
||||
@@ -457,9 +597,10 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'review_required_documents': review_document_count,
|
||||
'failed_documents': status_counter.get('failed', 0),
|
||||
'candidate_count': sum(_candidate_count(unit) for unit in units),
|
||||
'opened_existing_documents': opened_existing_count,
|
||||
},
|
||||
'current_activity': current_activity,
|
||||
'available_actions': _run_available_actions(run, units),
|
||||
'available_actions': _run_available_actions(run, units, open_existing_doc_ids=open_existing_doc_ids),
|
||||
}
|
||||
|
||||
|
||||
@@ -483,6 +624,7 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
|
||||
'reviewRequiredDocuments': int(summary.get('review_required_documents') or 0),
|
||||
'failedDocuments': int(summary.get('failed_documents') or 0),
|
||||
'candidateCount': int(summary.get('candidate_count') or 0),
|
||||
'openedExistingCount': int(summary.get('opened_existing_documents') or 0),
|
||||
},
|
||||
'currentActivity': (
|
||||
{
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
services/shipping_notice/order_freeze_service.py
|
||||
|
||||
用途:将已复核的动态订单解析冻结为强类型履约快照。
|
||||
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask 与统一 AppError。
|
||||
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot,库存、导出和上传的后续阶段只读取该快照。
|
||||
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask、
|
||||
standard_field_registry(投影列)、统一 AppError。
|
||||
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot;
|
||||
冻结摘要含 family_code + schema_version/checksum;库存、导出和上传后续阶段只读取该快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,13 +29,10 @@ from app.models import (
|
||||
ShippingTask,
|
||||
ShippingNoticeDocument,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
|
||||
# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。
|
||||
# 注意:本常量须保持在 fulfillment_policy / standard_field_registry 导入之前定义,
|
||||
# 供 standard_field_registry 引用,避免三方循环导入。
|
||||
HEADER_FIELD_PROJECTIONS = {
|
||||
'customer_po_number': 'customer_po_number', 'customer_code': 'customer_code', 'customer_name': 'customer_name',
|
||||
'bill_to_customer': 'bill_to_customer', 'bill_to_address': 'bill_to_address',
|
||||
@@ -201,8 +200,21 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic
|
||||
for item in ShippingOrderReviewEvent.query.filter_by(extraction_id=extraction.id, snapshot_id=None).all()
|
||||
]
|
||||
return {
|
||||
'family_code': getattr(extraction.schema_version.schema, 'schema_code', None),
|
||||
'schema_version_id': extraction.schema_version_id,
|
||||
'schema_version': extraction.schema_version.version,
|
||||
'schema_checksum': extraction.schema_version.checksum,
|
||||
'frozen_field_definitions': [
|
||||
{
|
||||
'field_id': item.get('field_id'),
|
||||
'field_code': item.get('field_code'),
|
||||
'scope': item.get('scope'),
|
||||
'value_type': item.get('value_type'),
|
||||
'enabled': item.get('enabled', True),
|
||||
}
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
],
|
||||
'fulfillment_policy': {'id': policy.id, 'version': policy.version, 'checksum': policy.checksum},
|
||||
'fields': fields,
|
||||
'manual_reviews': reviews,
|
||||
@@ -239,6 +251,12 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
|
||||
|
||||
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str, dict[str, Any]]]:
|
||||
"""按已发布货代策略验证冻结契约,Schema 只继续承担字段目录职责。"""
|
||||
# 懒加载:避免 standard_field_registry ↔ order_freeze ↔ fulfillment_policy 循环导入。
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
required_field_configs,
|
||||
)
|
||||
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
policy = published_policy()
|
||||
required = required_field_configs(definition, policy)
|
||||
@@ -249,7 +267,6 @@ def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str,
|
||||
}
|
||||
return policy, all_configs | required
|
||||
|
||||
|
||||
def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None:
|
||||
"""关键字段若由未经证据确认的 LLM fallback 参与裁决,则强制人工复核。"""
|
||||
decisions = {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task 与重复检测门禁。
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、progress_workflow.auto_progress。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
|
||||
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用。
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用;
|
||||
API commit 后触发 progress_workflow.auto_progress(禁止平行推进链)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -301,4 +302,29 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
))
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
return {'task_no': task.task_no, 'idempotent_replay': False, 'case': serialize_review_case(case)}
|
||||
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'idempotent_replay': False,
|
||||
'case': serialize_review_case(case),
|
||||
'trigger_auto_progress': True,
|
||||
}
|
||||
|
||||
|
||||
def trigger_auto_progress_after_review_confirm(*, task_no: str | None, idempotent_replay: bool = False) -> dict[str, Any] | None:
|
||||
"""
|
||||
人工复核确认建单并提交事务后,复用与 STP 直通相同的 auto_progress 入口。
|
||||
|
||||
核心逻辑:幂等回放不重复推进;系统 source,禁止平行链路。
|
||||
|
||||
Args:
|
||||
task_no: 新建或回放任务号。
|
||||
idempotent_replay: 是否幂等回放。
|
||||
|
||||
Returns:
|
||||
auto_progress 响应;无任务或回放时返回 None。
|
||||
"""
|
||||
if idempotent_replay or not task_no:
|
||||
return None
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
return auto_progress({'task_id': str(task_no).strip(), 'source': 'system'})
|
||||
@@ -119,3 +119,69 @@ def get_user_review_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCa
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
return case
|
||||
|
||||
|
||||
def get_review_run_visible_to_user(
|
||||
run_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingOrderExtractionRun:
|
||||
"""
|
||||
按 run_no 查找当前用户可见的复核 Run(创建者或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部 Run;普通用户仅可读自己创建且 user_id 非空的 Run。
|
||||
写操作仍须经 get_user_review_run 门禁。
|
||||
|
||||
Args:
|
||||
run_no: 抽取 Run 编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见 Run。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Run 不存在或当前用户无权只读访问。
|
||||
"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
|
||||
if is_admin:
|
||||
return run
|
||||
if run.user_id is None or int(run.user_id) != int(user_id):
|
||||
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
|
||||
return run
|
||||
|
||||
|
||||
def get_review_case_visible_to_user(
|
||||
case_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingOrderReviewCase:
|
||||
"""
|
||||
按 case_no 查找当前用户可见的复核 Case(owner 或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部 Case;普通用户仅可读 owner_user_id 匹配且非空的 Case。
|
||||
写操作仍须经 get_user_review_case 门禁。
|
||||
|
||||
Args:
|
||||
case_no: 复核 Case 编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见 Case。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 不存在或当前用户无权只读访问。
|
||||
"""
|
||||
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
if is_admin:
|
||||
return case
|
||||
if case.owner_user_id is None or int(case.owner_user_id) != int(user_id):
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
return case
|
||||
@@ -86,7 +86,8 @@ def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | N
|
||||
before: 作为基线的完整版本 definition。
|
||||
after: 用来比较的完整版本 definition。
|
||||
Returns:
|
||||
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构。
|
||||
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构;
|
||||
另含顶层 auto_creation_policy 变更摘要。
|
||||
"""
|
||||
before_fields = _field_map(before)
|
||||
after_fields = _field_map(after)
|
||||
@@ -113,4 +114,20 @@ def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | N
|
||||
'after': current,
|
||||
'changes': changes,
|
||||
})
|
||||
return {'summary': counts, 'fields': fields}
|
||||
before_policy = (before or {}).get('auto_creation_policy') if isinstance(before, dict) else None
|
||||
after_policy = (after or {}).get('auto_creation_policy') if isinstance(after, dict) else None
|
||||
before_enabled = bool((before_policy or {}).get('enabled')) if isinstance(before_policy, dict) else False
|
||||
after_enabled = bool((after_policy or {}).get('enabled')) if isinstance(after_policy, dict) else False
|
||||
auto_creation = None
|
||||
if before_enabled != after_enabled or (before_policy or {}) != (after_policy or {}):
|
||||
auto_creation = {
|
||||
'key': 'auto_creation_policy.enabled',
|
||||
'kind': 'value',
|
||||
'before': before_enabled,
|
||||
'after': after_enabled,
|
||||
}
|
||||
return {
|
||||
'summary': counts,
|
||||
'fields': fields,
|
||||
'auto_creation_policy': auto_creation,
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
|
||||
依赖:订单 Schema 动态模型、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影。
|
||||
依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影;
|
||||
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.notice_line_table import inspect_notice_table_text
|
||||
@@ -37,13 +39,41 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
|
||||
def published_version() -> ShippingOrderSchemaVersion:
|
||||
"""读取当前唯一 published 订单 Schema;未发布时阻断解析。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
"""
|
||||
读取唯一发货订单 Schema 的 published 版本。
|
||||
|
||||
核心逻辑:按 STANDARD_SHIPPING_NOTICE 联表查询;未命中时兼容历史 SHIPPING_ORDER 夹具。
|
||||
"""
|
||||
version = (
|
||||
ShippingOrderSchemaVersion.query
|
||||
.join(ShippingOrderSchema, ShippingOrderSchemaVersion.schema_id == ShippingOrderSchema.id)
|
||||
.filter(
|
||||
ShippingOrderSchema.schema_code == DEFAULT_SCHEMA_FAMILY_CODE,
|
||||
ShippingOrderSchemaVersion.status == 'published',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
|
||||
# 兼容历史族编码夹具,避免未迁移测试环境全断。
|
||||
version = (
|
||||
ShippingOrderSchemaVersion.query
|
||||
.join(ShippingOrderSchema, ShippingOrderSchemaVersion.schema_id == ShippingOrderSchema.id)
|
||||
.filter(
|
||||
ShippingOrderSchema.schema_code == 'SHIPPING_ORDER',
|
||||
ShippingOrderSchemaVersion.status == 'published',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError(
|
||||
'No published shipping order schema',
|
||||
code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED',
|
||||
details={'schema_code': DEFAULT_SCHEMA_FAMILY_CODE},
|
||||
)
|
||||
return version
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,8 +2,11 @@
|
||||
services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
|
||||
state_machine(CheckpointKind)、tool_response。
|
||||
逻辑:由 task_workflow / 复核确认 / Unit 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
|
||||
STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内;
|
||||
系统触发时事件 actor_id=None 且 detail.source=system。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,8 +31,8 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
|
||||
@@ -38,10 +41,13 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
按任务当前状态自动串联解析确认、正式库存准备与履约动作。
|
||||
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
|
||||
亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。
|
||||
|
||||
核心逻辑:先检查解析是否需要人工确认,再保证正式库存已按 published Profile 就绪,最后委托 fulfillment workflow 继续推进。
|
||||
核心逻辑:先按 checkpoint_kind 早停(must_human / wait_manual_upload / complete);
|
||||
再检查解析门禁与客户/库存源,保证正式库存就绪后委托 fulfillment(止于待人工上传,不触发 RPA 上传)。
|
||||
Args:
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language、auto-chain 控制参数,
|
||||
以及 source(system|workspace_api|tool_api|review_confirmation 等)。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Tool 标准响应,返回自动推进后的阶段、提示和数据。
|
||||
@@ -53,10 +59,55 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
source = str(payload.get("source") or "system").strip() or "system"
|
||||
# 系统入口不写用户 actor;人工 workspace/tool 可传 operator_id。
|
||||
actor_raw = payload.get("operator_id") or payload.get("actor_id")
|
||||
try:
|
||||
actor_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and source != "system" else None
|
||||
except (TypeError, ValueError):
|
||||
actor_id = None
|
||||
log_task_event(
|
||||
task,
|
||||
"auto_progress_started",
|
||||
{"source": source, "process_status": task.process_status, "current_step": task.current_step},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
|
||||
steps: list[str] = []
|
||||
|
||||
# [STEP 0] STP 检查点早停:必须人工或待人工上传时不产生新副作用。
|
||||
ui_early = resolve_task_ui_state(task)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="当前任务需要人工处理,已暂停自动推进。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.COMPLETE:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="任务已结束,无需自动推进。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 1] 先判断解析结果是否允许进入自动链路。
|
||||
# 解析待确认或低置信度时必须立即停下,避免 Agent 在错误数据上继续做库存/出货操作。
|
||||
# 解析待确认或低置信度时必须立即停下,避免在错误数据上继续做库存/出货操作。
|
||||
threshold = current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD")
|
||||
try:
|
||||
threshold = float(threshold) if threshold is not None else 0.7
|
||||
@@ -128,8 +179,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 2] 保证库存已经就绪。
|
||||
# 正常任务仅复用排程或手动刷新已导出的文件;这里不得隐式触发 RPA。
|
||||
# [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。
|
||||
if not task.inventory_lines_json:
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
@@ -137,15 +187,14 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inv_payload["lang"] = lang
|
||||
inv = ensure_inventory(inv_payload)
|
||||
if inv.get("status") == "running":
|
||||
steps.append("触发 RPA 库存导出")
|
||||
steps.append("等待库存准备")
|
||||
return inv
|
||||
if inv.get("status") != "ok":
|
||||
return inv
|
||||
else:
|
||||
steps.append("载入库存")
|
||||
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进。
|
||||
# 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进(止于待人工上传)。
|
||||
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
|
||||
if fulfillment_result is not None:
|
||||
return fulfillment_result
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、动态订单字段编辑器。
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、
|
||||
ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
|
||||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event;
|
||||
list_my_todos / count_my_todos 合并建单前 Review Case 与 Task 待办(管理员可读全局,仅创建者 can_handle);
|
||||
客户关键字 SQL 同时过滤 Review Case(文件名/Case 号/PO)与 Task(客户快照/来源文件名);
|
||||
待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT,
|
||||
仅水合当前页(禁止 500 截断冒充总数);
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
|
||||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||||
"""
|
||||
@@ -17,7 +22,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc
|
||||
from sqlalchemy import asc, case, desc, exists, func, literal, select, union_all
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
@@ -27,10 +32,41 @@ from app.models import (
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_RSV_REQ,
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RESULT_UNKNOWN,
|
||||
PH_UPLOAD_RPA_FAILED,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_REJECTED,
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
resolve_task_ui_state,
|
||||
resolve_task_ui_state_from_fields,
|
||||
)
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values_or_empty,
|
||||
current_line_field_values_or_empty,
|
||||
@@ -42,6 +78,38 @@ EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.
|
||||
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
|
||||
_BUSINESS_NO_RE = re.compile(r"(?<![A-Z0-9])[A-Z]{2,6}\d{8}(?![A-Z0-9])", re.IGNORECASE)
|
||||
|
||||
# 人工复核工作台入口检查点 → todo_category=review;其余 must_human → exception
|
||||
_REVIEW_TODO_CHECKPOINTS = frozenset({
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
})
|
||||
|
||||
_PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload"})
|
||||
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||||
"pending": _PENDING_TODO_CATEGORIES,
|
||||
"processing": frozenset({"in_progress"}),
|
||||
"done": frozenset({"done"}),
|
||||
}
|
||||
|
||||
# 建单前人工复核 Case 仍开放写操作的状态(未确认建单)。
|
||||
_OPEN_REVIEW_CASE_STATUSES = frozenset({
|
||||
"unreviewed",
|
||||
"draft",
|
||||
"ready",
|
||||
"quality_issue",
|
||||
"reparse_pending",
|
||||
})
|
||||
|
||||
|
||||
_REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||||
"unreviewed": "订单 PDF 待人工复核确认",
|
||||
"draft": "复核草稿待继续编辑",
|
||||
"ready": "复核草稿已就绪,可确认建单",
|
||||
"quality_issue": "复核标记为质量问题,待处置",
|
||||
"reparse_pending": "复核要求重识别,处理中",
|
||||
}
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||||
@@ -273,8 +341,8 @@ def list_sorted_batch_tasks(batch: ShippingBatch) -> list[ShippingTask]:
|
||||
|
||||
|
||||
def list_batch_task_summaries(batch: ShippingBatch) -> list[dict[str, Any]]:
|
||||
"""返回批次下已排序任务的摘要投影列表。"""
|
||||
return [serialize_task(item, TaskProjection.SUMMARY) for item in list_sorted_batch_tasks(batch)]
|
||||
"""返回批次下已排序任务的摘要投影列表(含任务中心 enrich 字段)。"""
|
||||
return [serialize_task_summary(item) for item in list_sorted_batch_tasks(batch)]
|
||||
|
||||
|
||||
def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
|
||||
@@ -750,14 +818,223 @@ def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||
return serialize_task(task, TaskProjection.SUMMARY)
|
||||
def task_todo_category(task: ShippingTask) -> str:
|
||||
"""
|
||||
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
|
||||
|
||||
核心逻辑:complete→done;wait_manual_upload→manual_upload;
|
||||
must_human 且属复核入口→review,其余 must_human→exception;auto_continue→in_progress。
|
||||
|
||||
Returns:
|
||||
review | exception | manual_upload | in_progress | done
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind)
|
||||
|
||||
|
||||
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务详情用的 DETAIL 投影(含 lines、events 等)。"""
|
||||
return serialize_task(task, TaskProjection.DETAIL)
|
||||
def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""将 checkpoint_kind(及复核入口集合)映射为 todo_category。"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "done"
|
||||
if kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return "manual_upload"
|
||||
if kind == CheckpointKind.MUST_HUMAN:
|
||||
if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS:
|
||||
return "review"
|
||||
return "exception"
|
||||
return "in_progress"
|
||||
|
||||
|
||||
def _todo_category_from_task_row(
|
||||
row: Any,
|
||||
*,
|
||||
extractions_with_lines: set[int],
|
||||
) -> str:
|
||||
"""
|
||||
用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。
|
||||
|
||||
核心逻辑:委托 resolve_task_ui_state_from_fields;has_dynamic_order_lines 查批量集合。
|
||||
"""
|
||||
extraction_id = getattr(row, "current_order_extraction_id", None)
|
||||
has_lines = (
|
||||
extraction_id is not None
|
||||
and int(extraction_id) in extractions_with_lines
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
process_status=getattr(row, "process_status", None),
|
||||
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),
|
||||
match_status=getattr(row, "match_status", None),
|
||||
export_file_path=getattr(row, "export_file_path", None),
|
||||
has_dynamic_order_lines=has_lines,
|
||||
upload_req_options=[],
|
||||
)
|
||||
return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind)
|
||||
|
||||
|
||||
def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]:
|
||||
"""
|
||||
批量返回「已接受且至少有一行」的 extraction_id 集合。
|
||||
|
||||
核心逻辑:两次 IN 查询替代逐任务 get Extraction + first Line。
|
||||
"""
|
||||
if not extraction_ids:
|
||||
return set()
|
||||
accepted_ids = {
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingOrderExtraction.id).filter(
|
||||
ShippingOrderExtraction.id.in_(tuple(extraction_ids)),
|
||||
ShippingOrderExtraction.status == "accepted",
|
||||
).all()
|
||||
}
|
||||
if not accepted_ids:
|
||||
return set()
|
||||
return {
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingOrderLine.extraction_id).filter(
|
||||
ShippingOrderLine.extraction_id.in_(tuple(accepted_ids)),
|
||||
).distinct().all()
|
||||
}
|
||||
|
||||
|
||||
def task_can_handle(task: ShippingTask, user_id: int, *, is_admin: bool = False) -> bool:
|
||||
"""
|
||||
判断当前用户是否可对该任务执行写操作。
|
||||
|
||||
核心逻辑:仅创建者可处理(task.user_id == user_id 且非空);
|
||||
user_id IS NULL 一律不可写;管理员代操作首期不开放(他人任务 can_handle=False,
|
||||
若管理员本人是创建者仍可处理)。is_admin 保留供调用方显式传参,不单独绕过归属。
|
||||
|
||||
Args:
|
||||
task: 目标任务。
|
||||
user_id: 当前操作者用户 ID。
|
||||
is_admin: 是否管理员视图;不改变归属判定。
|
||||
|
||||
Returns:
|
||||
是否允许写操作。
|
||||
"""
|
||||
del is_admin # 首期管理员不可代操作;保留参数以对齐 API 契约。
|
||||
return task.user_id is not None and int(task.user_id) == int(user_id)
|
||||
|
||||
|
||||
def _latest_task_event_summary(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
取任务最近一条 ShippingTaskEvent 摘要;无事件时返回 None。
|
||||
|
||||
核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。
|
||||
"""
|
||||
if task.id is None:
|
||||
return None
|
||||
event = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if event is None:
|
||||
return None
|
||||
return {
|
||||
"event_type": event.event_type,
|
||||
"created_at": event.created_at.isoformat() if event.created_at else None,
|
||||
"detail_json": event.detail_json,
|
||||
"actor_id": event.actor_id,
|
||||
}
|
||||
|
||||
|
||||
def _artifact_summary_for_task(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。
|
||||
|
||||
核心逻辑:优先读任务上的 export_file_*;有路径或文件名即视为有摘要。
|
||||
"""
|
||||
file_name = str(task.export_file_name or "").strip() or None
|
||||
file_path = str(task.export_file_path or "").strip() or None
|
||||
if not file_name and not file_path:
|
||||
return None
|
||||
return {
|
||||
"export_file_name": file_name,
|
||||
"export_file_path": file_path,
|
||||
}
|
||||
|
||||
|
||||
def _enrich_task_center_fields(
|
||||
task: ShippingTask,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||||
|
||||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||||
recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
data: 已构建的序列化字典。
|
||||
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
|
||||
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
|
||||
|
||||
Returns:
|
||||
同一 data 引用(已 enrich)。
|
||||
"""
|
||||
data["todo_category"] = task_todo_category(task)
|
||||
data["item_kind"] = "task"
|
||||
data["todo_ref"] = task.task_no
|
||||
data["created_by"] = task.user_id
|
||||
if viewer_user_id is not None:
|
||||
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)
|
||||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
data["ui_state"] = build_task_ui_state(task)
|
||||
return data
|
||||
|
||||
|
||||
def serialize_task_summary(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务列表用的 SUMMARY 投影(含任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
viewer_user_id: 当前查看者;用于 can_handle;缺省时省略该字段。
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||||
return _enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def serialize_task_detail(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.DETAIL)
|
||||
return _enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
|
||||
@@ -830,7 +1107,10 @@ def list_tasks_for_user(
|
||||
else:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
|
||||
return [serialize_task_summary(c) for c in rows]
|
||||
return [
|
||||
serialize_task_summary(c, viewer_user_id=user_id)
|
||||
for c in rows
|
||||
]
|
||||
|
||||
|
||||
def list_tasks_page_for_user(
|
||||
@@ -887,7 +1167,10 @@ def list_tasks_page_for_user(
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"items": [serialize_task_summary(item) for item in rows],
|
||||
"items": [
|
||||
serialize_task_summary(item, viewer_user_id=user_id)
|
||||
for item in rows
|
||||
],
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
@@ -895,10 +1178,614 @@ def list_tasks_page_for_user(
|
||||
|
||||
|
||||
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
|
||||
"""按 task_no 查找任务并校验 user_id 归属。"""
|
||||
"""
|
||||
按 task_no 查找任务并校验写路径归属(严格创建者)。
|
||||
|
||||
核心逻辑:仅当 task.user_id == user_id 时返回;user_id IS NULL 一律拒绝,
|
||||
避免历史无主任务被任意登录用户写入。管理员只读请用 get_task_visible_to_user。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return None
|
||||
if task.user_id is not None and task.user_id != user_id:
|
||||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||||
return None
|
||||
return task
|
||||
|
||||
|
||||
def get_task_visible_to_user(
|
||||
task_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> ShippingTask | None:
|
||||
"""
|
||||
按 task_no 查找当前用户可见的任务(创建者或管理员只读)。
|
||||
|
||||
核心逻辑:管理员可读全部;普通用户仅可读自己创建且 user_id 非空的任务。
|
||||
写操作仍须经 get_task_for_user / task_can_handle 门禁。
|
||||
|
||||
Args:
|
||||
task_no: 任务编号。
|
||||
user_id: 当前用户。
|
||||
is_admin: 为 True 时允许管理员只读可见。
|
||||
|
||||
Returns:
|
||||
可见任务或 None。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return None
|
||||
if is_admin:
|
||||
return task
|
||||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||||
return None
|
||||
return task
|
||||
|
||||
|
||||
def _task_matches_customer_filter(task: ShippingTask, customer: str) -> bool:
|
||||
"""待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。"""
|
||||
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))
|
||||
if task.source_file_name:
|
||||
candidates.append(str(task.source_file_name))
|
||||
header = current_header_field_values_or_empty(task)
|
||||
for key in ("customer_name", "bill_to_customer", "ship_to_customer", "customer_code"):
|
||||
value = header.get(key)
|
||||
if value:
|
||||
candidates.append(str(value))
|
||||
return any(needle in item.lower() for item in candidates)
|
||||
|
||||
|
||||
def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False):
|
||||
"""构造「我的待办」可见任务基础查询(活跃生命周期)。"""
|
||||
q = ShippingTask.query.filter(
|
||||
ShippingTask.deleted_at.is_(None),
|
||||
ShippingTask.lifecycle_status == "active",
|
||||
)
|
||||
if not is_admin:
|
||||
# 待办中心拒绝无主任务;仅创建者可见。
|
||||
q = q.filter(ShippingTask.user_id == user_id)
|
||||
return q
|
||||
|
||||
|
||||
def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False):
|
||||
"""
|
||||
构造建单前开放 Review Case 查询(尚未确认建单)。
|
||||
|
||||
核心逻辑:排除已确认/非订单/已替代 Case;非管理员仅 owner_user_id==user_id。
|
||||
"""
|
||||
q = ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.status.in_(tuple(_OPEN_REVIEW_CASE_STATUSES)),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
if not is_admin:
|
||||
q = q.filter(ShippingOrderReviewCase.owner_user_id == int(user_id))
|
||||
return q
|
||||
|
||||
|
||||
def serialize_review_case_todo(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将建单前 Review Case 投影为「我的待办」列表项,供打开人工复核深链。
|
||||
|
||||
核心逻辑:附带 review_run_no / review_case_no / owner_agent_id / conversation_id;
|
||||
todo_category 固定 review;entry_surface=review_workbench。
|
||||
|
||||
Args:
|
||||
case: 开放中的 Review Case。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图(不开放代操作)。
|
||||
|
||||
Returns:
|
||||
与任务 SUMMARY 兼容的待办字典。
|
||||
"""
|
||||
del is_admin
|
||||
run = db.session.get(ShippingOrderExtractionRun, case.run_id) if case.run_id else None
|
||||
document = db.session.get(ShippingNoticeDocument, case.document_id) if case.document_id else None
|
||||
source_name = None
|
||||
if document is not None:
|
||||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||||
current_todo = _REVIEW_CASE_STATUS_TODO.get(str(case.status), "订单 PDF 待人工复核")
|
||||
can_handle = (
|
||||
viewer_user_id is not None
|
||||
and case.owner_user_id is not None
|
||||
and int(case.owner_user_id) == int(viewer_user_id)
|
||||
)
|
||||
run_no = str(getattr(run, "run_no", None) or "").strip() or None
|
||||
conversation_id = str(getattr(run, "conversation_id", None) or "").strip() or None
|
||||
owner_agent_id = getattr(run, "owner_agent_id", None)
|
||||
item: dict[str, Any] = {
|
||||
"item_kind": "review_case",
|
||||
"todo_ref": case.case_no,
|
||||
"task_no": None,
|
||||
"todo_category": "review",
|
||||
"review_run_no": run_no,
|
||||
"review_case_no": case.case_no,
|
||||
"review_case_status": case.status,
|
||||
"conversation_id": conversation_id,
|
||||
"owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None,
|
||||
"created_by": case.owner_user_id,
|
||||
"source_file_name": source_name,
|
||||
"customer_name": None,
|
||||
"process_status": None,
|
||||
"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": {
|
||||
"checkpoint": "order_review",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"action_buttons": [],
|
||||
"summary": {
|
||||
"title": "待人工复核",
|
||||
"message": current_todo,
|
||||
"stage": "待人工复核",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"current_todo": current_todo,
|
||||
"pause_reason": current_todo,
|
||||
"pause_reason_code": f"review_case_{case.status}",
|
||||
"next_auto_step": None,
|
||||
"event_at": case.updated_at.isoformat() if case.updated_at else None,
|
||||
"entry_surface": "review_workbench",
|
||||
"allowed_actions": [],
|
||||
"issues": [],
|
||||
"error_message": None,
|
||||
},
|
||||
},
|
||||
}
|
||||
if viewer_user_id is not None:
|
||||
item["can_handle"] = can_handle
|
||||
return item
|
||||
|
||||
|
||||
def _todo_category_sql_filter(allowed: frozenset[str]):
|
||||
"""
|
||||
将待办类别粗筛下推到 SQL,缩小活跃任务读取面。
|
||||
|
||||
核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。
|
||||
"""
|
||||
clauses = []
|
||||
if "done" in allowed:
|
||||
clauses.append(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
if "manual_upload" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(("waiting_upload", "upload_failed")),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
)
|
||||
)
|
||||
if "review" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "pending_review",
|
||||
ShippingTask.review_status.isnot(None),
|
||||
)
|
||||
)
|
||||
if "exception" in allowed:
|
||||
clauses.append(ShippingTask.pending_human_reason.isnot(None))
|
||||
if "in_progress" in allowed:
|
||||
clauses.append(
|
||||
ShippingTask.process_status.in_(
|
||||
("created", "parsed", "matched", "inventory_ready")
|
||||
)
|
||||
)
|
||||
if not clauses:
|
||||
return None
|
||||
return db.or_(*clauses)
|
||||
|
||||
|
||||
def _task_has_dynamic_order_lines_sql():
|
||||
"""
|
||||
SQL 版「已接受 Extraction 且至少有一行」。
|
||||
|
||||
核心逻辑:关联 EXISTS,对齐 _task_has_dynamic_order_lines,供分类 CASE 复用。
|
||||
"""
|
||||
return exists(
|
||||
select(1)
|
||||
.select_from(ShippingOrderExtraction)
|
||||
.where(
|
||||
ShippingOrderExtraction.id == ShippingTask.current_order_extraction_id,
|
||||
ShippingOrderExtraction.status == "accepted",
|
||||
exists(
|
||||
select(1)
|
||||
.select_from(ShippingOrderLine)
|
||||
.where(ShippingOrderLine.extraction_id == ShippingOrderExtraction.id)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _sql_json_falsy(column):
|
||||
"""JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。"""
|
||||
return db.or_(column.is_(None), column == [], column == {})
|
||||
|
||||
|
||||
def _sql_str_blank(column):
|
||||
"""字符串列空白:NULL 或空串。"""
|
||||
return db.or_(column.is_(None), column == "")
|
||||
|
||||
|
||||
def _task_todo_category_sql_expr():
|
||||
"""
|
||||
将 resolve_task_ui_state_from_fields 同序映射为 todo_category SQL CASE。
|
||||
|
||||
核心逻辑:分支顺序与状态机一致;直接产出 review|exception|manual_upload|in_progress|done,
|
||||
供 UNION 分页与徽标 COUNT 在数据库内过滤,避免轻量全量索引。
|
||||
"""
|
||||
has_lines = _task_has_dynamic_order_lines_sql()
|
||||
reason = ShippingTask.pending_human_reason
|
||||
return case(
|
||||
(ShippingTask.process_status == "uploaded", literal("done")),
|
||||
(ShippingTask.process_status == "closed", literal("done")),
|
||||
(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "rejected",
|
||||
ShippingTask.review_status == RS_REJECTED,
|
||||
),
|
||||
literal("done"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_RSV_REQ, ShippingTask.review_status == RS_RSV_REQ),
|
||||
literal("review"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_LOW_CONF, ShippingTask.review_status == RS_PARSE_REVIEW),
|
||||
literal("review"),
|
||||
),
|
||||
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.shipping_case_id.isnot(None),
|
||||
db.or_(
|
||||
ShippingTask.customer_resolution_status.is_(None),
|
||||
ShippingTask.customer_resolution_status != "confirmed",
|
||||
),
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.and_(ShippingTask.order_snapshot_id.is_(None), has_lines),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(reason == PH_RPA_EXHAUSTED, literal("exception")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "parsed",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_json_falsy(ShippingTask.inventory_lines_json),
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "inventory_ready",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_str_blank(ShippingTask.match_status),
|
||||
has_lines,
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "matched",
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
),
|
||||
literal("manual_upload"),
|
||||
),
|
||||
(ShippingTask.process_status == "matched", literal("in_progress")),
|
||||
(reason == PH_INV_UNAVAIL, literal("exception")),
|
||||
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
|
||||
(
|
||||
db.or_(reason == PH_SHORTAGE, ShippingTask.review_status == RS_SHORTAGE_REVIEW),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_FAILED,
|
||||
ShippingTask.process_status == "upload_failed",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("exception")),
|
||||
(reason == PH_RPA_PENDING, literal("exception")),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_PENDING,
|
||||
ShippingTask.process_status == "waiting_upload",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
else_=literal("in_progress"),
|
||||
)
|
||||
|
||||
|
||||
def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]:
|
||||
"""待办排序键:updated_at 降序 + 稳定引用(测试/调试辅助)。"""
|
||||
if hasattr(value, "isoformat"):
|
||||
stamp = value.isoformat()
|
||||
else:
|
||||
stamp = str(value or "")
|
||||
return (stamp, str(ref or ""))
|
||||
|
||||
|
||||
def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, customer_like: str):
|
||||
"""对开放 Review Case 查询追加客户关键字过滤。"""
|
||||
if not customer_needle:
|
||||
return cases_q
|
||||
matching_document_ids = db.session.query(ShippingNoticeDocument.id).filter(
|
||||
ShippingNoticeDocument.filename.ilike(customer_like),
|
||||
)
|
||||
matching_candidate_ids = db.session.query(ShippingNoticeCandidate.id).filter(
|
||||
ShippingNoticeCandidate.po_number.ilike(customer_like),
|
||||
)
|
||||
return cases_q.filter(
|
||||
db.or_(
|
||||
ShippingOrderReviewCase.case_no.ilike(customer_like),
|
||||
ShippingOrderReviewCase.document_id.in_(matching_document_ids),
|
||||
ShippingOrderReviewCase.candidate_id.in_(matching_candidate_ids),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _todo_tasks_base_query(
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool,
|
||||
allowed: frozenset[str],
|
||||
normalized_bucket: str,
|
||||
customer_needle: str,
|
||||
customer_like: str,
|
||||
task_no: str | None,
|
||||
):
|
||||
"""
|
||||
构造带粗筛 + 精确 category CASE 过滤的 Task 待办查询。
|
||||
|
||||
核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。
|
||||
"""
|
||||
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
if task_no:
|
||||
q = q.filter(ShippingTask.task_no == str(task_no).strip())
|
||||
if customer_needle:
|
||||
q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingTask.shipping_case_id).filter(
|
||||
db.or_(
|
||||
ShippingCase.customer_name_snapshot.ilike(customer_like),
|
||||
ShippingCase.customer_short_code_snapshot.ilike(customer_like),
|
||||
ShippingTask.source_file_name.ilike(customer_like),
|
||||
)
|
||||
)
|
||||
category_clause = _todo_category_sql_filter(allowed)
|
||||
if category_clause is not None:
|
||||
q = q.filter(category_clause)
|
||||
if normalized_bucket in {"pending", "processing"}:
|
||||
q = q.filter(
|
||||
db.or_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
elif normalized_bucket == "done":
|
||||
q = q.filter(
|
||||
ShippingTask.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
)
|
||||
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
|
||||
|
||||
|
||||
def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
|
||||
"""徽标统计用的活跃 Task 粗筛范围(不含 done)。"""
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter(
|
||||
db.or_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def list_my_todos(
|
||||
user_id: int,
|
||||
*,
|
||||
bucket: str = "pending",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
is_admin: bool = False,
|
||||
todo_category: str | None = None,
|
||||
customer: str | None = None,
|
||||
task_no: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出「我的待办」:建单前 Review Case + 建单后 Task 异常/上传。
|
||||
|
||||
核心逻辑:pending 桶合并开放 Review Case(todo_category=review,含 review_run_no 深链);
|
||||
Task 分类下推为与状态机同序的 SQL CASE;两端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT,
|
||||
仅水合当前页 id(禁止 limit(500) 截断冒充总数)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
bucket: pending(review|exception|manual_upload)| processing | done。
|
||||
page / page_size: 分页参数。
|
||||
is_admin: 管理员全局只读视图。
|
||||
todo_category: 可选细分类覆盖 bucket。
|
||||
customer: 客户名/代码/来源文件名/Case 号/PO 模糊过滤(Task 与 Review Case 均参与)。
|
||||
task_no: 精确任务号过滤(仅 Task 项;复核项忽略)。
|
||||
|
||||
Returns:
|
||||
{items, page, page_size, total}
|
||||
"""
|
||||
normalized_page = max(1, int(page))
|
||||
normalized_page_size = max(1, min(int(page_size), 100))
|
||||
normalized_bucket = str(bucket or "pending").strip().lower()
|
||||
allowed = _TODO_BUCKET_CATEGORIES.get(normalized_bucket, _PENDING_TODO_CATEGORIES)
|
||||
if todo_category:
|
||||
cat = str(todo_category).strip().lower()
|
||||
allowed = frozenset({cat}) if cat in {
|
||||
"review", "exception", "manual_upload", "in_progress", "done",
|
||||
} else allowed
|
||||
|
||||
customer_needle = str(customer or "").strip()
|
||||
customer_like = f"%{customer_needle}%" if customer_needle else ""
|
||||
include_review_cases = "review" in allowed and not task_no
|
||||
|
||||
# [STEP 1] 两端投影为统一列:kind / entity_id / sort_at / sort_ref。
|
||||
branches = []
|
||||
if include_review_cases:
|
||||
cases_q = _apply_review_case_customer_filter(
|
||||
_visible_open_review_cases_query(user_id, is_admin=is_admin),
|
||||
customer_needle=customer_needle,
|
||||
customer_like=customer_like,
|
||||
)
|
||||
branches.append(
|
||||
cases_q.with_entities(
|
||||
literal("review_case").label("kind"),
|
||||
ShippingOrderReviewCase.id.label("entity_id"),
|
||||
ShippingOrderReviewCase.updated_at.label("sort_at"),
|
||||
ShippingOrderReviewCase.case_no.label("sort_ref"),
|
||||
)
|
||||
)
|
||||
|
||||
tasks_q = _todo_tasks_base_query(
|
||||
user_id,
|
||||
is_admin=is_admin,
|
||||
allowed=allowed,
|
||||
normalized_bucket=normalized_bucket,
|
||||
customer_needle=customer_needle,
|
||||
customer_like=customer_like,
|
||||
task_no=task_no,
|
||||
)
|
||||
branches.append(
|
||||
tasks_q.with_entities(
|
||||
literal("task").label("kind"),
|
||||
ShippingTask.id.label("entity_id"),
|
||||
func.coalesce(ShippingTask.updated_at, ShippingTask.created_at).label("sort_at"),
|
||||
ShippingTask.task_no.label("sort_ref"),
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP 2] UNION ALL → COUNT 真总数 → OFFSET/LIMIT 仅取当前页引用。
|
||||
if len(branches) == 1:
|
||||
union_stmt = branches[0].order_by(None).statement
|
||||
else:
|
||||
union_stmt = union_all(*[branch.order_by(None).statement for branch in branches])
|
||||
combined = union_stmt.subquery("todo_union")
|
||||
total = int(
|
||||
db.session.execute(select(func.count()).select_from(combined)).scalar_one() or 0
|
||||
)
|
||||
offset = (normalized_page - 1) * normalized_page_size
|
||||
page_refs = (
|
||||
db.session.execute(
|
||||
select(combined.c.kind, combined.c.entity_id)
|
||||
.order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id))
|
||||
.offset(offset)
|
||||
.limit(normalized_page_size)
|
||||
).all()
|
||||
if total and offset < total
|
||||
else []
|
||||
)
|
||||
|
||||
# [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。
|
||||
page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"]
|
||||
page_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"]
|
||||
cases_by_id: dict[int, ShippingOrderReviewCase] = {}
|
||||
if page_case_ids:
|
||||
for case in ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.id.in_(page_case_ids),
|
||||
).all():
|
||||
cases_by_id[int(case.id)] = case
|
||||
tasks_by_id: dict[int, ShippingTask] = {}
|
||||
if page_task_ids:
|
||||
for task in ShippingTask.query.filter(ShippingTask.id.in_(page_task_ids)).all():
|
||||
tasks_by_id[int(task.id)] = task
|
||||
|
||||
page_rows: list[dict[str, Any]] = []
|
||||
for kind, entity_id in page_refs:
|
||||
entity_id_int = int(entity_id)
|
||||
if kind == "review_case":
|
||||
case = cases_by_id.get(entity_id_int)
|
||||
if case is None:
|
||||
continue
|
||||
page_rows.append(
|
||||
serialize_review_case_todo(
|
||||
case, viewer_user_id=user_id, is_admin=is_admin,
|
||||
)
|
||||
)
|
||||
continue
|
||||
task = tasks_by_id.get(entity_id_int)
|
||||
if task is None:
|
||||
continue
|
||||
page_rows.append(
|
||||
serialize_task_summary(task, viewer_user_id=user_id, is_admin=is_admin)
|
||||
)
|
||||
|
||||
return {
|
||||
"items": page_rows,
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
|
||||
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
"""
|
||||
统计「我的待办」各 bucket 数量,供导航徽标使用。
|
||||
|
||||
核心逻辑:开放 Review Case 计入 pending;Task 用 SQL CASE 分类后 COUNT,
|
||||
不扫描全量 ORM 行。
|
||||
|
||||
Returns:
|
||||
{pending, processing, done, total_pending_badge}
|
||||
"""
|
||||
pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count()
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
active = _active_todo_tasks_scope(user_id, is_admin=is_admin)
|
||||
pending += (
|
||||
active.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES)))).count()
|
||||
)
|
||||
processing = active.filter(category_expr == "in_progress").count()
|
||||
done = (
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
.filter(category_expr == "done")
|
||||
.count()
|
||||
)
|
||||
return {
|
||||
"pending": pending,
|
||||
"processing": processing,
|
||||
"done": done,
|
||||
"total_pending_badge": pending,
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/standard_field_registry.py
|
||||
|
||||
用途:注册货代订单系统标准字段目录(锁定 57 项)及 Snapshot 核心投影元数据。
|
||||
依赖:shipping_order_snapshot ORM 列、order_freeze_service 投影表。
|
||||
逻辑:字段资产种子与治理校验只读本注册表;扩展字段不得占用标准 field_code;
|
||||
typed 项必须能投影到 Snapshot 物理列。启动/测试可调用 assert_registry_consistent。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from app.models.shipping_order_snapshot import ShippingOrderSnapshot, ShippingOrderSnapshotLine
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
)
|
||||
|
||||
StorageMode = Literal['typed_column', 'json_only']
|
||||
FieldScope = Literal['header', 'line']
|
||||
ValueType = Literal['string', 'decimal', 'integer', 'date', 'boolean', 'enum']
|
||||
|
||||
# 默认 Schema 族编码(本轮 UI/运行唯一启用)。
|
||||
DEFAULT_SCHEMA_FAMILY_CODE = 'STANDARD_SHIPPING_NOTICE'
|
||||
DEFAULT_SCHEMA_FAMILY_NAME = '标准发货通知'
|
||||
|
||||
# 首发建议采用集(C4);迁移不自动发布,仅供 UI/API 辅助勾选。
|
||||
DEFAULT_V1_ADOPTION_CODES: tuple[str, ...] = (
|
||||
'customer_po_number',
|
||||
'bill_to_customer',
|
||||
'bill_to_address',
|
||||
'ship_to_customer',
|
||||
'ship_to_address',
|
||||
'currency',
|
||||
'line_no',
|
||||
'part_number',
|
||||
'customer_part_number',
|
||||
'required_date',
|
||||
'qty',
|
||||
'uom',
|
||||
'line_amount_with_tax',
|
||||
'reservation_id',
|
||||
'inventory_source_hint',
|
||||
)
|
||||
|
||||
# 履约核心能力仅允许绑定的标准表身字段。
|
||||
FULFILLMENT_CORE_FIELD_CODES: frozenset[str] = frozenset({'part_number', 'reservation_id', 'qty'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StandardFieldSpec:
|
||||
"""单条系统标准字段的不可变注册项。"""
|
||||
|
||||
field_code: str
|
||||
scope: FieldScope
|
||||
value_type: ValueType
|
||||
display_name: str
|
||||
semantic_description: str
|
||||
storage_mode: StorageMode
|
||||
storage_column: str | None = None
|
||||
fulfillment_role: str | None = None
|
||||
|
||||
|
||||
def _typed(scope: FieldScope, field_code: str) -> tuple[StorageMode, str | None]:
|
||||
"""按冻结投影表判定标准字段是否双写强类型列。"""
|
||||
projections = HEADER_FIELD_PROJECTIONS if scope == 'header' else LINE_FIELD_PROJECTIONS
|
||||
column = projections.get(field_code)
|
||||
if column:
|
||||
return 'typed_column', column
|
||||
return 'json_only', None
|
||||
|
||||
|
||||
def _spec(
|
||||
field_code: str,
|
||||
scope: FieldScope,
|
||||
value_type: ValueType,
|
||||
display_name: str,
|
||||
semantic_description: str,
|
||||
*,
|
||||
fulfillment_role: str | None = None,
|
||||
) -> StandardFieldSpec:
|
||||
"""组装标准字段注册项并自动标注存储模式。"""
|
||||
storage_mode, storage_column = _typed(scope, field_code)
|
||||
return StandardFieldSpec(
|
||||
field_code=field_code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
display_name=display_name,
|
||||
semantic_description=semantic_description,
|
||||
storage_mode=storage_mode,
|
||||
storage_column=storage_column,
|
||||
fulfillment_role=fulfillment_role,
|
||||
)
|
||||
|
||||
|
||||
# [STEP 1] 锁定的 57 项标准目录(与历史 STANDARD_ORDER_FIELD_SPECS 编码/范围/类型一致)。
|
||||
_STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
|
||||
_spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'),
|
||||
_spec('order_date', 'header', 'date', '订单日期', '客户订单或发货通知上的订单日期'),
|
||||
_spec('source_order_number', 'header', 'string', '来源单号', '客户或上游系统的来源单据号'),
|
||||
_spec('contract_number', 'header', 'string', '合同号', '商务合同或框架协议编号'),
|
||||
_spec('order_type', 'header', 'string', '订单类型', '订单业务类型分类'),
|
||||
_spec('sales_channel', 'header', 'string', '销售渠道', '订单销售或交付渠道'),
|
||||
_spec('customer_code', 'header', 'string', '客户编码', '客户侧或外部系统客户编码'),
|
||||
_spec('customer_name', 'header', 'string', '客户名称', '客户法定或常用名称'),
|
||||
_spec('bill_to_customer', 'header', 'string', '账款客户', '账单/账款对象客户名称'),
|
||||
_spec('bill_to_address', 'header', 'string', '账款地址', '账单/账款地址'),
|
||||
_spec('ship_to_customer', 'header', 'string', '送货客户', '收货方客户名称'),
|
||||
_spec('ship_to_address', 'header', 'string', '送货地址', '收货地址'),
|
||||
_spec('end_customer', 'header', 'string', '最终客户', '终端使用客户'),
|
||||
_spec('customer_contact', 'header', 'string', '客户联系人', '订单相关联系人'),
|
||||
_spec('ship_from_organization', 'header', 'string', '发货组织', '发货组织或交付组织'),
|
||||
_spec('destination', 'header', 'string', '目的地', '交付目的地或口岸'),
|
||||
_spec('currency', 'header', 'string', '币种', '金额币种'),
|
||||
_spec('incoterm', 'header', 'string', '贸易条款', '国际贸易术语'),
|
||||
_spec('payment_term', 'header', 'string', '付款条款', '付款条件'),
|
||||
_spec('mark_number', 'header', 'string', '唛头', '包装唛头标识'),
|
||||
_spec('direct_ship_required', 'header', 'boolean', '是否直发', '是否要求直发'),
|
||||
_spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'),
|
||||
_spec('order_remark', 'header', 'string', '订单备注', '订单头备注'),
|
||||
_spec('line_no', 'line', 'string', '项次', '订单明细行号'),
|
||||
_spec('reservation_id', 'line', 'string', '预约单号', '库存占用/预约单标识', fulfillment_role='reservation_identity'),
|
||||
_spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'),
|
||||
_spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'),
|
||||
_spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'),
|
||||
_spec('customer_po_line_no', 'line', 'string', '客户 PO 行号', '客户采购订单行号'),
|
||||
_spec('product_feature', 'line', 'string', '产品特征', '产品特征或规格摘要'),
|
||||
_spec('qty', 'line', 'decimal', '数量', '本行需求数量,须大于 0', fulfillment_role='quantity'),
|
||||
_spec('uom', 'line', 'string', '单位', '数量计量单位'),
|
||||
_spec('reference_qty', 'line', 'decimal', '参考数量', '参考计量数量'),
|
||||
_spec('reference_uom', 'line', 'string', '参考单位', '参考计量单位'),
|
||||
_spec('pricing_qty', 'line', 'decimal', '计价数量', '计价用数量'),
|
||||
_spec('pricing_uom', 'line', 'string', '计价单位', '计价用单位'),
|
||||
_spec('required_date', 'line', 'date', '要求送货日期', '要求交货/送货日期'),
|
||||
_spec('requested_receipt_date', 'line', 'date', '要求收货日期', '要求收货日期'),
|
||||
_spec('unit_price', 'line', 'decimal', '单价', '行单价'),
|
||||
_spec('line_amount_before_tax', 'line', 'decimal', '未税金额', '行未税金额'),
|
||||
_spec('line_tax_amount', 'line', 'decimal', '税额', '行税额'),
|
||||
_spec('line_amount_with_tax', 'line', 'decimal', '含税金额', '行含税金额'),
|
||||
_spec('tax_category', 'line', 'string', '税种', '税分类'),
|
||||
_spec('tax_rate', 'line', 'decimal', '税率', '适用税率'),
|
||||
_spec('ship_from_site', 'line', 'string', '发货站点', '发货站点或库房线索'),
|
||||
_spec('line_ship_to_address', 'line', 'string', '行送货地址', '明细级送货地址'),
|
||||
_spec('requested_warehouse_code', 'line', 'string', '请求仓库', '客户或业务请求仓库编码'),
|
||||
_spec('storage_location_code', 'line', 'string', '库位编码', '库存库位编码'),
|
||||
_spec('lot_number', 'line', 'string', '批次号', '物料批次'),
|
||||
_spec('inventory_source_hint', 'line', 'string', '库存源线索', '可选库存路由线索', fulfillment_role='inventory_source_hint'),
|
||||
_spec('partial_delivery_allowed', 'line', 'boolean', '允许部分交货', '是否允许分批发货'),
|
||||
_spec('bonded_flag', 'line', 'boolean', '保税标记', '是否保税'),
|
||||
_spec('package_type', 'line', 'string', '包装类型', '包装方式'),
|
||||
_spec('project_code', 'line', 'string', '项目编码', '项目号'),
|
||||
_spec('wbs_code', 'line', 'string', 'WBS 编码', 'WBS 结构编码'),
|
||||
_spec('activity_code', 'line', 'string', '活动编码', '项目活动编码'),
|
||||
_spec('line_remark', 'line', 'string', '行备注', '明细备注'),
|
||||
)
|
||||
|
||||
STANDARD_FIELD_SPECS: dict[str, StandardFieldSpec] = {
|
||||
item.field_code: item for item in _STANDARD_FIELD_SPECS
|
||||
}
|
||||
|
||||
# 兼容旧服务中 (scope, value_type) 二元组查询。
|
||||
STANDARD_ORDER_FIELD_SPECS: dict[str, tuple[str, str]] = {
|
||||
code: (spec.scope, spec.value_type) for code, spec in STANDARD_FIELD_SPECS.items()
|
||||
}
|
||||
|
||||
|
||||
def standard_field_codes() -> frozenset[str]:
|
||||
"""返回全部标准 field_code 集合。"""
|
||||
return frozenset(STANDARD_FIELD_SPECS)
|
||||
|
||||
|
||||
def is_standard_field_code(field_code: str) -> bool:
|
||||
"""判断编码是否属于锁定的系统标准目录。"""
|
||||
return str(field_code or '').strip().lower() in STANDARD_FIELD_SPECS
|
||||
|
||||
|
||||
def get_standard_field(field_code: str) -> StandardFieldSpec | None:
|
||||
"""按编码读取标准字段注册项。"""
|
||||
return STANDARD_FIELD_SPECS.get(str(field_code or '').strip().lower())
|
||||
|
||||
|
||||
def assert_registry_consistent() -> None:
|
||||
"""
|
||||
校验注册表内部一致性及与 Snapshot ORM / 冻结投影的对齐。
|
||||
|
||||
Raises:
|
||||
AssertionError: 数量不为 57、typed 列缺失、或投影键不在标准目录中。
|
||||
"""
|
||||
# [STEP 1] 锁定数量与唯一性
|
||||
assert len(STANDARD_FIELD_SPECS) == 57, f'expected 57 standard fields, got {len(STANDARD_FIELD_SPECS)}'
|
||||
assert len(_STANDARD_FIELD_SPECS) == 57
|
||||
header_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'header')
|
||||
line_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'line')
|
||||
assert header_count == 23 and line_count == 34
|
||||
|
||||
# [STEP 2] typed 投影列必须存在于 Snapshot ORM
|
||||
header_columns = {column.key for column in ShippingOrderSnapshot.__table__.columns}
|
||||
line_columns = {column.key for column in ShippingOrderSnapshotLine.__table__.columns}
|
||||
for spec in _STANDARD_FIELD_SPECS:
|
||||
if spec.storage_mode != 'typed_column':
|
||||
continue
|
||||
assert spec.storage_column, f'{spec.field_code} typed without column'
|
||||
table_cols = header_columns if spec.scope == 'header' else line_columns
|
||||
assert spec.storage_column in table_cols, (
|
||||
f'{spec.field_code} maps to missing column {spec.storage_column}'
|
||||
)
|
||||
|
||||
# [STEP 3] 冻结投影表的每个键都必须是标准字段
|
||||
for code in HEADER_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'header'
|
||||
for code in LINE_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
|
||||
# [STEP 4] 建议采用集与履约核心均落在标准目录
|
||||
for code in DEFAULT_V1_ADOPTION_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS
|
||||
for code in FULFILLMENT_CORE_FIELD_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
services/shipping_notice/state_machine.py
|
||||
|
||||
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
|
||||
用途:发货通知检查点(checkpoint)与工作台动作按钮的单一注册表,负责任务 DB 字段与 UI 状态映射。
|
||||
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
|
||||
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试;
|
||||
是否具备可匹配订单行经锁定 Extraction 的 FieldValue 判断。
|
||||
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind 与按钮;
|
||||
resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台,
|
||||
Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。
|
||||
|
||||
扩展说明(开发者):
|
||||
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
|
||||
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
|
||||
- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition
|
||||
- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布
|
||||
"""
|
||||
@@ -56,6 +58,10 @@ from app.services.shipping_notice.constants import (
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
|
||||
|
||||
def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
@@ -67,13 +73,24 @@ def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
if extraction is None or extraction.status != "accepted":
|
||||
return False
|
||||
return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action buttons (id → label / message / variant)
|
||||
# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class CheckpointKind(StrEnum):
|
||||
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传 / 完成。"""
|
||||
|
||||
AUTO_CONTINUE = "auto_continue"
|
||||
MUST_HUMAN = "must_human"
|
||||
WAIT_MANUAL_UPLOAD = "wait_manual_upload"
|
||||
COMPLETE = "complete"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action buttons (id → label / message / variant) — 任务处理工作台动作目录
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
@@ -88,6 +105,11 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "上传库存文件",
|
||||
"message": "上传库存 Excel",
|
||||
"variant": "primary",
|
||||
},
|
||||
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
|
||||
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
|
||||
"mark_manual_uploaded": {
|
||||
@@ -107,7 +129,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
},
|
||||
}
|
||||
|
||||
# checkpoint id → default human option ids (HTTP / Dify before task reload)
|
||||
# checkpoint id → default human option ids
|
||||
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
|
||||
CP_CUSTOMER_REVIEW: ("confirm_customer",),
|
||||
@@ -133,6 +155,29 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_COMPLETED: (),
|
||||
}
|
||||
|
||||
# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue)
|
||||
CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
|
||||
CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN,
|
||||
CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_RSV_REQ: CheckpointKind.MUST_HUMAN,
|
||||
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_WAITING_UPLOAD: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.MUST_HUMAN,
|
||||
CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_REJECTED: CheckpointKind.COMPLETE,
|
||||
CP_UPLOADED: CheckpointKind.COMPLETE,
|
||||
CP_COMPLETED: CheckpointKind.COMPLETE,
|
||||
}
|
||||
|
||||
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
|
||||
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
|
||||
|
||||
@@ -143,8 +188,11 @@ OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa")
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskUiState:
|
||||
"""统一任务 UI 状态:checkpoint + STP kind + 工作台可用动作。"""
|
||||
|
||||
checkpoint: str | None
|
||||
human_options: list[str] | None
|
||||
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
|
||||
|
||||
@property
|
||||
def action_buttons(self) -> list[dict[str, str]]:
|
||||
@@ -164,11 +212,31 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
|
||||
return buttons
|
||||
|
||||
|
||||
def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
|
||||
"""
|
||||
按 checkpoint id 解析 STP 检查点分类。
|
||||
|
||||
核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。
|
||||
"""
|
||||
if not checkpoint:
|
||||
return CheckpointKind.AUTO_CONTINUE
|
||||
return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN)
|
||||
|
||||
|
||||
def _task_ui_state(checkpoint: str | None, human_options: list[str] | None) -> TaskUiState:
|
||||
"""构造带 checkpoint_kind 的 TaskUiState。"""
|
||||
return TaskUiState(
|
||||
checkpoint=checkpoint,
|
||||
human_options=human_options,
|
||||
checkpoint_kind=checkpoint_kind_for(checkpoint),
|
||||
)
|
||||
|
||||
|
||||
def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"""
|
||||
将库存源候选项转成聊天区可直接点击的确认按钮。
|
||||
将库存源候选项转成工作台可直接点击的确认按钮。
|
||||
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口并触发 RPA,
|
||||
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口,
|
||||
避免先把候选源文本发给 Agent 再等待二次确认。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
@@ -222,7 +290,7 @@ def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
|
||||
cp = str(checkpoint).strip() if checkpoint else None
|
||||
if cp and cp not in CHECKPOINT_REGISTRY:
|
||||
cp = None
|
||||
return TaskUiState(checkpoint=cp, human_options=options)
|
||||
return _task_ui_state(cp, options)
|
||||
|
||||
|
||||
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
|
||||
@@ -249,133 +317,138 @@ def human_options_for_task_or_checkpoint(
|
||||
return human_options_for_checkpoint(checkpoint)
|
||||
|
||||
|
||||
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
def resolve_task_ui_state_from_fields(
|
||||
*,
|
||||
process_status: str | None,
|
||||
review_status: str | None,
|
||||
pending_human_reason: str | None,
|
||||
shipping_case_id: int | None,
|
||||
customer_resolution_status: str | None,
|
||||
order_snapshot_id: int | None,
|
||||
inventory_lines_json: Any,
|
||||
match_status: str | None,
|
||||
export_file_path: str | None,
|
||||
has_dynamic_order_lines: bool,
|
||||
upload_req_options: list[str] | None = None,
|
||||
upload_req_task: ShippingTask | None = None,
|
||||
) -> TaskUiState:
|
||||
"""
|
||||
将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
|
||||
由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。
|
||||
|
||||
核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。
|
||||
核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算,
|
||||
供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。
|
||||
upload_req_options / upload_req_task 仅在命中 upload_req 分支时解析按钮列表。
|
||||
"""
|
||||
|
||||
def _upload_opts() -> list[str]:
|
||||
if upload_req_options is not None:
|
||||
return list(upload_req_options)
|
||||
if upload_req_task is not None:
|
||||
return upload_req_options_for_task(upload_req_task)
|
||||
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
|
||||
|
||||
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
|
||||
if task.process_status == "uploaded":
|
||||
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
|
||||
if task.process_status == "closed":
|
||||
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
|
||||
if process_status == "uploaded":
|
||||
return _task_ui_state(CP_UPLOADED, [])
|
||||
if process_status == "closed":
|
||||
return _task_ui_state(CP_COMPLETED, [])
|
||||
|
||||
if task.process_status == "rejected" or task.review_status == "rejected":
|
||||
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
|
||||
if process_status == "rejected" or review_status == "rejected":
|
||||
return _task_ui_state(CP_REJECTED, [])
|
||||
|
||||
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
|
||||
reason = task.pending_human_reason
|
||||
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
|
||||
)
|
||||
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
reason = pending_human_reason
|
||||
if reason == PH_RSV_REQ or review_status == RS_RSV_REQ:
|
||||
return _task_ui_state(CP_RSV_REQ, list(CHECKPOINT_REGISTRY[CP_RSV_REQ]))
|
||||
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
|
||||
return _task_ui_state(CP_PARSE_REVIEW, list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]))
|
||||
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
return _task_ui_state(
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
)
|
||||
|
||||
if task.shipping_case_id is not None and task.customer_resolution_status != "confirmed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_CUSTOMER_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]),
|
||||
)
|
||||
if shipping_case_id is not None and customer_resolution_status != "confirmed":
|
||||
return _task_ui_state(CP_CUSTOMER_REVIEW, list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]))
|
||||
|
||||
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结动作始终在 Chat Turn 执行。
|
||||
if not task.order_snapshot_id and _task_has_dynamic_order_lines(task):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_ORDER_FREEZE,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]),
|
||||
)
|
||||
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
|
||||
if not order_snapshot_id and has_dynamic_order_lines:
|
||||
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
|
||||
|
||||
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
|
||||
if reason == PH_RPA_EXHAUSTED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
|
||||
if (
|
||||
task.process_status == "parsed"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.inventory_lines_json
|
||||
process_status == "parsed"
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not inventory_lines_json
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_PENDING,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
|
||||
)
|
||||
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
|
||||
|
||||
if (
|
||||
task.process_status == "inventory_ready"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.match_status
|
||||
and bool(_task_has_dynamic_order_lines(task))
|
||||
process_status == "inventory_ready"
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not match_status
|
||||
and has_dynamic_order_lines
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_MATCH,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
|
||||
)
|
||||
return _task_ui_state(CP_READY_MATCH, list(CHECKPOINT_REGISTRY[CP_READY_MATCH]))
|
||||
|
||||
# [STEP 4] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。
|
||||
if task.process_status == "matched":
|
||||
if task.export_file_path:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_EXPORT_READY,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
|
||||
)
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_EXPORT,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
|
||||
)
|
||||
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
|
||||
if process_status == "matched":
|
||||
if export_file_path:
|
||||
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
|
||||
return _task_ui_state(CP_READY_EXPORT, list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]))
|
||||
|
||||
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
if reason == PH_INV_UNAVAIL:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
|
||||
return _task_ui_state(
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
|
||||
)
|
||||
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
|
||||
return _task_ui_state(RS_SHORTAGE_REVIEW, list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]))
|
||||
if reason == PH_UPLOAD_RPA_FAILED or process_status == "upload_failed":
|
||||
return _task_ui_state(CP_UPLOAD_FAILED, list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]))
|
||||
if reason == PH_UPLOAD_RESULT_UNKNOWN:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_RESULT_UNKNOWN,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
|
||||
return _task_ui_state(
|
||||
CP_UPLOAD_RESULT_UNKNOWN,
|
||||
list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
|
||||
)
|
||||
if reason == PH_RPA_PENDING or (
|
||||
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_WAITING_UPLOAD,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
|
||||
)
|
||||
return TaskUiState(checkpoint=None, human_options=None)
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
if reason == PH_UPLOAD_RPA_PENDING or process_status == "waiting_upload":
|
||||
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
|
||||
return _task_ui_state(None, None)
|
||||
|
||||
|
||||
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
"""
|
||||
将 ShippingTask DB 字段映射为 checkpoint + checkpoint_kind + human_options。
|
||||
|
||||
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
|
||||
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
|
||||
履约写操作由任务处理工作台消费 action_buttons;Chat 不再作为写入口。
|
||||
"""
|
||||
return resolve_task_ui_state_from_fields(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
order_snapshot_id=task.order_snapshot_id,
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
has_dynamic_order_lines=_task_has_dynamic_order_lines(task),
|
||||
upload_req_task=task,
|
||||
)
|
||||
|
||||
|
||||
def checkpoint_for_task(task: ShippingTask) -> str | None:
|
||||
@@ -396,6 +469,7 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
checkpoints.append(
|
||||
{
|
||||
"id": checkpoint_id,
|
||||
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
|
||||
"human_options": list(option_ids),
|
||||
"action_buttons": buttons,
|
||||
}
|
||||
@@ -403,6 +477,7 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
return {
|
||||
"checkpoints": checkpoints,
|
||||
"action_specs": ACTION_SPECS,
|
||||
"checkpoint_kinds": {k: str(v) for k, v in CHECKPOINT_KIND_REGISTRY.items()},
|
||||
"dify_fallback": {
|
||||
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
|
||||
},
|
||||
@@ -410,12 +485,17 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
|
||||
|
||||
def validate_registry() -> list[str]:
|
||||
"""校验 CHECKPOINT_REGISTRY 中 action id 是否均存在于 ACTION_SPECS;测试用。"""
|
||||
"""校验 CHECKPOINT_REGISTRY 动作完整性与 KIND 覆盖;测试用。"""
|
||||
errors: list[str] = []
|
||||
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
|
||||
for option_id in option_ids:
|
||||
if option_id not in ACTION_SPECS:
|
||||
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
|
||||
if checkpoint_id not in CHECKPOINT_KIND_REGISTRY:
|
||||
errors.append(f"checkpoint {checkpoint_id}: missing checkpoint_kind")
|
||||
for checkpoint_id in CHECKPOINT_KIND_REGISTRY:
|
||||
if checkpoint_id not in CHECKPOINT_REGISTRY:
|
||||
errors.append(f"checkpoint_kind {checkpoint_id}: not in CHECKPOINT_REGISTRY")
|
||||
return errors
|
||||
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
|
||||
extraction = _current_extraction(task)
|
||||
global_sequences = {
|
||||
str(field.field_code): int(field.display_sequence or 0)
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all()
|
||||
for field in ShippingOrderField.query.all()
|
||||
}
|
||||
fields = sorted(
|
||||
[
|
||||
|
||||
@@ -253,14 +253,32 @@ def build_task_action_event_detail(
|
||||
return detail
|
||||
|
||||
|
||||
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
|
||||
"""写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。"""
|
||||
def log_task_event(
|
||||
task: ShippingTask,
|
||||
event_type: str,
|
||||
detail: dict[str, Any] | None = None,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。
|
||||
|
||||
核心逻辑:actor_id 为 None 表示系统动作(STP auto_progress / orchestrator);
|
||||
人工动作传入真实用户 ID。detail 可含 source=system|workspace_api|tool_api 等。
|
||||
|
||||
Args:
|
||||
task: 目标任务。
|
||||
event_type: 事件类型码。
|
||||
detail: 结构化明细;可含 source。
|
||||
actor_id: 操作者用户 ID;系统事件传 None。
|
||||
"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
actor_id=actor_id,
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要;
|
||||
文件解析阶段额外汇总 summary.issues(解析复核 / RSV / 库存源门禁 + parse warnings)。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +15,8 @@ from typing import Any
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_COMPLETED,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_EXPORT_READY,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
@@ -47,6 +50,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
inventory_source_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
)
|
||||
@@ -90,6 +94,38 @@ _BLOCKED_CHECKPOINTS = {
|
||||
CP_UPLOAD_REQ,
|
||||
CP_UPLOAD_FAILED,
|
||||
CP_UPLOAD_RESULT_UNKNOWN,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
}
|
||||
|
||||
_REVIEW_ENTRY_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
}
|
||||
|
||||
_NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = {
|
||||
CP_INVENTORY_PENDING: "ensure_inventory",
|
||||
CP_ORDER_FREEZE: "freeze_order",
|
||||
CP_READY_MATCH: "match_inventory",
|
||||
CP_READY_EXPORT: "generate_excel",
|
||||
}
|
||||
|
||||
_PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"),
|
||||
CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"),
|
||||
CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"),
|
||||
CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"),
|
||||
CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源尚未唯一确定"),
|
||||
CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"),
|
||||
RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"),
|
||||
CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
|
||||
CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
|
||||
CP_WAITING_UPLOAD: ("waiting_upload", "等待货代上传结果"),
|
||||
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
}
|
||||
|
||||
|
||||
@@ -276,20 +312,67 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
|
||||
return issues
|
||||
|
||||
|
||||
def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, Any]:
|
||||
"""输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。"""
|
||||
def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""
|
||||
解析当前操作应进入的工作台类型。
|
||||
|
||||
Returns:
|
||||
review_workbench | task_workbench | none
|
||||
"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "none"
|
||||
if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS:
|
||||
return "review_workbench"
|
||||
if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}:
|
||||
return "task_workbench"
|
||||
if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in {
|
||||
CP_ORDER_FREEZE,
|
||||
CP_READY_MATCH,
|
||||
CP_READY_EXPORT,
|
||||
CP_INVENTORY_PENDING,
|
||||
}:
|
||||
# 自动链可继续,但仍允许工作台手动兜底
|
||||
return "task_workbench"
|
||||
return "none"
|
||||
|
||||
|
||||
def _current_todo_label(checkpoint: str | None, action_buttons: list[dict[str, str]]) -> str | None:
|
||||
"""从当前动作按钮推导「当前待办」文案;无人工动作时返回 None。"""
|
||||
if not action_buttons:
|
||||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
return pause[1] if pause else None
|
||||
primary = next((b for b in action_buttons if b.get("variant") == "primary"), action_buttons[0])
|
||||
label = str(primary.get("label") or "").strip()
|
||||
return label or None
|
||||
|
||||
|
||||
def _build_task_summary(
|
||||
task: ShippingTask,
|
||||
checkpoint: str | None,
|
||||
*,
|
||||
checkpoint_kind: CheckpointKind,
|
||||
action_buttons: list[dict[str, str]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
|
||||
|
||||
核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、
|
||||
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions。
|
||||
"""
|
||||
title = user_facing_task_stage(task)
|
||||
message_by_checkpoint: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
|
||||
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
|
||||
CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。",
|
||||
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
|
||||
CP_ORDER_FREEZE: "订单已复核,冻结订单后才能进入库存履约。",
|
||||
CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。",
|
||||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||||
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
|
||||
CP_EXPORT_READY: "发货文件已生成,可以下载或确认上传。",
|
||||
CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
|
||||
CP_EXPORT_READY: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_EXPORT_GENERATED: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_WAITING_UPLOAD: "系统正在等待货代上传结果。",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,需要重试或手工确认。",
|
||||
CP_REJECTED: "任务已驳回,无需继续处理。",
|
||||
@@ -297,11 +380,34 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
|
||||
CP_COMPLETED: "任务已关闭。",
|
||||
}
|
||||
issues = _collect_parse_stage_issues(task, checkpoint)
|
||||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
pause_reason_code = pause[0] if pause else (task.pending_human_reason or None)
|
||||
pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None)
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE:
|
||||
pause_reason = None
|
||||
pause_reason_code = None
|
||||
allowed_actions = [str(btn.get("id")) for btn in action_buttons if btn.get("id")]
|
||||
event_at = None
|
||||
if task.updated_at is not None:
|
||||
event_at = task.updated_at.isoformat()
|
||||
return {
|
||||
"title": title,
|
||||
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"issues": issues,
|
||||
"stage": title,
|
||||
"checkpoint_kind": str(checkpoint_kind),
|
||||
"current_todo": _current_todo_label(checkpoint, action_buttons),
|
||||
"pause_reason": pause_reason,
|
||||
"pause_reason_code": pause_reason_code,
|
||||
"next_auto_step": (
|
||||
_NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE
|
||||
else None
|
||||
),
|
||||
"event_at": event_at,
|
||||
"entry_surface": _entry_surface_for(checkpoint, checkpoint_kind),
|
||||
"allowed_actions": allowed_actions,
|
||||
}
|
||||
|
||||
|
||||
@@ -309,8 +415,8 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
构建单票任务 UI State。
|
||||
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/action_buttons/step,避免 Chat、顶部步骤条、
|
||||
右侧工作台分别推导状态导致不一致。
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
|
||||
禁止 Chat、通知卡与任务中心分别推导状态。
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = _action_buttons_for_task(task)
|
||||
@@ -321,13 +427,19 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
"task_no": task.task_no,
|
||||
"batch_no": task.batch.batch_no if task.batch is not None else None,
|
||||
"checkpoint": ui.checkpoint,
|
||||
"checkpoint_kind": str(ui.checkpoint_kind),
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"match_status": task.match_status,
|
||||
"current_step": current_step,
|
||||
"steps": steps,
|
||||
"summary": _build_task_summary(task, ui.checkpoint),
|
||||
"summary": _build_task_summary(
|
||||
task,
|
||||
ui.checkpoint,
|
||||
checkpoint_kind=ui.checkpoint_kind,
|
||||
action_buttons=action_buttons,
|
||||
),
|
||||
"action_buttons": action_buttons,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
@@ -335,9 +447,10 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
|
||||
"""
|
||||
构建批次级 UI State。
|
||||
构建批次级会话上传集合摘要(非履约写操作面)。
|
||||
|
||||
核心逻辑:批次摘要、焦点任务、任务卡片均包含同源 task ui_state,供右侧工作台统一消费。
|
||||
核心逻辑:批次仅聚合各 PDF/Task 的同源 ui_state,供会话右侧「本次上传」摘要消费;
|
||||
履约写操作一律进入任务处理工作台。
|
||||
"""
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
focus_task_no = str(batch.current_focus_task_no or "").strip()
|
||||
@@ -353,6 +466,7 @@ def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
|
||||
]
|
||||
return {
|
||||
**serialize_batch_summary(batch),
|
||||
"role": "upload_session_summary",
|
||||
"process_summary": batch.process_summary_json or compute_batch_process_summary(tasks),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
"focus_task_ui_state": build_task_ui_state(focus_task) if focus_task else None,
|
||||
|
||||
Reference in new issue
Block a user