Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	backend/app/api/__init__.py
#	backend/app/jobs/types.py
#	backend/app/models/__init__.py
#	backend/app/services/schedule/job_registry.py
#	docs/features/README.md
#	docs/funclist.md
#	docs/tec.md
#	frontend/src/locales/zh-CN/admin.json
This commit is contained in:
hugo committed 2026-09-07 10:15:13 +08:00
commit dac31e48bd
691 files changed
+53341 -14863

No files matched your search

@@ -23,7 +23,7 @@ from app.models import (
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingOrderTask,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
@@ -62,10 +62,19 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
'shipping_notices': (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == customer.id,
)
.distinct()
.count()
),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
@@ -25,6 +25,8 @@ from app.models import (
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
ShippingOrderTask,
ShippingCustomerShadowResolution,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -144,7 +146,16 @@ def serialize_customer(
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
'notice_count': notice_count if notice_count is not None else (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == record.id,
)
.distinct()
.count()
),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
@@ -174,8 +185,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
items、total、page、page_size、pages。
"""
notice_counts = (
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.group_by(ShippingNotice.customer_id)
db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id)
.filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None))
.group_by(ShippingCustomerShadowResolution.confirmed_customer_id)
.subquery()
)
identifier_counts = (
@@ -19,6 +19,7 @@ from app.models import (
ShippingOrderField,
ShippingInventoryParsingProfile,
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
ShippingExcelTemplate,
ShippingInventorySourceParsingBindingAudit,
ShippingReceiptReportConfig,
@@ -497,7 +498,11 @@ def delete_source(source_id: int) -> None:
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter(
ShippingNoticeLineInventoryMatch.inventory_source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
@@ -12,4 +12,5 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -129,3 +129,35 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
- TransferRun
- TransferPrecheck
- TransferInvoiceItem
required_fields: []
default_capabilities:
task_progress: true
human_confirm: true
forced_capabilities:
human_confirm: true
progress_contract:
enabled: true
data_source:
type: domain_state
domain: in_transit_transfer
update:
transport: sse
event: transfer_ui_state
binding:
type: conversation_context
keys:
- run_no
- precheck_id
requires_schedule_task: false
presentation:
layout: card
visualization: stepper
handler_config_schema: {}
@@ -30,10 +30,12 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
_handlers_loaded = True
@@ -0,0 +1,34 @@
"""
用途:在途仓自动调拨 Hybrid Handler。
依赖:agent_registry.handlers.base/registry。
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute)
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
Dify Chatflow 生命周期。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('in_transit_transfer')
class InTransitTransferHandler(AgentHandler):
"""
在途仓自动调拨业务 Handler。
核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
+ Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""构造 transfer_ui_state SSE 事件(预留;进度由卡片消息 + Run API 提供)。"""
return None
@@ -89,10 +89,10 @@ class ShippingNoticeHandler(AgentHandler):
if str(event.get('event') or '') != 'shipping_ui_state':
return None
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
checkpoint = ui_state.get('checkpoint')
return json.dumps({
'task_no': event.get('task_no'),
'checkpoint': checkpoint,
'position': ui_state.get('position'),
'user_mode': ui_state.get('user_mode'),
'updated_at': ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
@@ -17,6 +17,7 @@ from app.services.chat.turn_context import TurnContext
# action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。
ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = {
"shipping.": ("shipping_notice",),
"transfer.": ("in_transit_transfer",),
}
@@ -79,5 +80,7 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
from app.services.in_transit_transfer import chat_actions as _transfer_actions # noqa: F401
_ = _shipping_extended
_ = _transfer_actions
+5 -4
View File
@@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes(
expires_at=expires_at,
)
# [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
# [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。
# 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session
# 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。
try:
with db.session.begin_nested():
db.session.add(asset)
db.session.flush()
db.session.add(asset)
db.session.flush()
except IntegrityError:
raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
if raced is not None:
@@ -0,0 +1,8 @@
"""backend/app/services/in_transit_transfer/__init__.py
用途:在途仓自动调拨 Agent 一期独立领域模块入口。
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
Phase 1 起扩展 file_preparation / precheck_service 等。
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -0,0 +1,168 @@
"""在途调拨 MinIO 归档与 Hash 校验。
用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库;
归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。
依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。
逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。
凭据只来自环境/配置,绝不写入归档内容或索引。
"""
from __future__ import annotations
import hashlib
import io
import uuid
from datetime import datetime
from typing import Any, Protocol
from app import db
from app.core.errors import AppError
from app.models import TransferArchive
from app.services.in_transit_transfer.audit import build_transfer_audit_event
ARCHIVE_STORAGE_PROVIDER = "minio"
DEFAULT_ARCHIVE_BUCKET = "hxops-transfer"
class ObjectStore(Protocol):
"""对象存储协议(MinIO 或测试替身)。"""
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象,返回对象键。"""
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
class MinioObjectStore:
"""默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。"""
def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None:
from flask import current_app
self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket)
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip()
secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip()
secure = bool(current_app.config.get("MINIO_SECURE", False))
if not endpoint:
raise AppError(
code="TRANSFER.ARCHIVE_NOT_CONFIGURED",
message="MinIO endpoint not configured",
http_status=503,
)
from minio import Minio
self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure)
def _ensure_bucket(self) -> None:
"""确保 bucket 存在(幂等)。"""
if not self.client.bucket_exists(self.bucket):
self.client.make_bucket(self.bucket)
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象并返回键。"""
self._ensure_bucket()
self.client.put_object(
bucket_name=bucket or self.bucket,
object_name=key,
data=io.BytesIO(data),
length=len(data),
content_type=content_type,
)
return key
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key)
def _safe_filename(name: str) -> str:
"""清洗文件名片段。"""
return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive"
def archive_snapshot(
*,
object_type: str,
object_id: str,
data: bytes,
original_filename: str,
content_type: str,
object_store: ObjectStore,
bucket: str = DEFAULT_ARCHIVE_BUCKET,
request_id: str | None = None,
) -> TransferArchive:
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
content_type: MIME。
object_store: 对象存储替身。
bucket: 目标 bucket。
Returns:
TransferArchive 索引记录。
"""
digest = hashlib.sha256(data).hexdigest()
key = (
f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/"
f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}"
)
object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type)
archive = TransferArchive(
archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}",
object_type=object_type,
object_id=object_id,
storage_provider=ARCHIVE_STORAGE_PROVIDER,
storage_bucket=bucket,
storage_key=key,
original_filename=original_filename,
content_type=content_type,
file_size=len(data),
sha256=digest,
)
db.session.add(archive)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ARCHIVED",
aggregate_type=object_type,
aggregate_id=object_id,
actor_type="worker",
request_id=request_id,
result="success",
after={"storage_key": key, "sha256": digest, "file_size": len(data)},
))
db.session.commit()
return archive
def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool:
"""复核归档 Hash(下载对象重新计算)。
Args:
archive: TransferArchive 索引。
object_store: 对象存储替身。
Returns:
True 一致;False 损坏/篡改。
"""
data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
return hashlib.sha256(data).hexdigest() == archive.sha256
def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes:
"""恢复归档对象字节。"""
return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
@@ -0,0 +1,182 @@
"""在途调拨审计服务。
用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算
before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。
依赖:app.models.TransferAuditEvent、标准库 hashlib/json。
逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash;
event_hash 由事件自身稳定字段复算,不依赖对象内部状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Mapping
import hashlib
import json
from app.models import TransferAuditEvent
# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。
AUDIT_FORBIDDEN_KEY_FRAGMENTS = (
"password", "secret", "token", "ciphertext", "credential",
"api_key", "apikey", "webhook", "authorization", "auth",
)
def is_forbidden_audit_key(key: str) -> bool:
"""判断键名是否命中敏感片段(大小写不敏感)。"""
lowered = str(key or "").lower()
return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS)
def sanitize_snapshot(value: Any) -> Any:
"""递归剔除敏感键,返回可安全持久化的快照副本。
Args:
value: 原始快照(dict/list/标量)。
Returns:
脱敏后的副本。
"""
if isinstance(value, dict):
return {
str(key): sanitize_snapshot(item)
for key, item in value.items()
if not is_forbidden_audit_key(str(key))
}
if isinstance(value, (list, tuple)):
return [sanitize_snapshot(item) for item in value]
return value
def canonical_hash(value: Any) -> str:
"""对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。
Args:
value: 任意 JSON 可序列化值。
Returns:
64 位十六进制 Hash。
"""
payload = json.dumps(
sanitize_snapshot(value),
ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str,
)
return hashlib.sha256(payload.encode("ascii")).hexdigest()
def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]:
"""计算前后快照顶层差异。
Args:
before: 变更前快照。
after: 变更后快照。
Returns:
{"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。
"""
before_keys = set(before)
after_keys = set(after)
return {
"added": {key: after[key] for key in sorted(after_keys - before_keys)},
"removed": {key: before[key] for key in sorted(before_keys - after_keys)},
"changed": {
key: (before[key], after[key])
for key in sorted(before_keys & after_keys)
if before[key] != after[key]
},
}
def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
"""事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。"""
created = event.created_at or datetime.utcnow()
return {
"event_type": event.event_type,
"aggregate_type": event.aggregate_type,
"aggregate_id": event.aggregate_id,
"run_no": event.run_no,
"precheck_no": event.precheck_no,
"invoice_no": event.invoice_no,
"item_id": event.item_id,
"attempt_no": event.attempt_no,
"actor_type": event.actor_type,
"actor_id": event.actor_id,
"actor_role": event.actor_role,
"actor_display": event.actor_display,
"request_id": event.request_id,
"operation_id": event.operation_id,
"source": event.source,
"result": event.result,
"error_code": event.error_code,
"before_hash": event.before_hash,
"after_hash": event.after_hash,
"created_at": created.isoformat(),
}
def compute_event_hash(event: TransferAuditEvent) -> str:
"""由存储字段复算事件 Hash(Hash 校验作业的复算口径)。"""
return canonical_hash(_event_hash_inputs(event))
def build_transfer_audit_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
precheck_no: str | None = None,
invoice_no: str | None = None,
item_id: str | None = None,
attempt_no: str | None = None,
actor_type: str = "system",
actor_id: str | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
before: Any = None,
after: Any = None,
) -> TransferAuditEvent:
"""构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。
Args:
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。
actor_*: 操作者(user/worker/schedule/admin/rpa)。
request_id / operation_id: 关联上下文。
before / after: 前后快照(自动脱敏并计算 Hash)。
Returns:
TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。
"""
before_sanitized = sanitize_snapshot(before if before is not None else {})
after_sanitized = sanitize_snapshot(after if after is not None else {})
created_at = datetime.utcnow()
event = TransferAuditEvent(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=aggregate_id,
run_no=run_no,
precheck_no=precheck_no,
invoice_no=invoice_no,
item_id=item_id,
attempt_no=attempt_no,
actor_type=actor_type,
actor_id=actor_id,
actor_role=actor_role,
actor_display=actor_display,
request_id=request_id,
operation_id=operation_id,
source=source,
result=result,
error_code=error_code,
before_json=before_sanitized,
after_json=after_sanitized,
before_hash=canonical_hash(before_sanitized),
after_hash=canonical_hash(after_sanitized),
created_at=created_at,
)
event.event_hash = compute_event_hash(event)
return event
@@ -0,0 +1,71 @@
"""在途调拨自动排程编排(09:00 自动调拨)。
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from app import db
from app.services.in_transit_transfer.execution_service import execute_precheck
from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
@dataclass
class AutoTransferOutcome:
"""自动调拨阶段结果。"""
run_no: str | None = None
run_status: str | None = None
recovery: RecoveryOutcome = field(default_factory=RecoveryOutcome)
notification_status: str | None = None
errors: list[str] = field(default_factory=list)
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
Args:
business_date: 业务日期。
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
sender / recipients: 企微通知(None 则跳过通知)。
Returns:
AutoTransferOutcome。
"""
outcome = AutoTransferOutcome()
if recover_history:
try:
outcome.recovery = run_daily_recovery(business_date=business_date, deps=deps)
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"recovery_failed: {exc}")
try:
summary = create_precheck(
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
)
executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
outcome.run_no = executed.run_no
outcome.run_status = executed.status
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"auto_transfer_failed: {exc}")
if sender is not None and outcome.run_no:
try:
notice = notify_run_summary(run_no=outcome.run_no, sender=sender, recipients=recipients or [])
outcome.notification_status = notice.get("notification_status")
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"notification_failed: {exc}")
return outcome
@@ -0,0 +1,141 @@
"""在途调拨历史待处理池与老化分级。
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
依赖:models、status。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.status import TransferStatus
AGING_NORMAL = "normal"
AGING_WARN_3D = "warn_3d"
AGING_ESCALATE_5D = "escalate_5d"
AGING_CRITICAL_7D = "critical_7d"
AGING_UNKNOWN = "result_unknown"
AGING_CLOSED = "closed"
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
@dataclass(frozen=True)
class BacklogItemDTO:
"""待处理池单项。"""
item_id: int
source_code: str
invoice_no: str
material_no: str
status: str
reason: str
age_days: int
aging_level: str
last_attempt_at: Optional[str] = None
@dataclass
class BacklogSummaryDTO:
"""待处理池汇总(含老化分级计数)。"""
recoverable_count: int = 0
closed_count: int = 0
unknown_count: int = 0
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
"""按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。"""
if age_days >= critical:
return AGING_CRITICAL_7D
if age_days >= escalate:
return AGING_ESCALATE_5D
if age_days >= warn:
return AGING_WARN_3D
return AGING_NORMAL
def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]:
"""返回明细最近一次 Attempt(无则 None)。"""
return TransferAttempt.query.filter_by(item_id=item.id).order_by(
TransferAttempt.created_at.desc(),
).first()
def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
"""按最近 Attempt 或明细更新时间计算积压天数。"""
latest = _latest_attempt(item)
base = latest.created_at if latest is not None else item.updated_at
return max(0, int((now - base).total_seconds() // 86400))
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
Returns:
BacklogItemDTO 列表。
"""
current = now or datetime.utcnow()
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
]),
)
if source_code:
query = query.filter_by(source_code=source_code)
output: list[BacklogItemDTO] = []
for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all():
age = _item_age_days(item, current)
latest = _latest_attempt(item)
if item.status == TransferStatus.RESULT_UNKNOWN.value:
level = AGING_UNKNOWN
elif item.status == TransferStatus.MANUALLY_CLOSED.value:
level = AGING_CLOSED
else:
level = aging_level_for(age)
output.append(BacklogItemDTO(
item_id=item.id,
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
status=item.status,
reason=item.result_message or item.result_code or "",
age_days=age,
aging_level=level,
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
))
return output
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数与老化分级。"""
items = list_backlog(now=now)
summary = BacklogSummaryDTO()
for item in items:
if item.status == TransferStatus.MANUALLY_CLOSED.value:
summary.closed_count += 1
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
summary.unknown_count += 1
else:
summary.recoverable_count += 1
if item.aging_level == AGING_WARN_3D:
summary.warn_3d += 1
elif item.aging_level == AGING_ESCALATE_5D:
summary.escalate_5d += 1
elif item.aging_level == AGING_CRITICAL_7D:
summary.critical_7d += 1
return summary
@@ -0,0 +1,65 @@
"""在途调拨请求停止(取消剩余任务)。
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
原因必填;取消前后状态进入审计。
依赖:models、status、core.errors。
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""请求停止剩余任务。
Args:
run_no: Run 编号。
reason: 取消原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"run_no": ..., "cancelled_count": ...}。
Raises:
ValidationError: 原因为空。
NotFoundError: Run 不存在。
ConflictError: Run 已终态不可取消。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("reason is required")
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if run.status in {
status_machine.TransferRunStatus.SUCCESS.value,
status_machine.TransferRunStatus.FAILED.value,
status_machine.TransferRunStatus.CANCELLED.value,
}:
raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE")
cancelled = 0
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
cancelled += 1
active = db.session.query(TransferInvoiceItem).filter(
TransferInvoiceItem.run_id == run.id,
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.READY_TO_EXECUTE.value,
]),
).count()
if active == 0:
run.status = status_machine.TransferRunStatus.CANCELLED.value
run.completed_at = run.completed_at or datetime.utcnow()
db.session.commit()
return {"run_no": run.run_no, "cancelled_count": cancelled}
@@ -0,0 +1,100 @@
"""在途调拨 Chat Action Handler。
用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件
(message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。
依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。
逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。
"""
from __future__ import annotations
from typing import Any, Iterator
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.serializers import serialize_precheck_detail
ACTION_TRANSFER_PRECHECK = "transfer.precheck"
ACTION_TRANSFER_EXECUTE = "transfer.execute"
def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEvent:
"""构造结构化消息完成事件。"""
return TurnEvent(event="message.completed", data={
"content": content,
"message_type": message_type,
"payload": payload,
})
@register_action_handler
class TransferPrecheckAction:
"""预检 Action:创建(或恢复)预检并输出预检卡。"""
action_type = ACTION_TRANSFER_PRECHECK
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行只读预检并输出 transfer-precheck 卡片。
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
只读,不写 ERP。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
business_date = str(payload.get("business_date") or business_date_now())
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
)
detail = restore_precheck(summary.precheck_id)
yield _message(
content="调拨预检完成",
message_type="transfer-precheck",
payload={"kind": "precheck", **serialize_precheck_detail(detail)},
)
@register_action_handler
class TransferExecuteAction:
"""执行 Action:确认选择范围并直接生成执行 Run,输出结果卡。"""
action_type = ACTION_TRANSFER_EXECUTE
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 ERP 原子写入。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
invoice_nos = payload.get("invoice_nos")
invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
run_view = get_run(outcome.run_no)
yield _message(
content=f"调拨执行完成:{outcome.run_no}",
message_type="transfer-result",
payload={
"kind": "result",
"run_no": outcome.run_no,
"status": outcome.status,
"run": {
"run_no": outcome.run_no,
"status": outcome.status,
"result": run_view["result"],
},
},
)
@@ -0,0 +1,25 @@
"""在途调拨并发参数与单写者约束。
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
"""同预检最多一个执行 Run。
Args:
run_count: 已存在的执行 Run 数。
Raises:
AssertionError: run_count > 1(一期硬约束)。
"""
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
@@ -0,0 +1,200 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Iterable
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN"
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED = "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED"
TRANSFER_CONFIG_PUBLISH_BLOCKED = "TRANSFER_CONFIG_PUBLISH_BLOCKED"
TRANSFER_SECRET_NOT_EXPOSED = "TRANSFER_SECRET_NOT_EXPOSED"
TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_PERMISSION_DENIED,
TRANSFER_RECEIPT_NOT_MATURED,
TRANSFER_FILE_NOT_READY,
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_ERP_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
TRANSFER_RESULT_UNKNOWN,
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
TRANSFER_CONFIG_PUBLISH_BLOCKED,
TRANSFER_SECRET_NOT_EXPOSED,
TRANSFER_NOTIFICATION_FAILED,
})
def require_known_error_code(code: str) -> None:
"""校验错误码属于一期冻结集合。
Args:
code: 错误码。
Raises:
ValueError: 未知错误码。
"""
if str(code or "").strip() not in KNOWN_TRANSFER_ERROR_CODES:
raise ValueError(f"unknown transfer error code: {code}")
# ---- 预检 DTO -------------------------------------------------------------
@dataclass(frozen=True)
class PrecheckCountsDTO:
"""预检计数。"""
file_invoice_count: int = 0
not_matured_count: int = 0
prechecked_count: int = 0
executable_count: int = 0
blocked_count: int = 0
@dataclass(frozen=True)
class RawLineRefDTO:
"""原始文件行追溯(Sheet/行号/文件版本)。"""
sheet: str
row_no: int
file_version: str
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
source_code: str
material_no: str
material_name: str
specification: str
invoice_no: str
from_warehouse: str
from_quantity: Decimal | None
to_warehouse: str
to_quantity: Decimal
result: str
receipt_date: str | None = None
reason: str = ""
erp_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class PrecheckSummaryDTO:
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
precheck_id: str
status: str
business_date: str
eligible_receipt_date_to: str
expires_at: str
counts: PrecheckCountsDTO
estimated_transfer_quantity: str
estimated_erp_write_count: int
precheck_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@dataclass(frozen=True)
class ErpDocumentLineDTO:
"""ERP 单据内物料明细。"""
material_no: str
material_name: str
specification: str
invoice_no: str
quantity: Decimal
@dataclass(frozen=True)
class ErpDocumentDTO:
"""按 ERP 单号聚合的结果项。"""
document_no: str
from_warehouse: str
to_warehouse: str
material_count: int
total_quantity: Decimal
posting_status: str
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 ERP 单据的异常项(单独展示)。"""
source_code: str
invoice_no: str
material_no: str
reason: str
facts: str
@dataclass(frozen=True)
class RunResultDTO:
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
run_no: str
status: str
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
"""按 ERP 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 erp_document_no 与 result)。
Returns:
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
for item in items:
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.erp_document_no, []).append(item)
documents: list[ErpDocumentDTO] = []
for document_no in sorted(grouped):
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
lines = tuple(
ErpDocumentLineDTO(
material_no=row.material_no,
material_name=row.material_name,
specification=row.specification,
invoice_no=row.invoice_no,
quantity=row.to_quantity,
)
for row in rows
)
documents.append(ErpDocumentDTO(
document_no=document_no,
from_warehouse=rows[0].from_warehouse,
to_warehouse=rows[0].to_warehouse,
material_count=len(rows),
total_quantity=sum((row.to_quantity for row in rows), Decimal("0")),
posting_status="posted",
lines=lines,
))
return tuple(documents)
@@ -0,0 +1,81 @@
"""在途调拨业务日期与成熟度策略。
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
昨天及更早可预检,未来日期阻断)。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
避免各服务各自计算导致口径漂移。
"""
from __future__ import annotations
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 成熟度结果
MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
"""
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
def business_date_now(moment: datetime | None = None) -> date:
"""计算 Asia/Shanghai 业务日期。
Args:
moment: 可选时刻;带时区则转换到上海,naive 按 UTC 兼容处理(与
shipping_notice.business_numbering_service 口径一致)。
Returns:
Asia/Shanghai 口径的日期。
"""
if moment is None:
return datetime.now(SHANGHAI_TZ).date()
if moment.tzinfo is None:
moment = moment.replace(tzinfo=ZoneInfo("UTC"))
return moment.astimezone(SHANGHAI_TZ).date()
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
Returns:
'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或
'future'(receipt_date > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
if receipt == business:
return MATURITY_NOT_MATURED
if receipt > business:
return MATURITY_FUTURE
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str) -> date:
"""返回可进入预检的收料截止日期(业务日期 T - 1 天)。
Args:
business_date: 当前业务日期。
Returns:
T - 1 天。
"""
return parse_date(business_date) - timedelta(days=1)
@@ -0,0 +1,118 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
RouteResolver,
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RouteNotResolvedError(source_code=source_code)
mapping = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).first()
if mapping is None or not mapping.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
to_warehouse=mapping.external_warehouse_code,
)
def _build_erp_adapter() -> CapabilityErpAdapter:
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
"""
return CapabilityErpAdapter()
_override: TransferDeps | None = None
def set_transfer_dependencies(deps: TransferDeps | None) -> None:
"""测试注入点:设置/清除 TransferDeps 覆盖。"""
global _override # noqa: PLW0603
_override = deps
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
erp=_build_erp_adapter(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
@@ -0,0 +1,295 @@
"""在途调拨 ERP 访问统一边界(Adapter)。
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
verify_duplicate / 结果分类。
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Protocol
from app.core.errors import AppError
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
@dataclass(frozen=True)
class InventoryQuery:
"""ERP 账面库存查询结果。"""
found: bool
quantity: Decimal | None = None
document_no: str | None = None
class ErpNotFrozenError(AppError):
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "ERP contract not frozen"):
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ErpQueryTimeoutError(AppError):
"""ERP 查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "ERP query timeout"):
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ErpResultUnknownError(AppError):
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ErpWriteTimeoutError(TimeoutError):
"""ERP 写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""ERP 原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
class ErpTransport(Protocol):
"""ERP 传输层协议(SOAP 或测试替身)。"""
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""按 Invoice 查询账面库存。"""
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""原子建单/审核/过账(Phase 2)。"""
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""核实重复 Invoice 原单是否已审核过账。"""
class SoapErpTransport:
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
Args:
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
"""
def __init__(self, config: dict[str, Any] | None = None) -> None:
self._config = config or {}
def _require_frozen(self, operation: str) -> None:
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
if not str(self._config.get("endpoint") or "").strip():
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
self._require_frozen("query_inventory")
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
self._require_frozen("create_transfer")
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
self._require_frozen("verify_duplicate")
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
class ErpAdapter:
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
self._transport = transport
self._default_org = default_org
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询 ERP 账面库存并分类结果。
Args:
operation_id / run_no / attempt_no / invoice_no / erp_org /
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
Returns:
InventoryQuery。
Raises:
ErpQueryTimeoutError: 查询超时(可重试)。
ErpNotFrozenError: ERP 契约未冻结。
"""
request = {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
try:
response = self._transport.query_inventory(**request)
except ErpNotFrozenError:
raise
except TimeoutError as exc:
raise ErpQueryTimeoutError() from exc
response = response if isinstance(response, dict) else {}
if response.get("found"):
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
return InventoryQuery(found=False)
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
"""组装携带全部强制追踪字段的 ERP 请求。"""
return {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""ERP 原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ErpNotFrozenError: ERP 契约未冻结。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.create_transfer(**request)
except ErpNotFrozenError:
raise
except ErpWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.verify_duplicate(**request)
except ErpNotFrozenError:
raise
except (TimeoutError, ErpWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按 ERP 写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
@@ -0,0 +1,125 @@
"""在途调拨七 Sheet 异常 Excel 导出。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
依赖:openpyxl、models、execution_service。
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
Secret 明文永不写入单元格(仅输出业务字段)。
"""
from __future__ import annotations
import io
from typing import Any
from openpyxl import Workbook
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.core.errors import NotFoundError
EXCEL_SHEET_NAMES = [
"执行汇总",
"数量不一致",
"ERP无库存",
"ERP技术失败",
"ERP结果未知",
"通知失败",
"原始文件追溯",
]
_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def build_exceptions_workbook(run_no: str) -> bytes:
"""生成 Run 的七 Sheet 异常 Excel 字节。
Args:
run_no: Run 编号。
Returns:
xlsx 字节。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).order_by(
TransferInvoiceItem.invoice_no,
).all()
workbook = Workbook()
workbook.remove(workbook.active)
_sheet_summary(workbook, run, items)
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_unknown(workbook, items)
_sheet_notification(workbook, run)
_sheet_raw_trace(workbook, items)
buffer = io.BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""执行汇总 Sheet。"""
sheet = workbook.create_sheet("执行汇总")
sheet.append(["Run", run.run_no])
sheet.append(["Run 状态", run.status])
sheet.append(["通知状态", run.notification_status])
sheet.append([])
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.result_code or item.status, item.erp_document_no or "",
])
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.erp_quantity or "",
item.result_message or item.result_code or item.status,
])
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("ERP结果未知")
sheet.append(["Invoice", "来源", "料号", "说明"])
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
for item in items:
if item.status == "result_unknown" or (item.result_code or "") == "result_unknown":
sheet.append([item.invoice_no, item.source_code, item.material_no, item.result_message or ""])
def _sheet_notification(workbook: Workbook, run: TransferRun) -> None:
"""通知失败 Sheet。"""
sheet = workbook.create_sheet("通知失败")
sheet.append(["Run", "通知状态", "错误码"])
if run.notification_status == "failed":
sheet.append([run.run_no, run.notification_status, run.notification_error_code or ""])
def _sheet_raw_trace(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""原始文件追溯 Sheet(决策 11:Sheet/行号/文件版本)。"""
sheet = workbook.create_sheet("原始文件追溯")
sheet.append(["Invoice", "Sheet", "原始行号", "文件版本", "来源"])
for item in items:
for line in (item.raw_lines_json or []):
sheet.append([
item.invoice_no,
str(line.get("sheet") or ""),
int(line.get("row_no") or 0),
str(line.get("file_version") or ""),
item.source_code,
])
@@ -0,0 +1,399 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ErpDocumentDTO,
PrecheckInvoiceItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_erp_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
RESULT_EXECUTABLE,
RouteNotResolvedError,
TransferDeps,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
PRECHECK_EXPIRED_RESULT = "precheck_expired"
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
@dataclass(frozen=True)
class ExecuteOutcome:
"""一次执行的结果摘要。"""
run_no: str
status: str
result: RunResultDTO
def _item_result_of(item: TransferInvoiceItem) -> str:
"""从持久化状态还原明细结果值(与预检快照口径一致)。"""
if item.result_code:
return item.result_code
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
return RESULT_EXECUTABLE
return item.status
def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"""由存储明细复算预检 Hash(写前快照校验口径)。"""
from app.services.in_transit_transfer.audit import canonical_hash
counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {}
items = [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"erp_quantity": item.erp_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
]
snapshot = {
"scope": sorted(precheck.scope_json.get("source_codes") or []),
"business_date": precheck.business_date,
"file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {},
"counts": {
key: int(counts.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
},
"items": items,
}
return f"sha256:{canonical_hash(snapshot)}"
def _expire(precheck: TransferPrecheck) -> None:
"""将预检置为过期(fail-closed 落位)。"""
precheck.status = "expired"
db.session.flush()
def execute_precheck(
*,
precheck_id: str,
deps: TransferDeps,
selected_invoice_nos: list[str] | None = None,
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""执行一次已确认的预检(手工或自动触发共用)。
Args:
precheck_id: 预检编号。
deps: 注入依赖。
selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。
actor_id / request_id: 审计上下文。
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
ConflictError: 重复执行。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip(),
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
if precheck.confirmed_at is not None:
from app.core.errors import ConflictError
raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED")
if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value:
raise AppError(
code=TRANSFER_CONFIRMATION_REQUIRED,
message="precheck is not confirmed for execution",
http_status=400,
)
if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow():
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired",
http_status=409,
)
if recompute_precheck_hash(precheck) != precheck.precheck_hash:
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED,
message="precheck snapshot changed since confirmation",
http_status=409,
)
executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
if selected_invoice_nos is not None:
selected_set = {str(item).strip() for item in selected_invoice_nos}
available = {item.invoice_no for item in executable}
invalid = selected_set - available
if invalid:
raise ValidationError(
f"invoices not executable: {sorted(invalid)}",
code="TRANSFER.SELECTION_INVALID",
)
selected = [item for item in executable if item.invoice_no in selected_set]
else:
selected = list(executable)
if not selected:
raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED)
run = create_execution_run(
precheck, deps=deps, actor_id=actor_id,
selected_invoice_nos={item.invoice_no for item in selected},
)
for item in selected:
try:
_write_item(item, deps=deps, run_no=run.run_no, request_id=request_id)
except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = ITEM_EXECUTION_ERROR_RESULT
item.result_message = str(exc)
db.session.flush()
db.session.flush()
run_items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
finalize_run(run, run_items)
db.session.commit()
return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run))
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
try:
query = deps.erp.query_inventory(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
except RouteNotResolvedError:
raise
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
return
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
status="running", operation_id=operation_id,
request_snapshot_json={
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
result = deps.erp.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
before_status = item.status
_apply_write_result(item, attempt, result)
_audit_item_write(item, run_no, request_id, operation_id, before_status)
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
"""写前复查失败:fail-closed,不写 ERP。"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result
item.result_message = message
db.session.flush()
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
attempt.response_summary_json = {
"status": result.status,
"document_no": result.document_no,
"verified_posted": result.verified_posted,
"error_code": result.error_code,
}
if result.status == "success":
item.status = status_machine.TransferStatus.SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "duplicate_success":
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "result_unknown":
# 终态:禁止自动重试,等待人工核实 SOP。
item.status = status_machine.TransferStatus.RESULT_UNKNOWN.value
item.result_code = "result_unknown"
attempt.status = "result_unknown"
else:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result.status
item.result_message = result.error_message or result.error_code or ""
attempt.status = "failed"
attempt.error_code = result.error_code
attempt.completed_at = datetime.utcnow()
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_ITEM_EXECUTED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=run_no,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status in {"success", "duplicate_success"} else "failure",
before={"status": before_status},
after={"status": item.status, "erp_document_no": item.erp_document_no},
)
db.session.add(event)
def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = None) -> str:
"""单 Invoice 执行入口(Item Job Handler 使用)。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
Returns:
写入后的 item 状态。
Raises:
NotFoundError / RuntimeError: item 不存在或未关联执行 Run。
"""
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.run_id is None:
raise RuntimeError("item not linked to execution run")
run_no = item.run.run_no if item.run else "RUN-PENDING"
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
db.session.commit()
return item.status
def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
return {
"run_no": run.run_no,
"status": run.status,
"result": serialize_run_result(_build_run_result(run)),
}
def _build_run_result(run: TransferRun) -> RunResultDTO:
"""由 Run 明细构建结果投影。"""
item_dtos: list[PrecheckInvoiceItemDTO] = []
exceptions: list[TransferExceptionDTO] = []
for item in sorted(run.items, key=lambda row: row.invoice_no):
result = _item_result_of(item)
item_dtos.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=result,
reason=item.result_message or "",
erp_document_no=item.erp_document_no,
))
if result not in {"success", "duplicate_success"}:
exceptions.append(TransferExceptionDTO(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
status=run.status,
erp_documents=aggregate_erp_documents(item_dtos),
exceptions=tuple(exceptions),
)
def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
"""结果投影序列化(前端结果页 DTO)。"""
return {
"run_no": result.run_no,
"status": result.status,
"erp_documents": [
{
"document_no": document.document_no,
"from_warehouse": document.from_warehouse,
"to_warehouse": document.to_warehouse,
"material_count": document.material_count,
"total_quantity": str(document.total_quantity),
"posting_status": document.posting_status,
"lines": [
{
"material_no": line.material_no,
"material_name": line.material_name,
"specification": line.specification,
"invoice_no": line.invoice_no,
"quantity": str(line.quantity),
}
for line in document.lines
],
}
for document in result.erp_documents
],
"exceptions": [
{
"source_code": exc.source_code,
"invoice_no": exc.invoice_no,
"material_no": exc.material_no,
"reason": exc.reason,
"facts": exc.facts,
}
for exc in result.exceptions
],
}
@@ -0,0 +1,179 @@
"""在途调拨收料文件字段/结构校验。
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Any, Iterable, Mapping
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.date_policy import parse_date
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
@dataclass(frozen=True)
class ParsedReceiptRow:
"""单行已校验收料记录。"""
source_code: str
sheet: str
row_no: int
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
class ReceiptFileSchemaError(AppError):
"""收料文件结构/字段校验失败(整行阻断)。"""
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
super().__init__(
code=TRANSFER_FILE_SCHEMA_INVALID,
message=message,
http_status=422,
details={"rows": rows or []},
)
def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
"""累积式抛出首个行级错误(携带行号与原因)。"""
rows.append({"row_no": row_no, "reason": reason})
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 通用异动原始行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "doc_no",
"material_no": "material_code",
"receipt_quantity": "quantity",
"receipt_date": "movement_date",
},
)
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""校验并解析收料文件行。
Args:
source_code: 任务来源实例(用于校验行内来源身份一致性)。
rows: 原始文件行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "invoice_no",
"material_no": "material_no",
"receipt_quantity": "receipt_quantity",
"receipt_date": "receipt_date",
},
)
def _parse_rows(
*,
source_code: str,
rows: Iterable[Mapping[str, Any]],
projection: Mapping[str, str],
) -> list[ParsedReceiptRow]:
"""按字段名投影校验并解析原始行。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 原始文件行 dict。
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
invoice_key = str(projection.get("invoice_no") or "invoice_no")
material_key = str(projection.get("material_no") or "material_no")
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
date_key = str(projection.get("receipt_date") or "receipt_date")
errors: list[dict[str, Any]] = []
parsed: list[ParsedReceiptRow] = []
for raw in rows:
row = raw if isinstance(raw, Mapping) else {}
row_no = row.get("row_no")
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
continue
if not invoice_no:
_fail(errors, row_no=row_no, reason="missing_invoice_no")
continue
if not material_no:
_fail(errors, row_no=row_no, reason="missing_material_no")
continue
row_source = str(row.get("source_code") or "").strip()
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
try:
receipt_date = parse_date(receipt_date_raw)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
except QuantityValidationError as exc:
_fail(errors, row_no=row_no, reason=str(exc))
continue
parsed.append(ParsedReceiptRow(
source_code=str(source_code),
sheet=sheet,
row_no=int(row_no),
invoice_no=invoice_no,
material_no=material_no,
material_name=str(row.get("material_name") or "").strip(),
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
return parsed
@@ -0,0 +1,96 @@
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
任何触发失败 fail-closed 进入 failed,绝不误报 file_ready。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Protocol
STAGE_FILE_READY = "file_ready"
STAGE_WAITING_RPA = "waiting_rpa_callback"
STAGE_FAILED = "failed"
@dataclass(frozen=True)
class ReadyReceiptFile:
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
source_code: str
business_date: str
file_no: str
file_version: str
checksum: str
rows: tuple[dict[str, Any], ...] = ()
@dataclass(frozen=True)
class FilePreparationResult:
"""来源级文件准备结果。"""
stage: str
file: ReadyReceiptFile | None = None
error_code: str | None = None
error_message: str | None = None
class ReceiptFileRepository(Protocol):
"""收料 ready 文件仓库协议。"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
class RpaTrigger(Protocol):
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
def ensure_receipt_file_ready(
*,
source_code: str,
business_date: str,
repository: ReceiptFileRepository,
rpa_trigger: RpaTrigger,
active_source_job_key: str | None = None,
) -> FilePreparationResult:
"""确保来源当日 ready 文件可用。
Args:
source_code: 来源实例编码。
business_date: 业务日期(YYYY-MM-DD)。
repository: ready 文件仓库。
rpa_trigger: RPA 触发器。
active_source_job_key: 活动 Source Job 键;非空时绑定已有任务不重复触发。
Returns:
FilePreparationResult(file_ready / waiting_rpa_callback / failed)。
"""
ready = repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is not None:
return FilePreparationResult(stage=STAGE_FILE_READY, file=ready)
if active_source_job_key is not None:
# 已有活动抓取任务:绑定等待,不重复触发。
return FilePreparationResult(stage=STAGE_WAITING_RPA)
outcome = rpa_trigger.trigger(
source_code=source_code,
business_date=business_date,
reason="precheck_missing_ready_file",
)
outcome = outcome if isinstance(outcome, dict) else {}
if outcome.get("ok"):
return FilePreparationResult(stage=STAGE_WAITING_RPA)
return FilePreparationResult(
stage=STAGE_FAILED,
error_code=str(outcome.get("error_code") or "RPA_TRIGGER_FAILED"),
error_message=str(outcome.get("error_message") or "rpa trigger failed"),
)
@@ -0,0 +1,80 @@
"""services/in_transit_transfer/gateway_adapter.py
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
(query_inventory 是首个配置绑定消费者)。
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
class CapabilityErpAdapter:
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
Args:
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
"""
def __init__(self, gateway: Any | None = None) -> None:
self._gateway = gateway
def _gateway_or_default(self):
if self._gateway is not None:
return self._gateway
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询外部系统库存(经连接器框架)。
Args/Raises:
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
来源专属绑定待 P2/P3。
"""
result = self._gateway_or_default().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"invoice_no": invoice_no,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ErpQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
data = result.data or {}
found = bool(data.get("found"))
qty = data.get("quantity")
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
@@ -0,0 +1,91 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Iterable
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
@dataclass(frozen=True)
class AggregatedInvoice:
"""单 Invoice 汇总结果(含原始行追溯)。"""
source_code: str
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
class InvoiceConflictError(AppError):
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
super().__init__(
code=TRANSFER_INVOICE_CONFLICT,
message=message,
http_status=422,
details={"invoice_no": invoice_no, "conflict": conflict},
)
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
for row in group
)
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
))
return invoices
@@ -0,0 +1,66 @@
"""在途调拨人工关闭服务。
用途:将异常项标记为 manually_closed(原因必填、永久排除、历史保留)。
依赖:models、status、audit、contracts。
逻辑:result_unknown / success / duplicate_success / manually_closed 禁止关闭。
"""
from __future__ import annotations
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工关闭一个异常 Invoice。
Args:
item_id: TransferInvoiceItem.id。
reason: 关闭原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": "manually_closed"}。
Raises:
ValidationError: 原因缺失或状态不可关闭。
NotFoundError: item 不存在。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status in {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
}:
raise ValidationError(f"item status {item.status} is not closeable", code="TRANSFER.MANUAL_CLOSE_NOT_ALLOWED")
before_status = item.status
item.status = status_machine.TransferStatus.MANUALLY_CLOSED.value
item.result_code = "manually_closed"
item.result_message = reason_value
item.manually_closed_reason = reason_value
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_MANUALLY_CLOSED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
actor_type="user",
actor_id=str(actor_id) if actor_id is not None else None,
request_id=request_id,
result="success",
before={"status": before_status},
after={"status": item.status, "reason": reason_value},
))
db.session.commit()
return {"item_id": item.id, "status": item.status}
@@ -0,0 +1,56 @@
"""在途调拨运营指标。
用途:从数据库现状投影成功率、失败类型、待处理老化与通知失败等指标,
供运营看板与告警使用。
依赖:models、backlog_service。
逻辑:指标只读,不触发任何外部调用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.backlog_service import backlog_summary
from app.services.in_transit_transfer.status import TransferNotificationStatus
def collect_metrics(*, now: datetime | None = None) -> dict[str, Any]:
"""采集调拨域指标。
Args:
now: 判定时刻(老化计算用)。
Returns:
{"runs": {...}, "items": {...}, "backlog": {...}}。
"""
runs_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferRun.status).all():
runs_by_status[str(status)] = runs_by_status.get(str(status), 0) + 1
notification_failed_runs = TransferRun.query.filter_by(
notification_status=TransferNotificationStatus.FAILED.value,
).count()
items_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferInvoiceItem.status).all():
items_by_status[str(status)] = items_by_status.get(str(status), 0) + 1
backlog = backlog_summary(now=now)
return {
"runs": {
**runs_by_status,
"notification_failed_runs": notification_failed_runs,
},
"items": items_by_status,
"backlog": {
"recoverable": backlog.recoverable_count,
"closed": backlog.closed_count,
"unknown": backlog.unknown_count,
"aging": {
"warn_3d": backlog.warn_3d,
"escalate_5d": backlog.escalate_5d,
"critical_7d": backlog.critical_7d,
},
},
}
@@ -0,0 +1,75 @@
"""在途调拨通用异动/移动表领域字段契约。
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
依赖:标准库 dataclasses / enum。
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
class MovementFieldValueType(StrEnum):
"""领域字段值类型(校验与展示共用)。"""
TEXT = "text"
DECIMAL = "decimal"
DATE = "date"
@dataclass(frozen=True)
class MovementField:
"""单个定死异动字段契约。
Args:
code: 稳定字段名(运行时契约)。
label: 业务中文名。
value_type: 值类型(text / decimal / date)。
is_identity: 是否参与幂等/匹配键。
required: 是否必填(缺省阻断)。
"""
code: str
label: str
value_type: MovementFieldValueType
is_identity: bool = False
required: bool = False
# 定死的 10 个通用异动字段(领域契约,不配置化)。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
MovementField("in_out_flag", "进出库别", MovementFieldValueType.TEXT),
MovementField("material_code", "料号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("material_name", "品名", MovementFieldValueType.TEXT),
MovementField("warehouse_code", "仓库", MovementFieldValueType.TEXT),
MovementField("storage_code", "储位", MovementFieldValueType.TEXT),
MovementField("lot_no", "批号", MovementFieldValueType.TEXT),
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
)
def movement_match_key() -> str:
"""调拨幂等/汇总键:单号 doc_no。"""
return "doc_no"
def movement_quantity_field() -> str:
"""严格数量匹配字段:数量 quantity。"""
return "quantity"
def movement_identity_fields() -> set[str]:
"""参与幂等/匹配判定的字段集(doc_no / material_code / movement_date)。"""
return {field.code for field in MOVEMENT_FIELDS if field.is_identity}
def movement_field_codes() -> set[str]:
"""全部定死字段名集合。"""
return {field.code for field in MOVEMENT_FIELDS}
@@ -0,0 +1,125 @@
"""在途调拨真实异动(收料/出货)文件仓库。
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
def __init__(self) -> None:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
return None
data = self._storage.get_bytes(report.storage_key)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
)
return ReadyReceiptFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
rows=tuple(rows),
)
def _extract_movement_rows(
data: bytes,
*,
field_mapping: Mapping[str, str],
sheet_name: str | None = None,
header_row_index: int | None = None,
) -> list[dict[str, Any]]:
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
if sheet_name and sheet_name in wb.sheetnames:
ws = wb[sheet_name]
else:
ws = wb.active
raw_rows: list[list[Any]] = [list(row) for row in ws.iter_rows(values_only=True)]
finally:
wb.close()
if not raw_rows:
return []
header_idx: int | None = None
if header_row_index is not None:
idx = int(header_row_index) - 1
if 0 <= idx < len(raw_rows):
header_idx = idx
if header_idx is None:
header_idx = find_inventory_header_row_index(raw_rows)
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
return output
@@ -0,0 +1,84 @@
"""在途调拨企业微信汇总通知。
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
依赖:models、audit、typing.Protocol。
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
"""
from __future__ import annotations
from typing import Any, Protocol
from app import db
from app.core.errors import NotFoundError
from app.models import TransferRun
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.status import TransferNotificationStatus
class WeComSender(Protocol):
"""企业微信汇总通知协议(测试注入 FakeWeCom)。"""
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""发送一次汇总通知。"""
def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None,
excel_path: str | None = None) -> dict[str, Any]:
"""为 Run 发送一条汇总通知(幂等)。
Args:
run_no: Run 编号。
sender: 企微发送器。
recipients: 接收人列表(缺省空)。
excel_path: 异常 Excel 附件路径(可空)。
Returns:
{"run_no", "notification_status", "delivered"};空数据返回 skipped。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if not run.items:
# 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"}
if run.notification_status == TransferNotificationStatus.SUCCESS.value:
# 已成功投递:幂等跳过,保证每个 Run 恰好一条。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False}
summary = {
"run_no": run.run_no,
"status": run.status,
"business_date": run.business_date,
"counts": dict(run.counts_json or {}),
"result_summary": dict(run.result_summary_json or {}),
}
outcome = sender.send_summary(
run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path,
)
outcome = outcome if isinstance(outcome, dict) else {}
failed = str(outcome.get("status") or "success") != "success"
run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value
if failed:
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
run.notification_error_message = str(outcome.get("error_message") or "")
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_NOTIFICATION",
aggregate_type="transfer_run",
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type="worker",
result="failure" if failed else "success",
before={"status": run.status, "notification_status": "pending"},
after={"status": run.status, "notification_status": run.notification_status},
))
db.session.commit()
return {
"run_no": run.run_no,
"notification_status": run.notification_status,
"delivered": True,
}
@@ -0,0 +1,83 @@
"""在途调拨执行编排(Run 生命周期辅助)。
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
按明细终态收尾 Run(success / partial_failed)。
依赖:models、status、precheck_service.TransferDeps。
逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from app import db
from app.core.errors import ConflictError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED"
def create_execution_run(
precheck: TransferPrecheck,
*,
deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展
actor_id: int | None = None,
selected_invoice_nos: set[str] | None = None,
) -> TransferRun:
"""为已就绪预检创建执行 Run 并关联选中的可执行明细。
Args:
precheck: 已预检(ready_to_execute)对象。
deps: 依赖集合(预留)。
actor_id: 确认操作者。
selected_invoice_nos: 选择范围(缺省关联全部可执行项)。
Returns:
状态为 executing 的 TransferRun。
Raises:
ConflictError: 预检已确认(重复执行)。
"""
if precheck.confirmed_at is not None:
raise ConflictError(
"precheck already executed", code=EXECUTION_CONFLICT_CODE,
)
run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}"
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=precheck.business_date,
status=status_machine.TransferRunStatus.EXECUTING.value,
source_codes_json=list(precheck.scope_json.get("source_codes") or []),
counts_json=dict(precheck.counts_json or {}),
)
db.session.add(run)
db.session.flush()
precheck.run_id = run.id
precheck.status = status_machine.TransferRunStatus.EXECUTING.value
precheck.confirmed_at = datetime.utcnow()
precheck.confirmed_by = actor_id
for item in precheck.items:
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None:
continue
if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos:
continue
item.run_id = run.id
item.status = status_machine.TransferStatus.EXECUTING.value
item.attempt_no += 1
db.session.flush()
return run
def finalize_run(run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""按明细终态汇总 Run 状态(全部 success/duplicate_success → success,否则 partial_failed)。"""
statuses = {str(item.status) for item in items}
terminal_ok = {status_machine.TransferStatus.SUCCESS.value, status_machine.TransferStatus.DUPLICATE_SUCCESS.value}
if statuses and statuses <= terminal_ok:
run.status = status_machine.TransferRunStatus.SUCCESS.value
else:
run.status = status_machine.TransferRunStatus.PARTIAL_FAILED.value
run.completed_at = datetime.utcnow()
@@ -0,0 +1,578 @@
"""在途调拨预检服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
"""
from __future__ import annotations
import uuid
from dataclasses import asdict, dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Protocol
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import canonical_hash
from app.services.in_transit_transfer.contracts import (
PrecheckCountsDTO,
PrecheckInvoiceItemDTO,
PrecheckSummaryDTO,
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
ReadyReceiptFile,
ReceiptFileRepository,
RpaTrigger,
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
# 明细结果值(对应 Invoice 项状态)
RESULT_EXECUTABLE = "executable"
RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
@dataclass(frozen=True)
class RouteMapping:
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
erp_org: str
from_warehouse: str
to_warehouse: str
class RouteNotResolvedError(AppError):
"""来源实例缺少路由归属映射(fail-closed)。"""
def __init__(self, *, source_code: str):
super().__init__(
code=ROUTE_NOT_RESOLVED_CODE,
message=f"route not resolved for source {source_code}",
http_status=422,
details={"source_code": source_code},
)
class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
class SourceProgressDTO:
"""来源实例级进度(决策 18:来源隔离展示)。"""
source_code: str
stage: str
file_no: str | None = None
file_version: str | None = None
checksum: str | None = None
error_code: str | None = None
error_message: str | None = None
@dataclass(frozen=True)
class PrecheckRunResult:
"""一次预检运行的完整结果。"""
summary: PrecheckSummaryDTO
items: tuple[PrecheckInvoiceItemDTO, ...]
sources: tuple[SourceProgressDTO, ...]
@dataclass(frozen=True)
class TransferDeps:
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
erp: Any
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
if any(source.stage not in {"file_ready"} for source in sources):
return "file_pending"
if counts.executable_count > 0:
return "ready_to_execute"
return "success"
def run_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
business_date: 业务日期 T(YYYY-MM-DD)。
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(创建 Run 前可为占位)。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空。
"""
if not source_codes:
raise ValidationError("source_codes is required")
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
items: list[PrecheckInvoiceItemDTO] = []
file_snapshot: dict[str, Any] = {}
for source_code in source_codes:
source_stage: SourceProgressDTO
try:
prepared = ensure_receipt_file_ready(
source_code=source_code,
business_date=business_date,
repository=deps.file_repository,
rpa_trigger=deps.rpa_trigger,
active_source_job_key=active_source_job_key,
)
if prepared.stage != "file_ready" or prepared.file is None:
sources.append(SourceProgressDTO(
source_code=source_code,
stage=prepared.stage,
error_code=prepared.error_code,
error_message=prepared.error_message,
))
continue
ready_file = prepared.file
file_snapshot[source_code] = {
"file_no": ready_file.file_no,
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
business_date=business_date,
ready_file=ready_file,
deps=deps,
run_no=run_no,
)
items.extend(source_items)
sources.append(SourceProgressDTO(
source_code=source_code,
stage="file_ready",
file_no=ready_file.file_no,
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except RouteNotResolvedError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
error_message=str(exc),
))
counts = PrecheckCountsDTO(
file_invoice_count=sum(
1 for item in items
),
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
)
estimated_quantity = sum(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
"file_snapshot": file_snapshot,
"counts": {
"file_invoice_count": counts.file_invoice_count,
"not_matured_count": counts.not_matured_count,
"prechecked_count": counts.prechecked_count,
"executable_count": counts.executable_count,
"blocked_count": counts.blocked_count,
},
"items": [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"result": item.result,
}
for item in items
],
}
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
sources_tuple = tuple(sources)
summary = PrecheckSummaryDTO(
precheck_id="", # 落库时回填
status=_summary_status(sources_tuple, counts),
business_date=business_date,
eligible_receipt_date_to=str(
(date.fromisoformat(business_date) - timedelta(days=1))
),
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_erp_write_count=counts.executable_count,
precheck_hash=precheck_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
def _precheck_invoices(
*,
invoices: list,
source_code: str,
business_date: str,
ready_file: ReadyReceiptFile,
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
for invoice in invoices:
maturity = maturity_status(invoice.receipt_date, business_date)
raw = tuple(
RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version)
for line in invoice.raw_lines
)
receipt_date_iso = invoice.receipt_date.isoformat()
if maturity == MATURITY_NOT_MATURED:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
raw_lines=raw,
))
continue
if maturity == MATURITY_FUTURE:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
raw_lines=raw,
))
continue
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=run_no,
attempt_no=1,
invoice_no=invoice.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=invoice.receipt_quantity,
)
except ErpQueryTimeoutError:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
raw_lines=raw,
))
return output
def _item_status(result: str) -> str:
"""明细结果 → Invoice 项状态。"""
mapping = {
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
}
return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value)
def _generate_no(prefix: str, business_date: str) -> str:
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
compact = str(business_date).replace("-", "")
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
def create_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
Args:
source_codes / business_date / deps: 同 run_precheck。
Returns:
预检摘要(precheck_id 已回填)。
"""
run_no = _generate_no("RUN", business_date)
result = run_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
run_no=run_no,
)
now = datetime.utcnow()
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=business_date,
status="prechecking",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
)
db.session.add(run)
db.session.flush()
# 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。
# 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。
from app.services.in_transit_transfer.source_job_service import create_source_job
_valid_job_statuses = {
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
}
for job_source in result.sources:
create_source_job(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
)
precheck_no = _generate_no("TPC", business_date)
precheck = TransferPrecheck(
precheck_no=precheck_no,
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
"file_version": stage.file_version,
"checksum": stage.checksum,
}
for stage in result.sources
if stage.file_no
},
mapping_version="v0",
strategy_version="v0",
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.flush()
for item in result.items:
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
))
db.session.commit()
summary = PrecheckSummaryDTO(
precheck_id=precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
)
return summary
def restore_precheck(precheck_id: str) -> dict[str, Any]:
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
Args:
precheck_id: 预检编号(TPC-...)。
Returns:
{"summary": {...}, "items": [...], "sources": [...]}。
Raises:
NotFoundError: 预检不存在。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip()
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
counts = PrecheckCountsDTO(**{
key: int(precheck.counts_json.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
})
summary = PrecheckSummaryDTO(
precheck_id=precheck.precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=str(
date.fromisoformat(precheck.business_date) - timedelta(days=1)
),
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=counts,
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
precheck_hash=precheck.precheck_hash,
)
items = []
for item in sorted(precheck.items, key=lambda row: row.invoice_no):
items.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
raw_lines=tuple(
RawLineRefDTO(
sheet=line.get("sheet", ""),
row_no=int(line.get("row_no", 0)),
file_version=line.get("file_version", ""),
)
for line in (item.raw_lines_json or [])
),
))
sources = [
SourceProgressDTO(
source_code=job.source_code,
stage=job.status,
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
SourceProgressDTO(source_code=code, stage="file_ready")
for code in (precheck.scope_json.get("source_codes") or [])
]
return {
"summary": summary,
"items": items,
"sources": sources,
}
@@ -0,0 +1,61 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
# 匹配结果
MATCH_EXECUTABLE = "executable"
MATCH_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
class QuantityValidationError(ValueError):
"""收料数量非法(0、负数、非数字)。"""
def validate_receipt_quantity(value: Any) -> Decimal:
"""校验并归一化收料数量。
Args:
value: 数字或数字字符串。
Returns:
归一化后的 Decimal。
Raises:
QuantityValidationError: 非数字、0 或负数。
"""
try:
quantity = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
if quantity <= 0:
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
return quantity
def strict_quantities_equal(left: Any, right: Any) -> bool:
"""Decimal 精确相等比较(1.0 == 1.00)。"""
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
erp_quantity: ERP 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if erp_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, erp_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -0,0 +1,57 @@
"""在途调拨收料回调桥。
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import TransferSourceJob
_FILE_READY = 'file_ready'
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def advance_source_job_from_receipt_callback(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
"""按来源推进最新等待回调的调拨来源任务。
Args:
source_code: 回调所属来源实例。
file_no: 收料文件号(success 时)。
file_sha256: 收料文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
"""
job = (
TransferSourceJob.query
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
.order_by(TransferSourceJob.id.desc())
.first()
)
if job is None:
return None
if callback_ok and file_no:
job.status = _FILE_READY
job.file_no = file_no
job.file_sha256 = file_sha256
job.error_code = None
job.error_message = None
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
job.error_message = error_message or 'receipt rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
@@ -0,0 +1,101 @@
"""在途调拨真实收料 RPA 触发服务。
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
import uuid
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'warehouse_id': warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def trigger_receipt_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
@@ -0,0 +1,87 @@
"""在途调拨 Worker 崩溃/陈旧执行恢复(区别于 recovery_service 的每日历史复核)。
用途:回收租约过期的 executing 项(重新写前复查 + 幂等写入,不重复建单),
并将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
依赖:execution_service._write_item、orchestrator.finalize_run、status。
逻辑:恢复依赖 Invoice 幂等(重复返回原单号 duplicate_success);
result_unknown 绝不自动重试。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.execution_service import _write_item
from app.services.in_transit_transfer.orchestrator import finalize_run
from app.services.in_transit_transfer.precheck_service import TransferDeps
STALE_EXECUTION_THRESHOLD_SECONDS = 3600
_TERMINAL_ITEM_STATUSES = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
}
def recover_stale_execution_items(*, deps: TransferDeps, now: datetime | None = None,
request_id: str | None = None) -> dict:
"""回收租约过期的执行中明细。
Args:
deps: 注入依赖。
now: 判定时刻。
request_id: 审计上下文。
Returns:
{"recovered": n, "skipped_result_unknown": n, "failed": n}。
"""
current = now or datetime.utcnow()
threshold = current - timedelta(seconds=STALE_EXECUTION_THRESHOLD_SECONDS)
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status == status_machine.TransferStatus.EXECUTING.value,
TransferInvoiceItem.updated_at <= threshold,
).all()
recovered = skipped_unknown = failed = 0
for item in items:
if (item.result_code or "") == "result_unknown" or item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
skipped_unknown += 1
continue
run_no = item.run.run_no if item.run else "RUN-PENDING"
try:
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
recovered += 1
except Exception: # noqa: BLE001 —— 单项恢复失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "recovery_failed"
failed += 1
db.session.flush()
db.session.commit()
return {"recovered": recovered, "skipped_result_unknown": skipped_unknown, "failed": failed}
def finalize_stale_runs(*, now: datetime | None = None) -> list[int]:
"""将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
Args:
now: 判定时刻(保留参数)。
Returns:
已收尾的 Run id 列表。
"""
finalized: list[int] = []
runs = TransferRun.query.filter_by(
status=status_machine.TransferRunStatus.EXECUTING.value,
).all()
for run in runs:
items = list(run.items)
if items and all(item.status in _TERMINAL_ITEM_STATUSES for item in items):
finalize_run(run, items)
finalized.append(run.id)
db.session.flush()
db.session.commit()
return finalized
@@ -0,0 +1,66 @@
"""在途调拨每日历史恢复(自动复核待处理池)。
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
"""
from __future__ import annotations
from dataclasses import dataclass
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
from app.services.in_transit_transfer.retry_service import _recheck_item
@dataclass
class RecoveryOutcome:
"""每日恢复结果汇总。"""
recovered_count: int = 0
still_blocked_count: int = 0
skipped_result_unknown: int = 0
skipped_manually_closed: int = 0
attempts_created: int = 0
def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOutcome:
"""对可恢复异常执行每日自动复核。
Args:
business_date: 业务日期(仅用于审计上下文)。
deps: 注入依赖。
Returns:
RecoveryOutcome。
"""
outcome = RecoveryOutcome()
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
]),
).all()
for item in items:
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
# 只读隔离:不查询、不写入、不创建 Attempt。
outcome.skipped_result_unknown += 1
continue
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
# 永久排除。
outcome.skipped_manually_closed += 1
continue
before_attempt = item.attempt_no
new_status = _recheck_item(item, deps=deps, request_id=None)
if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
outcome.recovered_count += 1
else:
outcome.still_blocked_count += 1
if item.attempt_no > before_attempt:
outcome.attempts_created += 1
db.session.commit()
return outcome
@@ -0,0 +1,120 @@
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from decimal import Decimal
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
from app.services.in_transit_transfer.quantity import classify_quantity_match
RETRY_KIND_ERP_RECHECK = "erp_recheck"
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
Returns:
重检后的 item 状态。
"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no + 1,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
attempt.status = "failed"
else:
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
item.result_code = None
item.result_message = None
item.erp_quantity = str(query.quantity)
attempt.status = "success"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value else "failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no},
))
db.session.flush()
return item.status
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工重试异常项。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": ..., "attempt_no": ...}。
Raises:
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。
NotFoundError: item 不存在。
"""
kind_value = str(kind or "").strip()
if kind_value == RETRY_KIND_RPA_REFETCH:
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
if kind_value != RETRY_KIND_ERP_RECHECK:
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
@@ -0,0 +1,77 @@
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
依赖:contracts、execution_service。
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
"""
from __future__ import annotations
from typing import Any
from app.services.in_transit_transfer.execution_service import serialize_run_result
def serialize_summary(summary) -> dict[str, Any]:
"""预检摘要序列化。"""
return {
"precheck_id": summary.precheck_id,
"status": summary.status,
"business_date": summary.business_date,
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
"expires_at": summary.expires_at,
"counts": {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"prechecked_count": summary.counts.prechecked_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
},
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
"estimated_erp_write_count": summary.estimated_erp_write_count,
"precheck_hash": summary.precheck_hash,
}
def serialize_item(item) -> dict[str, Any]:
"""明细项序列化(决策 6 十列字段)。"""
return {
"source_code": item.source_code,
"material_no": item.material_no,
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"receipt_date": item.receipt_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"to_warehouse": item.to_warehouse,
"to_quantity": str(item.to_quantity),
"result": item.result,
"reason": item.reason,
"raw_lines": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
def serialize_source(source) -> dict[str, Any]:
"""来源进度序列化。"""
return {
"source_code": source.source_code,
"stage": source.stage,
"file_no": source.file_no,
"file_version": source.file_version,
"checksum": source.checksum,
"error_code": source.error_code,
"error_message": source.error_message,
}
def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]:
"""预检恢复详情(summary + items + sources)。"""
return {
"summary": serialize_summary(detail["summary"]),
"items": [serialize_item(item) for item in detail["items"]],
"sources": [serialize_source(source) for source in detail["sources"]],
}
@@ -0,0 +1,63 @@
"""在途调拨来源收料文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;否则 → none。
"""
from __future__ import annotations
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is not None:
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
}
active_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -0,0 +1,70 @@
"""在途调拨来源级状态服务(唯一推进入口)。
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
依赖:models(TransferSourceJob)、status_machine。
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferSourceJob
SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
Args:
run_id: 所属 TransferRun.id。
source_code: 来源实例编码。
status: 初始状态。
Returns:
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
"""
existing = (
TransferSourceJob.query.filter_by(run_id=run_id, source_code=source_code).order_by(TransferSourceJob.id.desc()).first()
)
if existing is not None:
return existing
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
db.session.add(job)
db.session.flush()
return job
def advance_source_job(*, job: TransferSourceJob, status: str, **fields: Any) -> TransferSourceJob:
"""推进单条来源 job 状态并写入来源级事实字段。
Args:
job: 目标 TransferSourceJob。
status: 目标状态(须在 SOURCE_JOB_STATUSES 内,模型 CheckConstraint 兜底)。
fields: 其余来源级字段(file_no/file_sha256/error_code/error_message/lease_until 等),
可选 finished_at 被重置为当前时间。
Returns:
更新后的 job。
"""
job.status = status
for key, value in fields.items():
if hasattr(job, key):
setattr(job, key, value)
if status in ('success', 'partial_failed', 'failed', 'cancelled'):
job.finished_at = datetime.utcnow()
if status == 'pending':
job.started_at = datetime.utcnow()
db.session.flush()
return job
def source_jobs_for_run(run_id: int) -> list[TransferSourceJob]:
"""读取某次 run 的全部来源级 job(供 restore/投影)。"""
return TransferSourceJob.query.filter_by(run_id=run_id).order_by(TransferSourceJob.source_code).all()
@@ -0,0 +1,217 @@
"""在途调拨状态机与转换门禁。
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
(TransferRunStatus)与通知状态(TransferNotificationStatus),
并强制所有状态转换走服务端门禁。
依赖:app.core.errors.AppError。
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态;
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
"""
from __future__ import annotations
from enum import StrEnum
from typing import Mapping
from app.core.errors import AppError
INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
class TransferStatus(StrEnum):
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
FILE_PENDING = "file_pending"
FILE_READY = "file_ready"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
DUPLICATE_SUCCESS = "duplicate_success"
BLOCKED_RECOVERABLE = "blocked_recoverable"
NOT_MATURED = "not_matured"
RESULT_UNKNOWN = "result_unknown"
MANUALLY_CLOSED = "manually_closed"
CANCELLED = "cancelled"
NOTIFICATION_FAILED = "notification_failed"
class TransferRunStatus(StrEnum):
"""Run 级生命周期;ERP 结果与通知结果分离。"""
QUEUED = "queued"
PREPARING_FILES = "preparing_files"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
PARTIAL_FAILED = "partial_failed"
FAILED = "failed"
CANCELLED = "cancelled"
class TransferNotificationStatus(StrEnum):
"""通知投递状态;failed 即提示词中 notification_failed 的语义。"""
PENDING = "pending"
SUCCESS = "success"
FAILED = "failed"
# 无出边终态:这些状态不得再触发任何自动或手工迁移。
TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.NOTIFICATION_FAILED.value,
})
# Invoice 项转换白名单:key=当前状态,value=允许的目标状态集合。
ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.FILE_PENDING.value: frozenset({
TransferStatus.FILE_READY.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.FILE_READY.value: frozenset({
TransferStatus.PRECHECKING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.PRECHECKING.value: frozenset({
TransferStatus.READY_TO_EXECUTE.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.READY_TO_EXECUTE.value: frozenset({
TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检
TransferStatus.EXECUTING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.EXECUTING.value: frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.NOT_MATURED.value: frozenset(),
TransferStatus.SUCCESS.value: frozenset(),
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
TransferStatus.RESULT_UNKNOWN.value: frozenset(),
TransferStatus.MANUALLY_CLOSED.value: frozenset(),
TransferStatus.CANCELLED.value: frozenset(),
TransferStatus.NOTIFICATION_FAILED.value: frozenset(),
}
# Run 级转换白名单。
RUN_TRANSITIONS: dict[str, frozenset[str]] = {
TransferRunStatus.QUEUED.value: frozenset({
TransferRunStatus.PREPARING_FILES.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PREPARING_FILES.value: frozenset({
TransferRunStatus.PRECHECKING.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PRECHECKING.value: frozenset({
TransferRunStatus.READY_TO_EXECUTE.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.READY_TO_EXECUTE.value: frozenset({
TransferRunStatus.EXECUTING.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.EXECUTING.value: frozenset({
TransferRunStatus.SUCCESS.value,
TransferRunStatus.PARTIAL_FAILED.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.SUCCESS.value: frozenset(),
TransferRunStatus.PARTIAL_FAILED.value: frozenset(),
TransferRunStatus.FAILED.value: frozenset(),
TransferRunStatus.CANCELLED.value: frozenset(),
}
class TransferStateError(AppError):
"""非法状态转换领域错误。"""
def __init__(
self,
message: str = "Invalid state transition",
*,
current: str | None = None,
target: str | None = None,
):
details: dict[str, str] = {}
if current is not None:
details["current"] = current
if target is not None:
details["target"] = target
super().__init__(
code=INVALID_STATE_TRANSITION_CODE,
message=message,
http_status=409,
details=details,
)
def assert_transition_allowed(
current: str,
target: str,
*,
transitions: Mapping[str, frozenset[str]] = ITEM_TRANSITIONS,
) -> None:
"""服务端状态转换门禁。
Args:
current: 当前状态。
target: 目标状态。
transitions: 转换白名单(默认 Invoice 项表)。
Raises:
TransferStateError: 当前状态未知或目标不在允许集合内。
"""
current_value = str(current or "").strip()
target_value = str(target or "").strip()
allowed = transitions.get(current_value)
if allowed is None:
raise TransferStateError("unknown current status", current=current_value)
if target_value not in allowed:
raise TransferStateError(
"status transition not allowed",
current=current_value,
target=target_value,
)
def apply_notification_failure(run_status: str) -> str:
"""通知失败不改变 ERP 结果。
Args:
run_status: Run 的 ERP 业务终态。
Returns:
原 run_status(保持不变)。
Raises:
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
"""
status = str(run_status or "").strip()
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
raise TransferStateError(
"notification failure only allowed after ERP terminal status",
current=status,
)
return status
@@ -0,0 +1,61 @@
"""在途调拨策略硬门禁。
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
强制默认 10 分钟确认有效期。
依赖:app.core.errors.AppError、standard decimal。
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
阻止发布/执行(fail-closed)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from app.core.errors import AppError
STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION"
DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟
@dataclass(frozen=True)
class TransferStrategyPolicy:
"""调拨策略冻结快照;三项禁令默认关闭。"""
allow_partial: bool = False
quantity_tolerance: Decimal = Decimal("0")
allow_erp_auto_retry: bool = False
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
class StrategyViolationError(AppError):
"""策略触碰一期禁令。"""
def __init__(self, message: str, *, reason: str):
super().__init__(
code=STRATEGY_VIOLATION_CODE,
message=message,
http_status=409,
details={"reason": reason},
)
def validate_strategy(strategy: TransferStrategyPolicy) -> None:
"""校验策略是否违反一期硬门禁。
Args:
strategy: 待校验策略。
Raises:
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
"""
if strategy.allow_partial:
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
if strategy.quantity_tolerance != Decimal("0"):
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
if strategy.allow_erp_auto_retry:
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
def default_strategy() -> TransferStrategyPolicy:
"""返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。"""
return TransferStrategyPolicy()
@@ -0,0 +1,7 @@
"""services/integration_connector/__init__.py
Integration Connector(外部系统连接器框架):能力契约、绑定解析、REST/SOAP 传输、
声明式映射、凭据引用与调用引擎(CapabilityGateway)。
"""
from __future__ import annotations
@@ -0,0 +1,124 @@
"""services/integration_connector/binding.py
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
from app.services.integration_connector.errors import BindingNotFoundError
@dataclass(frozen=True)
class BindingSnapshot:
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
capability: str
context_selector: dict
client_code: str
interface_code: str
connector_type: str
interface_version: int
mapping_version: int
credential_ref_code: str | None
config: dict
request_spec: dict
response_mapping: dict
output_schema: dict
def _to_naive(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt
def _within_window(binding: IntegrationBinding, now: datetime) -> bool:
effective_from = _to_naive(binding.effective_from)
effective_to = _to_naive(binding.effective_to)
if effective_from is not None and now < effective_from:
return False
if effective_to is not None and now > effective_to:
return False
return True
def _is_subset(selector: dict, context: dict) -> bool:
"""selector 的键值须全部存在于 context(空 selector 恒命中)。"""
return all(context.get(k) == v for k, v in selector.items())
def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot:
"""解析最佳绑定并冻结调用期快照。
Args:
capability: 能力名(如 in_transit_transfer.query_inventory)。
context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。
environment: 环境(prod/test/dev)。
now: 可选时钟(测试注入);缺省用 utcnow。
Returns:
BindingSnapshot。
Raises:
BindingNotFoundError: 无可用绑定(fail-closed)。
"""
base_now = now or datetime.utcnow()
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
candidates: list[tuple[IntegrationBinding, dict]] = []
for row in rows:
if not _within_window(row, base_now):
continue
selector = row.context_selector_json or {}
if not _is_subset(selector, context or {}):
continue
candidates.append((row, selector))
if not candidates:
raise BindingNotFoundError(capability=capability)
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
row, selector = candidates[0]
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
if client is None or iface is None:
raise BindingNotFoundError(capability=capability)
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
config = dict(client.config_json or {})
if client.endpoint is not None:
config['endpoint'] = client.endpoint
if client.timeout_seconds is not None:
config['timeout_seconds'] = client.timeout_seconds
request_spec = dict(iface.request_spec_json or {})
if iface.http_method is not None:
request_spec['method'] = iface.http_method
if iface.request_path is not None:
request_spec['path'] = iface.request_path
selector = dict(row.context_selector_json or {})
if row.context_source_code is not None and 'source_code' not in selector:
selector['source_code'] = row.context_source_code
return BindingSnapshot(
capability=row.capability,
context_selector=selector,
client_code=client.code,
interface_code=iface.code,
connector_type=client.connector_type,
interface_version=iface.version,
mapping_version=row.mapping_version,
credential_ref_code=client.credential_ref_code,
config=config,
request_spec=request_spec,
response_mapping=iface.response_mapping_json or {},
output_schema=iface.output_schema_json or {},
)
@@ -0,0 +1,125 @@
"""services/integration_connector/capability.py
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
"""
from __future__ import annotations
from dataclasses import dataclass
from app.core.errors import ValidationError
from app.services.integration_connector.errors import CapabilityNotFoundError
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
"properties": {
"invoice_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"to_warehouse": {"type": "string"},
"quantity": {"type": "number"},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"properties": {
"found": {"type": "boolean"},
"quantity": {"type": ["number", "null"]},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
@dataclass(frozen=True)
class CapabilitySpec:
"""强类型能力契约(由代码注册)。"""
name: str
input_schema: dict
output_schema: dict
idempotency: str
write: bool
_CAPABILITIES: dict[str, CapabilitySpec] = {}
_LOADED = False
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
"""注册能力;同名重复注册抛 ValidationError。"""
if spec.name in _CAPABILITIES:
raise ValidationError(
f"capability already registered: {spec.name}",
code="INTEGRATION.CAPABILITY_DUPLICATE",
details={"name": spec.name},
)
_CAPABILITIES[spec.name] = spec
return spec
def get_capability(name: str) -> CapabilitySpec:
"""按名查询能力;未注册抛 CapabilityNotFoundError(fail-closed)。"""
spec = _CAPABILITIES.get(name)
if spec is None:
raise CapabilityNotFoundError(name=name)
return spec
def list_capabilities() -> list[CapabilitySpec]:
"""返回全部已注册能力(按名排序)。"""
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
def ensure_capabilities_loaded() -> None:
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
global _LOADED # noqa: PLW0603
if _LOADED:
return
_LOADED = True
_register_transfer_capabilities()
def _register_transfer_capabilities() -> None:
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
register_capability(CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
))
def reset_capability_registry_for_tests() -> None:
"""单测隔离:清空注册表并重置加载标记。"""
global _LOADED # noqa: PLW0603
_CAPABILITIES.clear()
_LOADED = False
@@ -0,0 +1,153 @@
"""services/integration_connector/engine.py
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
"""
from __future__ import annotations
import time
import uuid
from dataclasses import replace
from app import db
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
from app.services.integration_connector.mapping import map_response, schema_errors
from app.services.integration_connector.security import sanitize
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
from app.models import IntegrationCall
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
request_spec = request_spec or {}
spec_path = str(request_spec.get('path') or '')
try:
path = spec_path.format(**params)
except (KeyError, IndexError, ValueError):
path = spec_path
headers = dict(config.get('headers') or {})
spec_params = list(request_spec.get('params') or [])
selected = {k: params[k] for k in spec_params if k in params} or params
template = request_spec.get('template')
if isinstance(template, dict):
body = _fill_template(template, params)
else:
body = selected
return {'path': path, 'params': selected, 'body': body, 'headers': headers}
def _fill_template(template: dict, params: dict) -> dict:
"""填充模板 dict 中的 {placeholder} 占位符。"""
filled: dict = {}
for key, value in template.items():
if isinstance(value, str) and '{' in value:
try:
filled[key] = value.format(**params)
except (KeyError, IndexError, ValueError):
filled[key] = value
else:
filled[key] = value
return filled
def _environment() -> str:
"""从 Flask 配置推导环境(dev/test/prod),缺省 prod。"""
try:
from flask import current_app, has_app_context
if has_app_context():
value = str(current_app.config.get('ENV_NAME') or '').strip().lower()
if value in {'dev', 'test', 'prod'}:
return value
except Exception:
pass
return 'prod'
class CapabilityGateway:
"""能力调用引擎;transports 为 {connector_type: Transport} 可注入。"""
def __init__(self, transports: dict[str, Transport] | None = None) -> None:
self.transports = dict(transports or {})
def call(
self,
*,
capability: str,
context: dict,
params: dict,
operation_id: str,
idempotency_key: str | None = None,
environment: str | None = None,
transports: dict[str, Transport] | None = None,
) -> IntegrationCallResult:
ensure_capabilities_loaded()
spec = get_capability(capability)
input_errors = schema_errors(params, spec.input_schema)
if input_errors:
raise InputInvalidError(details={'errors': input_errors})
env = environment or _environment()
snapshot = resolve_binding(capability, context, env)
transport = (transports or self.transports).get(snapshot.connector_type)
if transport is None:
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
request = build_request(snapshot.request_spec, snapshot.config, params)
trace_id = f'ic-{uuid.uuid4().hex}'
start_ms = int(time.time() * 1000)
try:
raw = transport.call(
client={'config_json': snapshot.config, 'credential': {}},
interface={'request_spec_json': snapshot.request_spec},
request=request,
)
except TimeoutError:
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
return result
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
result = replace(result, data=data)
result = replace(result, trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id)
return result
def _record_call(
operation_id: str,
capability: str,
snapshot: BindingSnapshot,
params: dict,
raw: dict | None,
result: IntegrationCallResult,
start_ms: int,
trace_id: str,
) -> None:
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
elapsed_ms = int(time.time() * 1000) - start_ms
call = IntegrationCall(
operation_id=operation_id,
capability=capability,
binding_snapshot_json={
'client_code': snapshot.client_code,
'interface_code': snapshot.interface_code,
'connector_type': snapshot.connector_type,
'interface_version': snapshot.interface_version,
'mapping_version': snapshot.mapping_version,
'credential_ref_code': snapshot.credential_ref_code,
},
request_summary_json=sanitize(params),
response_summary_json=sanitize(raw or {}),
status=result.status,
elapsed_ms=elapsed_ms,
trace_id=trace_id,
)
db.session.add(call)
db.session.commit()
@@ -0,0 +1,104 @@
"""services/integration_connector/errors.py
用途:Integration Connector 框架统一业务异常类(INTEGRATION.* 错误码)。
依赖:app.core.errors.AppError。
逻辑:fail-closed —— 缺绑定/缺凭据/映射不合法/契约未冻结均抛出,绝不猜测。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
INTEGRATION_CAPABILITY_NOT_FOUND = "INTEGRATION.CAPABILITY_NOT_FOUND"
INTEGRATION_INPUT_INVALID = "INTEGRATION.INPUT_INVALID"
INTEGRATION_BINDING_NOT_FOUND = "INTEGRATION.BINDING_NOT_FOUND"
INTEGRATION_TRANSPORT_NOT_FROZEN = "INTEGRATION.TRANSPORT_NOT_FROZEN"
INTEGRATION_MAPPING_INVALID = "INTEGRATION.MAPPING_INVALID"
INTEGRATION_CREDENTIAL_UNRESOLVED = "INTEGRATION.CREDENTIAL_UNRESOLVED"
INTEGRATION_RESULT_UNKNOWN = "INTEGRATION.RESULT_UNKNOWN"
INTEGRATION_CALL_FAILED = "INTEGRATION.CALL_FAILED"
class CapabilityNotFoundError(AppError):
"""能力未注册(fail-closed)。"""
def __init__(self, message: str = "capability not registered", *, name: str | None = None):
details = {"name": name} if name else {}
super().__init__(
code=INTEGRATION_CAPABILITY_NOT_FOUND, message=message, http_status=404, details=details,
retryable=False,
)
class InputInvalidError(AppError):
"""入参不合能力输入 Schema。"""
def __init__(self, message: str = "input invalid", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_INPUT_INVALID, message=message, http_status=400, details=details or {},
retryable=False,
)
class BindingNotFoundError(AppError):
"""无可用绑定(fail-closed)。"""
def __init__(self, message: str = "no binding for capability", *, capability: str | None = None):
details = {"capability": capability} if capability else {}
super().__init__(
code=INTEGRATION_BINDING_NOT_FOUND, message=message, http_status=503, details=details,
retryable=False,
)
class TransportNotFrozenError(AppError):
"""传输契约未冻结(缺 endpoint/wsdl)。"""
def __init__(self, message: str = "transport not frozen"):
super().__init__(
code=INTEGRATION_TRANSPORT_NOT_FROZEN, message=message, http_status=503, retryable=False,
)
class MappingInvalidError(AppError):
"""映射结果不合输出 Schema(fail-closed)。"""
def __init__(self, message: str = "mapping invalid", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_MAPPING_INVALID, message=message, http_status=503, details=details or {},
retryable=False,
)
class CredentialUnresolvedError(AppError):
"""凭据无法解析(fail-closed)。"""
def __init__(self, message: str = "credential unresolved", *, ref: str | None = None):
details = {"secret_ref": ref} if ref else {}
super().__init__(
code=INTEGRATION_CREDENTIAL_UNRESOLVED, message=message, http_status=503, details=details,
retryable=False,
)
class ResultUnknownError(AppError):
"""写结果无法确认;禁止自动重试。"""
def __init__(self, message: str = "result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(
code=INTEGRATION_RESULT_UNKNOWN, message=message, http_status=503, details=details,
retryable=False,
)
class CallFailedError(AppError):
"""调用技术失败(非业务失败)。"""
def __init__(self, message: str = "call failed", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_CALL_FAILED, message=message, http_status=502, details=details or {},
retryable=False,
)
@@ -0,0 +1,27 @@
"""services/integration_connector/gateway.py
用途:模块级 CapabilityGateway 装配与测试注入点。
依赖:engine.CapabilityGateway、transports.rest/soap。
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
"""
from __future__ import annotations
from app.services.integration_connector.engine import CapabilityGateway
from app.services.integration_connector.transports.rest import RestTransport
from app.services.integration_connector.transports.soap import SoapTransport
_override: CapabilityGateway | None = None
def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
"""测试注入点:设置/清除 CapabilityGateway 覆盖。"""
global _override # noqa: PLW0603
_override = gateway
def get_capability_gateway() -> CapabilityGateway:
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
if _override is not None:
return _override
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
@@ -0,0 +1,210 @@
"""services/integration_connector/mapping.py
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.services.integration_connector.errors import MappingInvalidError
# 表达式安全边界:路径长度/深度上限(失败即 fail-closed)。
MAX_PATH_LENGTH = 256
MAX_DEPTH = 8
# 缺字段哨兵:与合法值 None 区分。
MISSING = object()
def _tokenize(path: str) -> list[str]:
"""把点路径 + 数组下标拆成 token 序列,如 a.b[0].c -> ['a','b','0','c']。"""
tokens: list[str] = []
current = ""
i = 0
n = len(path)
while i < n:
c = path[i]
if c == "[":
if current:
tokens.append(current)
current = ""
j = path.index("]", i)
tokens.append(path[i + 1:j])
i = j + 1
elif c == ".":
if current:
tokens.append(current)
current = ""
i += 1
else:
current += c
i += 1
if current:
tokens.append(current)
return tokens
def extract_path(obj: Any, path: str) -> Any:
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
path = str(path or "")
if len(path) > MAX_PATH_LENGTH:
raise MappingInvalidError(details={"reason": "path_too_long"})
tokens = _tokenize(path)
if len(tokens) > MAX_DEPTH:
raise MappingInvalidError(details={"reason": "path_too_deep"})
cur = obj
for tok in tokens:
if isinstance(cur, list) and tok.isdigit():
idx = int(tok)
if idx >= len(cur):
return MISSING
cur = cur[idx]
elif isinstance(cur, dict) and tok in cur:
cur = cur[tok]
else:
return MISSING
return cur
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
def _default(value: Any, default: Any) -> Any:
return default if value is MISSING else value
def _fallback(value: Any, fallback: Any) -> Any:
return fallback if value is MISSING or value in (None, "") else value
def _decimal(value: Any) -> Any:
if value is MISSING:
return MISSING
return Decimal(str(value))
def _cast(value: Any, to: str) -> Any:
if value is MISSING or value is None:
return MISSING
if to == "int":
return int(value)
if to == "float":
return float(value)
if to == "str":
return str(value)
if to == "bool":
return bool(value)
return value
def _enum_map(value: Any, mapping: dict[str, str]) -> Any:
if value is MISSING:
return MISSING
return mapping.get(str(value), value)
def _list_map(value: Any, mapping: dict[str, str]) -> list[Any]:
if value is MISSING:
return MISSING
return [mapping.get(str(item), item) for item in (value or [])]
def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
if value is MISSING:
return MISSING
return then if condition == "truthy" and bool(value) else else_
TRANSFORMS: dict[str, Any] = {
"default": _default,
"fallback": _fallback,
"decimal": _decimal,
"cast": _cast,
"enum-map": _enum_map,
"list-map": _list_map,
"if-else": _if_else,
}
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
def _matches_type(value: Any, type_spec: Any) -> bool:
if isinstance(type_spec, list):
return any(_matches_type(value, t) for t in type_spec)
if type_spec == "object":
return isinstance(value, dict)
if type_spec == "array":
return isinstance(value, (list, tuple))
if type_spec == "string":
return isinstance(value, str)
if type_spec == "number":
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
if type_spec == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if type_spec == "boolean":
return isinstance(value, bool)
if type_spec == "null":
return value is None
return True
def _validate_against_schema(value: Any, schema: dict, path: str = "") -> list[tuple[str, str]]:
"""返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
if not isinstance(schema, dict):
return []
errors: list[tuple[str, str]] = []
if "enum" in schema and value not in schema["enum"]:
errors.append((path, f"not in enum: {value!r}"))
if "type" in schema and not _matches_type(value, schema["type"]):
errors.append((path, f"expected {schema['type']}, got {type(value).__name__}"))
if isinstance(value, dict):
for req in schema.get("required") or []:
if req not in value:
errors.append((f"{path}.{req}" if path else req, "required missing"))
for key, sub in (schema.get("properties") or {}).items():
if key in value:
errors.extend(_validate_against_schema(value[key], sub, f"{path}.{key}" if path else key))
elif isinstance(value, list) and "items" in schema:
for i, item in enumerate(value):
errors.extend(_validate_against_schema(item, schema["items"], f"{path}[{i}]"))
return errors
def schema_errors(value: Any, schema: dict) -> list[tuple[str, str]]:
"""对 value 做最小 Schema 校验,返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
return _validate_against_schema(value, schema or {})
def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
"""按 mapping 从 raw 提取并转换字段,组装 result 后经 output_schema 校验。
Raises:
MappingInvalidError: 未知转换函数 / 缺必需字段 / 类型或枚举不合。
"""
mapping = mapping or {}
result: dict[str, Any] = {}
for field, spec in mapping.items():
if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec:
value = spec["default"]
else:
expr = spec.get("expr")
value = extract_path(raw, expr) if expr is not None else MISSING
transform = spec.get("transform")
if transform:
fn = TRANSFORMS.get(transform)
if fn is None:
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
value = fn(value, **(spec.get("args") or {}))
if value is not MISSING:
result[field] = value
errors = _validate_against_schema(result, output_schema or {})
if errors:
raise MappingInvalidError(details={"errors": errors})
return result
@@ -0,0 +1,83 @@
"""services/integration_connector/security.py
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
"""
from __future__ import annotations
from typing import Any
from app.models import IntegrationCredentialReference
from app.services.integration_connector.errors import CredentialUnresolvedError
DEFAULT_SENSITIVE_KEYS = frozenset({
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
})
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
Raises:
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
"""
from flask import current_app
cred = IntegrationCredentialReference.query.filter_by(
code=credential_ref_code, status='active',
).first()
if cred is None:
raise CredentialUnresolvedError(ref=credential_ref_code)
secret_ref = cred.secret_ref
value = current_app.config.get(secret_ref) if has_app_ctx() else None
if value is None or value == '':
raise CredentialUnresolvedError(ref=secret_ref)
if isinstance(value, dict):
return dict(value)
return {'value': value}
def has_app_ctx() -> bool:
"""当前是否处于 Flask app 上下文(无则返回 False)。"""
try:
from flask import has_app_context
return has_app_context()
except Exception:
return False
def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any:
"""递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。
Args:
obj: 待脱敏对象(dict/list/标量)。
sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。
Returns:
脱敏后的新对象(不修改入参)。
"""
keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set())
if isinstance(obj, dict):
return {
key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys))
for key, value in obj.items()
}
if isinstance(obj, (list, tuple)):
return [sanitize(item, sensitive_keys) for item in obj]
return obj
def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]:
"""只回凭据元数据,绝不含解析出的明文。"""
return {
'code': cred.code,
'secret_ref': cred.secret_ref,
'secret_provider': cred.secret_provider,
'credential_type': cred.credential_type,
'version': cred.version,
'status': cred.status,
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
}
@@ -0,0 +1,18 @@
"""services/integration_connector/transports/__init__.py
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
"""
from __future__ import annotations
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
from app.services.integration_connector.transports.rest import RestTransport
from app.services.integration_connector.transports.soap import SoapTransport
__all__ = [
'IntegrationCallResult',
'Transport',
'classify_transport_response',
'RestTransport',
'SoapTransport',
]
@@ -0,0 +1,73 @@
"""services/integration_connector/transports/base.py
用途:Transport 统一契约 + 结果分类(IntegrationCallResult)。
依赖:typing.Protocol、dataclass;无 Flask/DB。
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Protocol
# 结果状态集(与在途调拨写入结果分类一致):success / duplicate_success /
# duplicate_unverified / business_failed / technical_failed / timeout / result_unknown
RESULT_STATUSES = (
'success', 'duplicate_success', 'duplicate_unverified', 'business_failed',
'technical_failed', 'timeout', 'result_unknown',
)
@dataclass(frozen=True)
class IntegrationCallResult:
"""一次调用归一后的结果对象。"""
status: str
data: dict[str, Any] | None = None
error_code: str | None = None
error_message: str | None = None
document_no: str | None = None
trace_id: str | None = None
class Transport(Protocol):
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
connector_type: str
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
...
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
Args:
raw: 原始响应 dict,含 status/document_no/verified_posted/code/message。
Returns:
IntegrationCallResult。
"""
status = str(raw.get('status') or 'technical_failed')
document_no = raw.get('document_no')
if status == 'success':
return IntegrationCallResult(status='success', data=raw, document_no=document_no)
if status == 'duplicate_success':
posted = bool(raw.get('verified_posted'))
if posted:
return IntegrationCallResult(status='duplicate_success', data=raw, document_no=document_no)
return IntegrationCallResult(
status='duplicate_unverified', data=raw, document_no=document_no,
error_code='INTEGRATION_DUPLICATE_NOT_VERIFIED',
)
if status == 'business_failed':
return IntegrationCallResult(
status='business_failed', data=raw,
error_code=str(raw.get('code') or 'ERP_BUSINESS_REJECT'),
error_message=str(raw.get('message') or ''),
)
if status == 'timeout':
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
if status == 'result_unknown':
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
@@ -0,0 +1,62 @@
"""services/integration_connector/transports/rest.py
用途:REST Transport——按 client 配置与 interface 请求规格构造 HTTP 请求并返回原始 dict。
依赖:requests(默认注入),可注入 http_request 供测试替身。
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
business_failed dict;非 JSON 响应映射为 technical_failed。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from app.services.integration_connector.errors import TransportNotFrozenError
HttpRequest = Callable[..., Any]
class RestTransport:
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
connector_type = 'rest'
def __init__(self, http_request: HttpRequest | None = None) -> None:
self._http_request = http_request or requests.request
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
spec = interface.get('request_spec_json') or {}
method = str(spec.get('method') or 'GET').upper()
path = str(spec.get('path') or '').strip()
url = endpoint.rstrip('/') + '/' + path.lstrip('/')
headers = {**(config.get('headers') or {}), **(request.get('headers') or {})}
timeout = int(config.get('timeout_seconds') or 60)
response = self._http_request(
method,
url,
params=request.get('params'),
json=request.get('body'),
headers=headers,
timeout=timeout,
)
if int(getattr(response, 'status_code', 0)) >= 400:
return {
'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}",
'message': str(getattr(response, 'text', ''))[:500],
}
try:
return response.json()
except Exception:
return {
'status': 'technical_failed',
'code': 'NON_JSON',
'message': str(getattr(response, 'text', ''))[:500],
}
@@ -0,0 +1,29 @@
"""services/integration_connector/transports/soap.py
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
依赖:zeep(延时导入);errors.py。
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
"""
from __future__ import annotations
from typing import Any
from app.services.integration_connector.errors import TransportNotFrozenError
class SoapTransport:
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
connector_type = 'soap'
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
wsdl = str(config.get('endpoint') or '').strip()
if not wsdl:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
raise NotImplementedError('SOAP implementation pending frozen WSDL')
@@ -40,7 +40,7 @@ def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failed',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
@@ -0,0 +1,57 @@
"""独立收料文件抓取排程(08:00)。
用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。
依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。
逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready
from app.services.schedule.job_registry import ScheduleExecuteResult
def _wanted_sources(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空代表全部启用来源。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get("source_codes") or []
if isinstance(values, str):
values = [values]
return [str(item).strip() for item in values if str(item).strip()]
def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""08:00 收料文件抓取;按来源实例独立执行。"""
deps = transfer_deps.get_transfer_dependencies()
sources = _wanted_sources(task) or []
business_date = str(business_date_now())
total = success = failed = empty = 0
results: list[dict[str, Any]] = []
warnings: list[str] = []
errors: list[str] = []
for source_code in sources:
total += 1
try:
prepared = ensure_receipt_file_ready(
source_code=source_code,
business_date=business_date,
repository=deps.file_repository,
rpa_trigger=deps.rpa_trigger,
)
results.append({"source_code": source_code, "stage": prepared.stage})
if prepared.stage == "file_ready":
success += 1
elif prepared.stage == "waiting_rpa_callback":
empty += 1
else:
failed += 1
errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}")
except Exception as exc: # noqa: BLE001 —— 来源隔离
failed += 1
errors.append(f"{source_code}: {exc}")
return (total, success, failed, empty, results, warnings, errors)
@@ -0,0 +1,59 @@
"""自动调拨排程(09:00)。
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
依赖:auto_transfer、transfer deps、ScheduleExecuteResult。
逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.schedule.job_registry import ScheduleExecuteResult
def _task_params(task: ScheduleTask) -> dict[str, Any]:
return task.job_params if isinstance(task.job_params, dict) else {}
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""09:00 自动调拨:恢复 + 预检 + 执行 + 通知。"""
params = _task_params(task)
source_codes = params.get("source_codes") or []
if isinstance(source_codes, str):
source_codes = [source_codes]
recover_history = bool(params.get("recover_history", True))
recipients = params.get("notify_user_ids") or []
deps = transfer_deps.get_transfer_dependencies()
outcome = run_auto_transfer(
business_date=str(business_date_now()),
deps=deps,
source_codes=[str(item).strip() for item in source_codes],
recover_history=recover_history,
sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果)
recipients=[str(item) for item in recipients],
)
results: list[dict[str, Any]] = []
errors: list[str] = list(outcome.errors)
if outcome.run_no:
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
"notification_status": outcome.notification_status,
})
recovery = outcome.recovery
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
return (
success + recovery.recovered_count,
success,
recovery.still_blocked_count,
0,
results,
[f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"],
errors,
)
@@ -178,6 +178,8 @@ def _register_builtin_platform_jobs() -> None:
description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。",
category="procurement",
))
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
register_platform_job(PlatformJobDefinition(
key="shipping-order-extraction-progress-cleanup",
@@ -403,6 +405,67 @@ def _register_builtin_platform_jobs() -> None:
),
defaults=dict(DEFAULT_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="in-transit-receipt-file",
label="在途收料文件抓取",
handler=run_in_transit_receipt_file_schedule,
description=(
"每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。"
"09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。"
),
category="platform",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "来源实例",
"label_key": "admin.schedule.form.transferSourceCodes",
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
},
),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="in-transit-transfer",
label="在途自动调拨",
handler=run_in_transit_transfer_schedule,
description=(
"每日 09:00 自动处理新增可调拨项与历史可恢复异常;"
"每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。"
),
category="platform",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "来源实例",
"label_key": "admin.schedule.form.transferSourceCodes",
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
},
{
"key": "recover_history",
"type": "boolean",
"label": "历史可恢复异常复核",
"label_key": "admin.schedule.form.transferRecoverHistory",
"required": False,
"default": True,
},
{
"key": "notify_user_ids",
"type": "multi_select",
"label": "通知人",
"label_key": "admin.schedule.form.transferNotifyUsers",
"required": False,
"default": [],
"options_source": "users",
},
),
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
))
_register_builtin_platform_jobs()
@@ -2,7 +2,7 @@
services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py
用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_snapshot_line_ids。
逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op;
仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。
"""
@@ -18,7 +18,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import (
)
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
list_eligible_post_ot_line_keys,
list_eligible_post_ot_snapshot_line_ids,
)
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -63,7 +63,7 @@ def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]:
if scanned >= safe_limit:
break
scanned += 1
eligible = list_eligible_post_ot_line_keys(case)
eligible = list_eligible_post_ot_snapshot_line_ids(case)
if not eligible:
skipped += 1
continue
@@ -2,9 +2,11 @@
services/shipping_notice/auto_progress_controller.py
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll,
强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
from __future__ import annotations
@@ -18,18 +20,18 @@ from flask import current_app
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice.tool_common import log_task_event
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled'})
def audit_legacy_forwarded_entrypoint(
*, task: ShippingNotice, action_code: str, actor_id: int | None = None,
*, task: ShippingOrderTask, action_code: str, actor_id: int | None = None,
request_id: str | None = None,
) -> None:
"""记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。"""
@@ -51,9 +53,9 @@ def _utc_now() -> datetime:
return datetime.utcnow()
def _task_is_cancelled(task: ShippingNotice) -> bool:
def _task_is_cancelled(task: ShippingOrderTask) -> bool:
"""根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。"""
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES or str(getattr(task, 'status', '') or '').strip().lower() == 'cancelled'
def _recover_stale_active_job(job: Job) -> bool:
@@ -90,6 +92,17 @@ def _recover_stale_active_job(job: Job) -> bool:
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'technical_failure_present'
gate.updated_at = now
# [FIX] 同一事务内重算 Execution 指针并回写 OT.stage,避免 Gate 已被判为
# blocked_manual 而 execution.status / OT.stage 仍停在上一机械阶段(如 automating)。
execution_id = getattr(gate, 'execution_id', None)
execution = (
db.session.get(ShippingProcessExecution, int(execution_id))
if execution_id is not None else None
)
if execution is not None:
from app.services.shipping_notice.process_gate_service import _refresh_execution_pointers
_refresh_execution_pointers(execution)
db.session.flush()
return True
@@ -111,7 +124,7 @@ def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
def determine_formal_start_gate(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set: Any | None = None,
) -> str:
@@ -126,7 +139,8 @@ def determine_formal_start_gate(
return 'order_freeze_readiness'
# 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史
# Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
customer_status = str((customer_confirmation_facts(task) or {}).get('status') or '').strip().lower()
if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}:
return 'customer_resolution'
# 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。
@@ -139,7 +153,7 @@ def determine_formal_start_gate(
def _create_formal_execution_for_task(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set_id: int | None,
) -> ShippingProcessExecution:
@@ -178,7 +192,7 @@ def _supersede_duplicate_execution(
)
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
def _active_execution_for_task(task: ShippingOrderTask, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
锁定并取得当前唯一活动 Execution。
@@ -235,7 +249,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id)
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
def supersede_auto_progress_for_candidate_refreeze(task: ShippingOrderTask) -> None:
"""
在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。
@@ -309,9 +323,37 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
return None, None
def _auto_retry_blocked(
trigger: str | None,
has_failed_worker_attempt: bool,
resume_gate_code: str | None = None,
) -> bool:
"""[禁止自动重试] 裁决:已存在失败 Worker Attempt 时是否拒绝再入队。
核心逻辑:防止自动/后台 trigger 在外部依赖持续故障时无人值守空转重试;
但用户显式重试(user_retry / user_manual)或带 resume_gate_code 的显式定向推进
(如匹配工具调 run_task_auto_progress,其 trigger 为 tool_api_match_inventory_line
而非 user_retry)应放行,否则点"重新匹配库存"会因 has_failed_worker_attempt
被误拦、报"自动推进已无待处理 Gate"。
Args:
trigger: 触发类型(auto / user_retry / user_manual / worker_takeover / ...)。
has_failed_worker_attempt: 当前 Gate 是否已有带 job_id 的失败 Attempt。
resume_gate_code: 显式定向推进的目标 Gate;有值即视为用户/工具主动恢复,不拦。
Returns:
True 表示应禁止自动再入队;False 表示放行。
"""
user_initiated = str(trigger or '').strip() in {'user_retry', 'user_manual'}
explicit_resume = bool(str(resume_gate_code or '').strip())
return bool(has_failed_worker_attempt) and not user_initiated and not explicit_resume
def submit_auto_progress(
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
*, task: ShippingOrderTask, trigger: str, operator_id: int | None = None,
resume_gate_code: str | None = None, commit: bool = True,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
@@ -319,14 +361,12 @@ def submit_auto_progress(
"""
接收任何自动/用户触发并安全入队当前 Gate。
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
入口只接受 ShippingOrderTask;Execution 与 Gate 始终按 OT 任务身份推进。
"""
# ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN;
# PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。
locked_task = (
ShippingNotice.query
ShippingOrderTask.query
.filter_by(id=int(task.id))
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.first()
)
if locked_task is None:
@@ -373,14 +413,23 @@ def submit_auto_progress(
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
explicit_inventory_retry = (
str(inventory_mode or '').strip() == 'retry_rpa'
and str(resume_gate_code or '').strip() == 'inventory_preparation'
)
db.session.flush()
if not explicit_inventory_retry:
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
)
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = str(execution.current_gate_code or '').strip() or None
current_gate = (
'inventory_preparation'
if explicit_inventory_retry
else str(execution.current_gate_code or '').strip() or None
)
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=current_gate)
@@ -388,6 +437,53 @@ def submit_auto_progress(
.first()
if current_gate else None
)
if explicit_inventory_retry and gate is not None:
# [ROOT CAUSE] 显式 retry_rpa(含行级改源后重抓)必须覆盖残留的
# poll_inventory_preparation / waiting_external。否则只会再入队只读 poll:
# poll 遇到失败 Preparation 会直接收口,既不建新 RPA Attempt 也不写 trigger。
# passed / waiting_external / failed_terminal 一律放开为 blocked_retryable。
from app.services.shipping_notice.process_gate_job_service import (
cancel_inventory_external_wait_polls,
)
cancel_inventory_external_wait_polls(
gate_id=int(gate.id),
reason='显式库存重抓:终止外部等待轮询',
)
# 活动 Attempt 不得被复用;否则 queue_gate_attempt 会因 BUSY 失败,
# 或 active_attempt 早退把「强制重抓」吞成「继续轮询」。
for stale in (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.all()
):
stale.status = 'failed'
stale.error_code = 'superseded_by_explicit_retry'
stale.error_summary = '被显式库存重抓取代'
stale.finished_at = _utc_now()
if stale.job_id:
stale_job = db.session.get(Job, int(stale.job_id))
if stale_job is not None and str(stale_job.status or '') in _ACTIVE_JOB_STATUSES:
stale_job.status = 'cancelled'
stale_job.finished_at = _utc_now()
stale_job.message = '显式库存重抓:取消残留活动 Job'
gate.status = 'blocked_retryable'
gate.passed_at = None
gate.blocking_reason_code = 'inventory_rpa_retry_requested'
gate.next_action_code = 'retry_inventory_preparation'
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.lock_version = int(gate.lock_version) + 1
gate.updated_at = _utc_now()
execution.current_gate_code = 'inventory_preparation'
# 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate
# 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。
execution.responsible_party = 'worker'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.updated_at = _utc_now()
db.session.flush()
active_attempt = (
ShippingProcessGateAttempt.query
.filter(
@@ -398,7 +494,7 @@ def submit_auto_progress(
.first()
if gate is not None else None
)
if active_attempt is not None and active_attempt.job_id:
if active_attempt is not None and active_attempt.job_id and not explicit_inventory_retry:
if commit:
db.session.commit()
return {
@@ -410,6 +506,22 @@ def submit_auto_progress(
'reused': True,
}
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
# [禁止自动重试] 门禁一旦存在“Worker 真实执行失败”的 Attempt(failed 且 job_id 非空),
# 本次自动投递即属重试:任何 trigger(回调/聊天/批处理)都不得再入队,重试必须由
# 用户在当前 Gate 显式发起;否则外部依赖持续故障时,回调/轮询会形成无人值守的
# “失败→重试→再失败”空转环。仅存量内联投影 Attempt(job_id 为空)或无 Attempt
# 的首次投递不受影响,编排初始触发保持不变。
has_failed_worker_attempt = (
gate is not None
and db.session.query(ShippingProcessGateAttempt.id)
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status == 'failed',
ShippingProcessGateAttempt.job_id.isnot(None),
)
.first()
is not None
)
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
@@ -418,6 +530,7 @@ def submit_auto_progress(
if (
gate is not None
and action_code
and not _auto_retry_blocked(trigger, has_failed_worker_attempt, resume_gate_code)
and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code)
and not is_navigation_action(action_code)
and is_technical_gate_party(execution.responsible_party)
@@ -439,6 +552,8 @@ def submit_auto_progress(
'candidate_set_id': candidate_set_id,
'fencing_token': uuid.uuid4().hex,
'trigger': trigger,
'inventory_mode': inventory_mode,
'line_scope_key': line_scope_key,
'recovery_plan_id': recovery_plan_id,
'recovery_attempt_id': recovery_attempt_id,
'resume_after_gate': resume_after_gate,
@@ -3,7 +3,7 @@ services/shipping_notice/batch_create_idempotency.py
用途:发货通知跨请求文件内容重复校验。
依赖:models.ShippingNotice。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingUploadAttempt.idempotency_key(货代上传幂等)语义分离。
"""
from __future__ import annotations
@@ -83,10 +83,17 @@ def assert_no_exact_duplicate_notices(
return
for content_hash, _filename in hashes:
query = ShippingNotice.query.filter(
ShippingNotice.user_id == user_id,
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
from app.models import ShippingOrderTask, ShippingOrderIntake, FileAsset
query = (
ShippingNotice.query
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(
ShippingOrderTask.user_id == user_id,
FileAsset.content_hash == content_hash,
ShippingOrderTask.lifecycle_status == 'active',
)
)
if skipped_ids:
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -14,7 +14,9 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.tool_common import (
@@ -55,22 +57,25 @@ def _unmark_running(bucket: set[str], key: str) -> None:
def _should_orchestrate_task(task: Any) -> bool:
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if not task_is_active(task):
return False
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
if has_verified_upload_success(task):
return False
if getattr(task, "review_status", None):
return False
if (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason in {"", PH_RPA_PENDING}
):
return True
if getattr(task, "pending_human_reason", None):
if task_blocking_reason(task):
return False
if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}:
latest_attempt = latest_upload_attempt(task) if hasattr(task, 'id') else None
if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {"pending", "running", "failed", "unknown", "timed_out"}:
return False
return True
@@ -95,6 +100,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {"status": "skipped", "message": "task already running"}
try:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
task = get_task_by_ref(normalized_task_no)
if not task:
return {"status": "missing", "message": "task not found"}
@@ -102,30 +109,38 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {
"status": "skipped",
"message": (
f"skip stage={getattr(task, 'current_step', '') or ''}"
f" pending_human_reason={task.pending_human_reason or ''}"
f" review_status={task.review_status or ''}"
f"skip stage={getattr(task, 'stage', '') or ''}"
f" pending_human_reason={task_blocking_reason(task) or ''}"
f" review_status={getattr(task, 'review_status', '') or ''}"
),
}
log_task_event(
task,
"backend_orchestrator_task_started",
{"current_step": task.current_step, "lifecycle_status": task.lifecycle_status},
{"stage": task.stage, "lifecycle_status": task.lifecycle_status},
)
db.session.commit()
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
pending_reason = str(task.pending_human_reason or "").strip().lower()
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
if (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason == PH_RPA_PENDING
):
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
# [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
# rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator')
if recheck is not None:
result = recheck
else:
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
if current_app:
current_app.logger.info(
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
@@ -134,7 +149,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
str(result.get("message") or "")[:300],
)
elif (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason == ""
):
payload["mode"] = "auto"
@@ -166,7 +181,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
"[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
task.task_no,
result.get("status"),
task.current_step,
task.stage,
str(result.get("message") or "")[:300],
)
@@ -178,7 +193,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
{
"result_status": str(result.get("status") or ""),
"lifecycle_status": refreshed.lifecycle_status,
"current_step": refreshed.current_step,
"stage": refreshed.stage,
},
)
db.session.commit()
@@ -190,7 +205,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
db.session.rollback()
task = get_task_by_ref(normalized_task_no)
if task:
task.error_message = str(exc)
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
if hasattr(owner, 'error_message'):
owner.error_message = str(exc)
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
db.session.commit()
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
@@ -15,7 +15,7 @@ from sqlalchemy import update
from app import db
from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
BUSINESS_TYPE = "shipping_notice"
@@ -121,13 +121,19 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
return int(value)
def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str:
def assign_notice_business_number(
notice: ShippingNotice,
*,
moment: datetime | None = None,
customer_id_override: int | None = None,
) -> str:
"""
为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
Args:
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
moment: 可选时刻,测试时用于固定上海业务日期。
customer_id_override: 纠错替代单使用的新客户;仅用于编号,不修改原 OT 的历史匹配事实。
Returns:
分配或已存在的 business_no。
@@ -137,12 +143,18 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
"""
if notice.business_no:
return str(notice.business_no)
if notice.customer_id is None:
owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
resolution = customer_resolution_facts(owner) if owner is not None else {'customer_id': None}
customer_id = int(customer_id_override) if customer_id_override is not None else (
int(resolution['customer_id']) if resolution['customer_id'] is not None else None
)
if customer_id is None:
raise ConflictError(
'Shipping notice customer must be confirmed before numbering',
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED',
)
customer = db.session.get(ShippingCustomer, int(notice.customer_id))
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None or customer.status != 'active':
raise ConflictError(
'Active customer is required before numbering',
@@ -160,7 +172,5 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
notice.business_date = business_date
notice.business_sequence_value = sequence_value
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION
notice.customer_name_snapshot = customer.standard_name
notice.customer_short_code_snapshot = short_code
db.session.flush()
return str(notice.business_no)
@@ -27,7 +27,6 @@ from app.models import (
ShippingOrderCandidate,
ShippingOrderCandidateQualification,
ShippingOrderExtraction,
ShippingOrderCustomerMatch,
)
from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
@@ -71,7 +70,6 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
@@ -79,9 +77,8 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有
``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法
追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知
字段继续 fail-closed。
``required`` 或 ``auto_create_key_field`` 才能阻断。无法追溯 Schema
时继续 fail-closed;系统项次由写路径生成,不构成证据缺失例外。
"""
reason = str(item.get('reason') or item.get('code') or '').strip()
if reason not in _EVIDENCE_GAP_REASONS:
@@ -111,7 +108,7 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
config = None
if config is not None:
return not bool(config.get('required')) and not bool(config.get('auto_create_key_field'))
return field_code in _OPTIONAL_INTERNAL_FIELD_CODES
return False
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
@@ -173,8 +170,7 @@ def resolve_candidate_customer_resolved(
"""
判定 Candidate/Extraction 的 Bill-to 客户是否已确认。
核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed;
其次读 Candidate.structured_result_json.customer.resolution_status。
核心逻辑:只读 Candidate 的正式客户识别结果;不读取 bill_to 或解析摘要兜底。
Args:
candidate: 可选 Candidate。
@@ -183,56 +179,35 @@ def resolve_candidate_customer_resolved(
Returns:
True 表示客户已确认,可用于建单资格评估。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return True
from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
if candidate is None:
return False
ok, _reason = _customer_ok(candidate, customer_resolved=None)
return bool(ok)
resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
if resolution is not None:
return bool(resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None)
# review_case 人工确认新建的 Candidate 只在 structured_result_json['customer'] 写入确认事实
# (review_case 权威确认,见 order_review_confirmation_service._create_review_candidate),并不落 resolution 表;
# 在建单资格判断时兜底认可,避免"已确认客户却无法建单"。
structured = getattr(candidate, 'structured_result_json', None) if candidate is not None else None
if isinstance(structured, dict):
customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {}
return str(customer.get('resolution_status') or '').strip().lower() == 'confirmed'
return False
def resolve_confirmed_bill_to_customer_id(
def resolve_confirmed_customer_id(
*,
candidate: Any | None = None,
extraction_id: int | None = None,
) -> int | None:
"""
返回已确认 Bill-to 标准客户主键;未确认时为 None。
核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。
返回正式识别结果中已确认的标准客户主键;未确认时为 None。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return int(row.customer_id)
return None
from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
return int(resolution.confirmed_customer_id) if (
resolution is not None and resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None
) else None
def assert_customer_confirmed_before_task_create(
@@ -2,11 +2,17 @@
services/shipping_notice/chat_actions.py
用途:发货通知聊天只读状态适配。
依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。
依赖:state_machine(位置/用户模式与内部状态迁移)、ui_state。
逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry
from app.services.shipping_notice.state_machine import (
TaskTransition,
apply_task_transition,
position_for_task,
resolve_task_ui_state,
validate_registry,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
@@ -14,19 +20,20 @@ def build_chat_actions_payload(task) -> dict:
"""
构建聊天气泡侧动作按钮兼容 payload。
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 position/user_mode/summary/process_gate;
业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。
Args:
task: ShippingNotice 模型实例。
Returns:
包含 task_no、checkpoint、process_gate、actions 与摘要的字典。
包含 task_no、position、user_mode、process_gate、actions 与摘要的字典。
"""
state = build_task_ui_state(task)
return {
"task_no": state.get("task_no"),
"checkpoint": state.get("checkpoint"),
"position": state.get("position"),
"user_mode": state.get("user_mode"),
"stage": state.get("stage"),
"todo": state.get("todo"),
"actions": state.get("actions"),
@@ -41,7 +48,7 @@ __all__ = [
"TaskTransition",
"apply_task_transition",
"build_chat_actions_payload",
"checkpoint_for_task",
"position_for_task",
"resolve_task_ui_state",
"validate_registry",
]
@@ -13,7 +13,7 @@ from typing import Any
from flask import current_app
from app.core.errors import ForbiddenError
from app.models import ChatSession, ShippingNotice
from app.models import ChatSession, ShippingOrderTask
READ_SCOPES = frozenset({'get_shipping_status'})
@@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
if session is None:
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
if task_no:
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
task = ShippingOrderTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
if task is None or str(body.get('task') or '').upper() != task.task_no:
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
return body
@@ -1,10 +1,10 @@
"""
services/shipping_notice/constants.py
用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量;
用途:发货通知 API 字段名、位置标签 POSITION_* / review_status / pending_human_reason 的规范常量;
并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。
依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移;
依赖:error_explainability_contract(分层原因码冻结集);state_machine / ui_state 引用 POSITION_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免位置标签漂移;
细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。
"""
@@ -36,28 +36,27 @@ from app.services.shipping_notice.error_explainability_contract import (
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_UPLOAD_REQ = "upload_req"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_CUSTOMER_REVIEW = "customer_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from domain facts)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
CP_ORDER_FREEZE = "order_freeze"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# 位置标签(原 CheckPoint 字面量;非状态机。derive_position / 文案表共用)
POSITION_UPLOAD_REQ = "upload_req"
POSITION_PARSE_OK = "parse_ok" # 转瞬态;新逻辑勿依赖
POSITION_PARSE_REVIEW = "parse_review"
POSITION_CUSTOMER_REVIEW = "customer_review"
POSITION_TASK_EXISTS = "task_exists" # 信息态;新逻辑勿依赖
POSITION_RSV_REQ = "rsv_req"
POSITION_UPLOAD_FAILED = "upload_failed"
POSITION_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
POSITION_WAITING_UPLOAD = "waiting_upload"
POSITION_REJECTED = "rejected"
POSITION_INVENTORY_PENDING = "inventory_pending"
POSITION_READY_MATCH = "ready_to_match"
POSITION_READY_EXPORT = "ready_to_export"
POSITION_EXPORT_READY = "export_ready"
POSITION_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
POSITION_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
POSITION_ORDER_FREEZE = "order_freeze"
POSITION_EXPORT_GENERATED = "export_generated"
POSITION_UPLOADED = "uploaded"
POSITION_COMPLETED = "completed"
# review_status
RS_PARSE_REVIEW = "parse_review"
@@ -68,13 +67,13 @@ RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_RSV_REQ = POSITION_RSV_REQ
PH_SHORTAGE = "shortage"
PH_RPA_EXHAUSTED = "rpa_exhausted"
PH_RPA_PENDING = "rpa_pending"
PH_INV_UNAVAIL = "inv_unavail"
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_NOTICE_TEXT_EXTRACTION_FAILED = POSITION_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
@@ -82,26 +81,26 @@ PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
# 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档)
__all__ = (
'AUTO_CHAIN_FALLBACK',
'CP_UPLOAD_REQ',
'CP_PARSE_OK',
'CP_PARSE_REVIEW',
'CP_CUSTOMER_REVIEW',
'CP_TASK_EXISTS',
'CP_RSV_REQ',
'CP_UPLOAD_FAILED',
'CP_UPLOAD_RESULT_UNKNOWN',
'CP_WAITING_UPLOAD',
'CP_REJECTED',
'CP_INVENTORY_PENDING',
'CP_READY_MATCH',
'CP_READY_EXPORT',
'CP_EXPORT_READY',
'CP_NOTICE_TEXT_EXTRACTION_FAILED',
'CP_INVENTORY_SOURCE_REVIEW',
'CP_ORDER_FREEZE',
'CP_EXPORT_GENERATED',
'CP_UPLOADED',
'CP_COMPLETED',
'POSITION_UPLOAD_REQ',
'POSITION_PARSE_OK',
'POSITION_PARSE_REVIEW',
'POSITION_CUSTOMER_REVIEW',
'POSITION_TASK_EXISTS',
'POSITION_RSV_REQ',
'POSITION_UPLOAD_FAILED',
'POSITION_UPLOAD_RESULT_UNKNOWN',
'POSITION_WAITING_UPLOAD',
'POSITION_REJECTED',
'POSITION_INVENTORY_PENDING',
'POSITION_READY_MATCH',
'POSITION_READY_EXPORT',
'POSITION_EXPORT_READY',
'POSITION_NOTICE_TEXT_EXTRACTION_FAILED',
'POSITION_INVENTORY_SOURCE_REVIEW',
'POSITION_ORDER_FREEZE',
'POSITION_EXPORT_GENERATED',
'POSITION_UPLOADED',
'POSITION_COMPLETED',
'RS_PARSE_REVIEW',
'RS_SHORTAGE_REVIEW',
'RS_RSV_REQ',
@@ -1,19 +1,16 @@
"""
services/shipping_notice/customer_auto_resolution.py
用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。
用途:基于管理员审核的强证据受控自动确认 OT 客户。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
"""
from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
@@ -24,24 +21,25 @@ from app.models import (
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingOrderTask,
ShippingTaskEvent,
)
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
customer_confirmation_facts,
)
from app.services.shipping_notice.customer_normalization import (
is_public_email_domain,
normalize_customer_name,
normalize_domain,
normalize_email,
)
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated",
"customer_auto_confirmed",
"customer_correction_applied",
)
@@ -92,6 +90,52 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
}
def _ruleset_definitions_semantically_compatible(
snapshot: dict[str, Any], schema_version: ShippingOrderSchemaVersion,
) -> bool:
"""
校验规则集冻结定义在解析所用 Schema 版本中语义契约仍成立(允许 Schema 常规重发布造成的版本错位)。
语义键集合:field_code / scope('header') / value_type / normalizer_key / available_for_customer_identity。
允许 display_name、aliases、extraction_instruction、evidence_policy 等非语义字段变化;
任一语义键不一致或字段被停用则 fail-closed,防止按过期配置标准化产生误绑客户。
Args:
snapshot: 影子 rule_set 快照(含 definitions)。
schema_version: 解析实际使用的 Schema 版本。
Returns:
True 表示所有带 field_code 的定义在新 Schema 中语义兼容。
"""
fields = ((schema_version.definition_json or {}).get('fields') or []) if schema_version else []
fields_by_code = {
str(item.get('field_code') or ''): item
for item in fields if isinstance(item, dict) and str(item.get('field_code') or '')
}
definitions = snapshot.get('definitions') if isinstance(snapshot, dict) else []
for raw in definitions if isinstance(definitions, list) else []:
if not isinstance(raw, dict):
continue
config = raw.get('field_config') if isinstance(raw.get('field_config'), dict) else {}
field_code = str(config.get('field_code') or '').strip()
if not field_code:
# 旧快照未保存 field_code:无法做语义校验,交由 UUID 直配路径(继续,不判定失败)。
continue
actual = fields_by_code.get(field_code)
if actual is None or not actual.get('enabled', True):
return False
if str(actual.get('scope') or '') != 'header' or str(config.get('scope') or '') != 'header':
return False
if str(actual.get('value_type') or '') != str(config.get('value_type') or ''):
return False
if not actual.get('available_for_customer_identity'):
return False
frozen_normalizer = str(config.get('normalizer_key') or '').strip()
if frozen_normalizer and frozen_normalizer != str(actual.get('normalizer_key') or '').strip():
return False
return True
def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None:
"""校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。"""
context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {}
@@ -118,16 +162,12 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] |
or snapshot.get('order_schema') != frozen_definition.get('order_schema')
):
return None
schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None
if not schema or schema.get('id') != shadow.order_schema_version_id:
return None
# Schema 锚点放宽:规则集冻结的版本 id 可与解析实际使用的版本错位(Schema 常规重发布),
# 但解析所用 Schema 版本必须真实存在(published/retired),且规则集定义在新 Schema 中语义兼容。
schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
if (
schema_version is None
or schema_version.status not in {'published', 'retired'}
or schema_version.version != schema.get('version')
or schema_version.checksum != schema.get('checksum')
):
if schema_version is None or schema_version.status not in {'published', 'retired'}:
return None
if not _ruleset_definitions_semantically_compatible(snapshot, schema_version):
return None
extraction_id = context.get('order_extraction_id')
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None
@@ -286,7 +326,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
return result
def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""
使用任务来源 Candidate 的影子证据执行受控自动裁决。
@@ -307,13 +347,14 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
'is_eligible': False,
},
}
if task.source_candidate_id is None:
candidate_id = getattr(task, 'candidate_id', None)
if candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(task.source_candidate_id),
candidate_id=int(candidate_id),
).first()
if shadow is None:
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
candidate = db.session.get(ShippingOrderCandidate, int(candidate_id))
if candidate is not None:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
@@ -333,20 +374,23 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
return {**decision, 'quality_gate': quality_gate}
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
def try_auto_confirm_task_customer(task: ShippingOrderTask) -> dict[str, Any]:
"""
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
尝试自动确认 OT 客户;未达门槛时保持 customer_review。
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。
核心逻辑:先写自动裁决审计,再复用人工确认事务;成功后将确认方法改为 auto_rule。
"""
if task.customer_resolution_status == "confirmed":
return {"status": "already_confirmed", "customer_id": task.customer_id}
facts = customer_confirmation_facts(task)
if facts['status'] == 'confirmed':
return {"status": "already_confirmed", "customer_id": facts['customer_id']}
decision = resolve_auto_customer_from_shadow(task)
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type="customer_auto_resolution_evaluated",
detail_json=decision,
))
event_task_id = task_event_task_id(task)
if event_task_id is not None:
db.session.add(ShippingTaskEvent(
task_id=event_task_id,
event_type="customer_auto_resolution_evaluated",
detail_json=decision,
))
if decision.get("customer_id") is None:
db.session.flush()
return decision
@@ -358,165 +402,32 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
resolution_method="auto_rule",
commit=False,
)
db.session.add(ShippingTaskEvent(
task_id=updated.id,
event_type="customer_auto_confirmed",
detail_json={
**decision,
"business_no": updated.business_no,
},
))
updated_event_task_id = task_event_task_id(updated)
if updated_event_task_id is not None:
db.session.add(ShippingTaskEvent(
task_id=updated_event_task_id,
event_type="customer_auto_confirmed",
detail_json={
**decision,
"business_no": getattr(updated, 'business_no', None),
},
))
db.session.flush()
return {**decision, "status": "auto_confirmed", "business_no": updated.business_no}
def correct_numbered_task_customer(
task: ShippingNotice,
*,
customer_id: int,
reason: str,
actor_id: int | None,
) -> dict[str, Any]:
"""
更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。
核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice →
清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
Args:
task: 原业务号或技术号定位到的当前任务版本。
customer_id: 管理员确认的正确启用客户 ID。
reason: 必填纠错原因,写入审计事件。
actor_id: 管理员审计 ID。
Returns:
原号、新号、替代业务单和受影响任务信息。
Raises:
ValidationError: 缺少原因、客户无效或客户未变化。
ConflictError: 业务单未编号、已上传或已被替代。
"""
correction_reason = str(reason or "").strip()
if not correction_reason:
raise ValidationError(
"Customer correction reason is required",
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
)
original = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
.with_for_update()
.one_or_none()
)
if original is None or not original.business_no:
raise ConflictError(
"Numbered shipping notice is required for customer correction",
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
)
existing_replacement = db.session.query(ShippingNotice.id).filter_by(
supersedes_task_id=original.id,
).first()
if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided':
raise ConflictError(
"Shipping notice has already been replaced",
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
)
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
if customer.status == "merged":
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
if customer.status != "active":
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
if original.customer_id == customer.id:
raise ValidationError(
"Corrected customer must differ from the current customer",
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
)
if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
raise ConflictError(
"Uploaded shipping notices require an external cancellation workflow before correction",
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
)
old_business_no = str(original.business_no)
now = datetime.utcnow()
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
replacement = ShippingNotice(
task_no=generate_task_no(),
user_id=original.user_id,
conversation_id=original.conversation_id,
source_type=original.source_type,
source_file_name=original.source_file_name,
source_file_type=original.source_file_type,
source_content_hash=original.source_content_hash,
source_asset_id=original.source_asset_id,
source_intake_id=original.source_intake_id,
source_candidate_id=original.source_candidate_id,
order_task_id=original.order_task_id,
business_fingerprint=original.business_fingerprint,
fingerprint_version=original.fingerprint_version,
content_fingerprint=original.content_fingerprint,
content_fingerprint_version=original.content_fingerprint_version,
document_version=int(original.document_version or 1) + 1,
supersedes_task_id=original.id,
raw_content=original.raw_content,
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
customer_resolution_status="confirmed",
customer_resolution_method="admin_correction",
customer_identity_fingerprint=customer_fingerprint,
customer_confirmed_by=actor_id,
customer_confirmed_at=now,
)
db.session.add(replacement)
db.session.flush()
new_business_no = assign_notice_business_number(replacement)
original.lifecycle_status = 'voided'
original.voided_at = now
original.voided_by_id = actor_id
original.void_reason = f'customer_correction:{correction_reason}'
correction_detail = {
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"old_customer_id": original.customer_id,
"new_customer_id": customer.id,
"reason": correction_reason,
"actor_id": actor_id,
}
db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail))
db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail))
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
db.session.commit()
return {
"task_no": replacement.task_no,
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"customer_id": customer.id,
"affected_task_count": 1,
}
# OT 阶段只确认客户;业务编号属于正式 Notice 的 Excel 生成事务。
return {**decision, "status": "auto_confirmed", "business_no": None}
def get_auto_resolution_metrics() -> dict[str, Any]:
"""汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。"""
"""汇总自动裁决事件,供管理员监控、查询与降级判断。"""
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_resolution_evaluated",
).distinct().count()
confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_confirmed",
).distinct().count()
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_correction_applied",
).distinct().count()
recent_events = (
db.session.query(ShippingTaskEvent, ShippingNotice.task_no)
.join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id)
db.session.query(ShippingTaskEvent, ShippingOrderTask.task_no)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingTaskEvent.task_id)
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
.order_by(ShippingTaskEvent.id.desc())
.limit(100)
@@ -528,7 +439,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
'quality_gate': _auto_confirmation_quality_gate(),
"evaluated_count": evaluated,
"auto_confirmed_count": confirmed,
"corrected_task_count": corrected,
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
"recent_events": [
{
@@ -8,7 +8,6 @@ backend/app/services/shipping_notice/customer_identity_gate.py
from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any
@@ -16,18 +15,44 @@ from sqlalchemy import or_
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.models import (
ShippingCustomer,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.customer_normalization import clean_text
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
customer_resolution_facts,
)
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
"""判断 Notice 自身是否已通过标准客户确认。"""
if task.customer_id is None:
def customer_confirmation_facts(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""读取唯一客户识别结果;bill_to 等订单字段仅可出现在识别证据中。"""
facts = customer_resolution_facts(task)
resolution = facts['resolution']
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
return {
'customer_id': facts['customer_id'],
'status': facts['status'],
'resolution_method': getattr(resolution, 'confirmation_method', None),
'identity_fingerprint': getattr(resolution, 'identity_rule_set_checksum', None),
'confirmed_by_id': getattr(resolution, 'confirmed_by_id', None),
'confirmed_at': getattr(resolution, 'confirmed_at', None),
'customer_name_snapshot': getattr(customer, 'standard_name', None),
'customer_short_code_snapshot': getattr(customer, 'short_code', None),
}
def customer_identity_is_confirmed(task: ShippingNotice | ShippingOrderTask) -> bool:
"""判断 OT 或正式 Notice 是否已通过标准客户确认。"""
facts = customer_confirmation_facts(task)
if facts['customer_id'] is None or facts['status'] != 'confirmed':
return False
customer = db.session.get(ShippingCustomer, int(task.customer_id))
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
customer = db.session.get(ShippingCustomer, int(facts['customer_id']))
return bool(customer and customer.status == 'active')
def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None:
@@ -42,6 +67,9 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
"""
if customer_identity_is_confirmed(task):
return
facts = customer_confirmation_facts(task)
customer_id = facts['customer_id']
status = facts['status'] or 'pending'
raise AppError(
code=CUSTOMER_GATE_ERROR_CODE,
message='标准客户尚未确认,无法继续后续流程',
@@ -49,8 +77,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
details={
'operation': operation,
'task_no': task.task_no,
'customer_resolution_status': task.customer_resolution_status or 'pending',
'customer_id': task.customer_id,
'customer_resolution_status': status,
'customer_id': customer_id,
},
)
@@ -71,15 +99,15 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str
def confirm_task_customer(
task: ShippingNotice,
task: ShippingNotice | ShippingOrderTask,
*,
customer_id: int,
actor_id: int | None,
resolution_method: str = 'manual',
commit: bool = True,
) -> ShippingNotice:
) -> ShippingNotice | ShippingOrderTask:
"""
人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。
人工确认 OT/Notice 所属标准客户;业务编号仅由正式 Notice 的 Excel 阶段分配。
核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。
客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。
@@ -91,12 +119,11 @@ def confirm_task_customer(
resolution_method: manual/auto_rule 等审计方法。
commit: 是否提交事务;批次编排传 False 由外层统一提交。
"""
model = ShippingOrderTask if isinstance(task, ShippingOrderTask) else ShippingNotice
task = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
# ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN;
# PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。
.with_for_update(of=ShippingNotice)
db.session.query(model)
.filter(model.id == int(task.id))
.with_for_update(of=model)
.one()
)
customer = db.session.get(ShippingCustomer, int(customer_id))
@@ -106,38 +133,28 @@ def confirm_task_customer(
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
if task.business_no and task.customer_id not in {None, customer.id}:
facts = customer_confirmation_facts(task)
if getattr(task, 'business_no', None) and facts['customer_id'] not in {None, customer.id}:
raise ConflictError(
'Numbered shipping notice customer cannot be changed silently',
code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED',
)
now = datetime.utcnow()
previous_customer_id = task.customer_id
task.customer_id = customer.id
task.customer_name_snapshot = customer.standard_name
task.customer_short_code_snapshot = customer.short_code
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = resolution_method
task.customer_identity_fingerprint = fingerprint
task.customer_confirmed_by = actor_id
task.customer_confirmed_at = now
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type='customer_confirmed',
detail_json={
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'previous_customer_id': previous_customer_id,
'method': resolution_method,
'business_no': task.business_no,
},
))
owner = task
if not isinstance(task, ShippingOrderTask):
order_task_id = getattr(task, 'order_task_id', None)
owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
if owner is None:
raise ConflictError('Shipping notice is not linked to an order task', code='SHIPPING.ORDER_TASK_REQUIRED')
confirm_customer_resolution(
owner,
customer_id=int(customer.id),
actor_id=actor_id,
method=resolution_method,
)
if commit:
db.session.commit()
return db.session.get(ShippingNotice, int(task.id))
return db.session.get(model, int(task.id))
db.session.flush()
return task
@@ -154,7 +171,7 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict
task=task,
message='标准客户尚未确认,请先选择正式客户后再继续。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
forbidden_next_tools=[
'ensure_inventory', 'parse_inventory', 'match_inventory',
@@ -187,7 +204,7 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message='请选择标准客户。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
)
updated = confirm_task_customer(
@@ -0,0 +1,76 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
"""按 OT、Notice 或 Candidate 读取正式客户识别结果,不回读 bill_to 或解析摘要。"""
candidate_id = getattr(task, 'id', None) if isinstance(task, ShippingOrderCandidate) else getattr(task, 'candidate_id', None)
if candidate_id is None:
order_task_id = getattr(task, 'order_task_id', None)
order_task = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
candidate_id = getattr(order_task, 'candidate_id', None)
if candidate_id is None:
return None
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(candidate_id)).one_or_none()
def resolution_for_extraction(extraction_id: int | None) -> ShippingCustomerShadowResolution | None:
"""按当前 Extraction 找到关联 Candidate 的唯一客户识别结果。"""
if extraction_id is None:
return None
candidate = ShippingOrderCandidate.query.filter_by(order_extraction_id=int(extraction_id)).one_or_none()
return resolution_for_task(candidate) if candidate is not None else None
def customer_resolution_facts(task: Any) -> dict[str, Any]:
"""返回流程 Gate 所需的最小客户确认事实,缺失时 fail-closed。"""
resolution = resolution_for_task(task)
if resolution is None:
return {'customer_id': None, 'status': None, 'resolution': None}
return {
'customer_id': resolution.confirmed_customer_id,
'status': resolution.status,
'resolution': resolution,
}
def confirm_customer_resolution(
task: Any,
*,
customer_id: int,
actor_id: int | None,
method: str,
reason: str | None = None,
) -> ShippingCustomerShadowResolution:
"""确认当前识别结果的客户;人工或自动确认均保留原始证据、规则和候选快照。"""
resolution = resolution_for_task(task)
if resolution is None:
raise ConflictError('Customer resolution is required before confirmation', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
resolution.confirmed_customer_id = int(customer.id)
resolution.confirmation_method = str(method)
resolution.confirmation_reason = str(reason or '').strip() or None
resolution.confirmed_by_id = actor_id
resolution.confirmed_at = datetime.utcnow()
resolution.status = 'confirmed'
db.session.flush()
return resolution
@@ -1,517 +0,0 @@
"""
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、
tool_common(操作人/生命周期快照)、fulfillment_audit。
逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照,
reject/close/confirm 同步写入 ShippingAuditEvent。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_PARSE_OK,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
adjudicate_and_apply_inventory_source,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
from app.services.shipping_notice.tool_common import (
log_task_action_event,
log_task_event,
merge_tool_payload,
payload_wants_auto_chain_fallback,
resolve_workspace_actor_id,
task_lifecycle_audit_snapshot,
prepend_tool_message,
)
from app.services.shipping_notice.tool_response import tool_response
def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
return _start(task_no)
def _reset_inventory_state_for_forced_rpa(task) -> None:
"""
清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。
【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。
"""
task.inventory_lines_json = None
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。
核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留
(review_status / pending_human_reason / error_message / upload 错误),
避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。
"""
task = kwargs.get('task')
if task is not None:
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
def _prepare_task_for_inventory_reupload(task) -> None:
"""
解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。
【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。
历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。
"""
if task.id is not None:
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all():
link.is_active = False
_reset_inventory_state_for_forced_rpa(task)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate
Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。
Args:
payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
Returns:
dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(
status="failed",
message=t("workflow.decision.task_not_found", lang="zh"),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
actor_id = resolve_workspace_actor_id(payload)
before_snapshot = task_lifecycle_audit_snapshot(task)
# Published parsing profiles are the only production mapping contract.
# Reject legacy task-level mapping decisions instead of reopening a manual
# mapping path that could override the source's configured profile.
if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。",
data=serialize_task_for_tool(task),
)
if decision == "reparse_inventory":
_prepare_task_for_inventory_reupload(task)
log_task_action_event(
task,
"inventory_reupload_requested",
action="reparse_inventory",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
data=serialize_task_for_tool(task),
checkpoint="upload_req",
stop_agent_turn=True,
)
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_rejected",
action="reject",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='reject',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'rejected'},
metadata={'decision': 'reject'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.rejected", lang=lang),
data=serialize_task_for_tool(task),
)
if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_closed",
action="close",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='close',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'closed'},
metadata={'decision': 'close'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.closed", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 2] 处理“确认继续”类决策。
# confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。
if decision in {"confirm", "confirmed", "confirm_parse"}:
if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
data=serialize_task_for_tool(task),
)
if (
decision == "confirm_parse"
or task.review_status == RS_PARSE_REVIEW
or task.pending_human_reason == PH_LOW_CONF
or not match_completed(task)
):
parse_validation = (
(task.step_payload_json or {}).get("parse_validation")
if isinstance(task.step_payload_json, dict)
else None
)
blocking_issues = [
item
for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or []
if isinstance(item, dict) and item.get("severity") == "blocking"
]
if blocking_issues:
return tool_response(
status="needs_human",
task=task,
message="解析结果仍包含不合法的关键字段,请修正后再确认。",
data={**serialize_task_for_tool(task), "parse_validation": parse_validation},
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
# 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
if (
not is_low_confidence_parse_confirm
and (
task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
or not is_inventory_source_stable(task)
)
):
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"parse_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_parse',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
if not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
return tool_response(
status="ok",
task=task,
message="解析内容已确认,请继续选择正式库存源。",
data={
**serialize_task_for_tool(task),
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
if not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.parse_confirmed_running", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="ok",
task=task,
message=t("workflow.decision.parse_confirmed_next", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_matched',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.matched_confirmed", lang=lang),
data=serialize_task_for_tool(task),
)
if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.inventory_preparing", lang=lang),
data=serialize_task_for_tool(task),
)
if task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.fulfillment_running", lang=lang),
data=serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.confirm_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 3] 处理重算型决策。
# retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路,
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
_reset_inventory_state_for_forced_rpa(task)
log_task_event(
task,
"decision_retry_rpa",
{"comment": comment, "force_refresh": True},
actor_id=actor_id,
source=event_source,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_preparation',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
if decision == "rematch":
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_action_event(
task,
"decision_rematch",
action="rematch",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
# flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_from_matching',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
if decision == "reparse":
candidate = (
db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
if task.source_candidate_id else None
)
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
if source_run_id:
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
run = db.session.get(ShippingOrderProcessingRun, source_run_id)
if run is not None:
replacement, reused = reparse_order_extraction_run(
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
)
log_task_action_event(
task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment,
extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused},
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human", task=task,
message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。",
data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no},
checkpoint=task.review_status or "parse_review", stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="needs_human",
task=task,
message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。",
data=serialize_task_for_tool(task),
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
)
@@ -13,18 +13,18 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingNotice, ShippingTemporaryInventorySession
from app.models import ShippingOrderTask, ShippingTemporaryInventorySession
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
def _task_by_task_no(task_id: str) -> ShippingOrderTask | None:
"""按显式 task_id 获取任务;禁止按会话号猜测当前任务。"""
normalized = str(task_id or "").strip().upper()
if not normalized:
return None
return ShippingNotice.query.filter_by(task_no=normalized).first()
return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
@@ -56,7 +56,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
return str(item.session_no or '').strip().upper() or None if item else None
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None:
def _focus_task_row(focus_task: str, explicit_task_row: ShippingOrderTask | None) -> ShippingOrderTask | None:
"""
解析当前显式焦点任务行。
@@ -74,7 +74,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -
return None
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
return explicit_task_row
return ShippingNotice.query.filter_by(task_no=normalized).first()
return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def build_dify_chat_inputs(
@@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy(
dynamic_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
# dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
@@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows(
_absolute_relative_region(bbox, item)
for item in (exclusion_regions or []) if isinstance(item, dict)
]
marker_authorization_exclusions = exclusions
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
# 从而保留管理员配置的普通排除区。
@@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows(
continue
band_indices = {glyph_index for glyph_index, _glyph in band}
marker_indices.update(band_indices)
if exclusions and any(
if marker_authorization_exclusions and any(
_inside_region(glyph.bbox, region)
for _glyph_index, glyph in band
for region in exclusions
for region in marker_authorization_exclusions
):
authorized_marker_indices.update(band_indices)
# [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。
@@ -604,7 +606,8 @@ def reconstruct_coordinate_profile_rows(
# This mode is opt-in per table region. It supports documents whose stable
# columns stay put while optional descriptions move values across visual rows.
if row_reconstruction_mode == 'dynamic_x_columns':
return _reconstruct_dynamic_x_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_dynamic_x_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
if row_reconstruction_mode == 'adaptive_record_columns':
return _reconstruct_adaptive_record_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_adaptive_record_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
relative_y_rows = _reconstruct_relative_y_profile_rows(
@@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows(
schema_fields=schema_fields,
)
if relative_y_rows is not None:
return relative_y_rows
return _resolve_shifted_part_number_candidates(
rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def values_for(
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
@@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows(
current_issues.extend(continuation_issues)
next_offset += 1
flush()
return results if include_deleted else [row for row in results if row.role != 'deleted']
rows = results if include_deleted else [row for row in results if row.role != 'deleted']
return _resolve_shifted_part_number_candidates(
rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def _project_coordinate_profile_regions(
@@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows(
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
values: dict[str, str] = {}
issues: list[str] = []
deleted = any(
_DELETED_PATTERN.fullmatch(re.sub(
r'\s+', '', ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
),
))
for _row_index, band in record
)
for field in fields:
code = str(field['field_code'])
saved = _absolute_relative_region(table_bbox, field['region'])
# [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分,
# 保持 LayoutBBox 的非负原点和正面积契约。
shifted_y0 = max(0.0, saved.y0 + delta_y)
region = LayoutBBox(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
x0=saved.x0, y0=shifted_y0,
x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y),
)
selected_bands = [
band for _row_index, band in record
@@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows(
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _band in record],
role='data', issues=issues,
role='deleted' if deleted else 'data', issues=issues,
))
return results if include_deleted else [row for row in results if row.role != 'deleted']
@@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows(
start_region = _absolute_relative_region(table_bbox, start_field['region'])
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
results: list[CoordinateProfileLogicalRow] = []
sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)]
expected_indices = _calibrate_field_band_indices(
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
)
multiline_fields = {
id(field) for field in fields
if sum(
_regions_overlap_vertically(
_absolute_relative_region(table_bbox, field['region']), _band_bbox(band),
)
for _row_index, band in sample_record
) > 1
}
for anchor_index, start in enumerate(anchors):
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
record = usable_bands[start:end]
@@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
)
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if id(field) not in multiline_fields:
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else ''
if code == 'part_number':
expected_index = expected_indices.get(id(field), 0)
candidates: list[tuple[float, int, str]] = []
for candidate_index in range(expected_index, len(record)):
candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region)
if _is_structured_part_identifier(candidate_raw):
compact_candidate = re.sub(r'\s+', '', candidate_raw)
candidates.append((
_profile_field_band_score(
raw=candidate_raw, field_code=code,
extractor_key=str(field.get('extractor_key') or 'direct'),
),
candidate_index, candidate_raw,
))
if re.search(r'\d', compact_candidate):
candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:])
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
raw = candidates[0][2]
elif len(candidates) > 1:
best = candidates[0]
if best[0] > candidates[1][0] + .25:
raw = best[2]
else:
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
raw = ''
else:
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if not raw:
continue
extracted = extract_profile_field_value(
@@ -1890,6 +1964,112 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
return score
def _is_structured_part_identifier(raw: str) -> bool:
"""仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。"""
value = str(raw or '').strip()
compact = re.sub(r'\s+', '', value)
return bool(
not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE)
and
re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact)
and re.search(r'\d|[._:/-]', compact)
)
def _resolve_shifted_part_number_candidates(
*, rows: list[CoordinateProfileLogicalRow],
glyphs: list[tuple[int, PositionedCharacter]],
ordered_layouts: list[dict[str, Any]],
table_bbox: LayoutBBox,
line_start_field_code: str,
) -> list[CoordinateProfileLogicalRow]:
"""在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前
逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变
没有折行的其他模板。
"""
part_fields = [
field for layout in ordered_layouts
for field in (layout.get('field_regions') or [])
if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number'
and isinstance(field.get('region'), dict)
]
if not part_fields:
return rows
part_start_offset = min(
offset for offset, layout in enumerate(ordered_layouts)
if any(field in (layout.get('field_regions') or []) for field in part_fields)
)
# 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段,
# 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。
if part_start_offset == 0:
return rows
bands = _group_visual_rows(glyphs)
main_fields = ordered_layouts[0].get('field_regions') or []
start_field = next(
(
field for field in main_fields
if isinstance(field, dict)
and str(field.get('field_code') or '') == line_start_field_code
and isinstance(field.get('region'), dict)
),
None,
)
start_region = (
_absolute_relative_region(table_bbox, start_field['region'])
if start_field is not None else None
)
for row_position, row in enumerate(rows):
current = str(row.fields.get('part_number') or '').strip()
if not current or not row.source_row_indices:
continue
record_start = min(row.source_row_indices)
record_end = (
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
if row_position + 1 < len(rows) else len(bands)
)
candidates: list[tuple[float, int, str]] = []
# 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述,
# 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步,
# 因为自适应重建可能已把后续候选 band 一并吸收到当前行。
expected_index = record_start + part_start_offset
scan_start = expected_index
for index in range(scan_start, record_end):
# 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因
# 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。
if index > record_start and start_region is not None:
start_raw = _text_in_horizontal_region(bands[index], start_region)
if is_valid_line_start_value(start_raw):
break
for field in part_fields:
region = _absolute_relative_region(table_bbox, field['region'])
raw = _text_in_horizontal_region(bands[index], region)
if raw.strip() == current:
continue
if not _is_structured_part_identifier(raw):
continue
score = _profile_field_band_score(
raw=raw, field_code='part_number',
extractor_key=str(field.get('extractor_key') or 'direct'),
)
score -= abs(index - expected_index) * .5
if re.search(r'\d', re.sub(r'\s+', '', raw)):
score += .5
candidates.append((score, index, raw))
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
row.fields['part_number'] = candidates[0][2]
elif len(candidates) > 1:
if candidates[0][0] > candidates[1][0] + .25:
row.fields['part_number'] = candidates[0][2]
else:
row.fields.pop('part_number', None)
row.issues.append('coordinate_profile_field_band_ambiguous:part_number')
return rows
def _text_in_region(
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
) -> str:
@@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
# segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。
segment.pop('segment_id', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
@@ -464,10 +464,13 @@ def _map_data_row(
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
return HtmlMappedRow(row_index=row_index, role='repeated_header')
joined = ' '.join(normalized)
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
# 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。
marker_joined = joined.lower()
if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined:
return HtmlMappedRow(row_index=row_index, role='deleted')
first = next((item for item in normalized if item), '')
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
# 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()):
return HtmlMappedRow(row_index=row_index, role='summary')
if _has_explicit_zero_quantity(row, columns=columns):
return HtmlMappedRow(row_index=row_index, role='deleted')
@@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
if not texts:
return False
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
return all(text in markers for text in texts)
# 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。
return all(text.lower() in markers for text in texts)
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
@@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
if field_code == 'reservation_id':
value = validated_reservation_id(text)
return {field_code: value} if value else {}
if field_code == 'uom':
# 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。
stripped = re.sub(r'\d+', '', text).strip()
return {field_code: stripped} if stripped else {}
return {field_code: text}
if extractor_key == 'temp_internal_parts':
resolved = resolve_composite_part_numbers(text)
@@ -1383,6 +1383,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature(
*, band_tokens: list[str], signature: dict[str, Any] | None,
) -> bool:
"""判断冻结表头带读到的 token 是否足以代表签名表头。
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。
"""
expected = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
if not expected or not band_tokens:
return False
observed = [str(token).casefold() for token in band_tokens]
matched = sum(1 for token in expected if token in observed)
return matched / len(expected) >= 0.5
def _observe_primary_table_header(
*,
glyph_tables: dict[str, Any],
@@ -1391,7 +1413,13 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。"""
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
@@ -1419,11 +1447,28 @@ def _observe_primary_table_header(
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
return tokens, centers, widths
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
# 固定带有效 → 直接沿用(对正常模板零影响)。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
candidates = [{
'bbox': primary_bbox,
'header_candidates': _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
),
}]
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
if selected is not None:
header, _ = selected
return (
[str(token).casefold() for token in header['header_tokens']],
header['column_centers'], header['column_width_ratios'],
)
return band_tokens, band_centers, band_widths
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
@@ -14,6 +14,15 @@ from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
LayoutBBox,
_absolute_relative_region,
_group_visual_rows,
_inside_horizontal_region,
_table_glyphs,
_text_in_horizontal_region,
coordinate_profile_character_candidates,
)
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
@@ -84,12 +93,14 @@ def validate_profile_parse_candidate(
fields=header_bound, glyphs=glyphs, page=page,
)
# [STEP 2] Line 字段覆盖
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
line_fields = [
field for table in profile.table_regions for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line'
]
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
line_coverage = _line_region_coverage_shift_tolerant(
profile=profile, glyphs=glyphs, page=page, layout=layout,
)
# [STEP 3] 明细行数启发式
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
@@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None:
return None
def _line_region_coverage_shift_tolerant(
*,
profile: OrderCoordinateProfile,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
layout: dict[str, Any],
) -> dict[str, Any]:
"""按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。
核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体
纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致
``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段
区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。
此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行
做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。
Args:
profile: 当前候选 Profile(含 table_regions)。
glyphs: 当前页冻结坐标字符。
page: 当前页尺寸。
layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。
Returns:
{coverage_ratio, empty_region_count, total_region_count}。
"""
if not profile.table_regions:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
line_fields = [
field for table in profile.table_regions for layout_item in table.line_layouts
for field in layout_item.field_regions if field.scope == 'line'
]
if not line_fields:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
primary_region = next(
(table for table in profile.table_regions if table.line_layouts), None,
)
raw_table = _locate_overlapping_raw_table(
primary_region=primary_region, layout=layout, page=page, profile=profile,
)
width, height = float(page['width']), float(page['height'])
table_region = primary_region.region.model_dump() if primary_region is not None else None
reference_page_frame = _reference_page_frame_mapping(profile, page)
reconstruction_page_bbox = {
'x0': 0.0, 'y0': 0.0,
'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width,
'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height,
}
# 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。
characters, _ = coordinate_profile_character_candidates(
table_region=table_region or {},
page_size=page, reference_page_frame=reference_page_frame,
page_characters=glyphs if isinstance(glyphs, list) else None,
table_characters=(
page_glyph_tables.get(raw_table.get('table_id'))
if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list)
else None
),
raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None),
table_id=(raw_table.get('table_id') if raw_table is not None else None),
page_no=1, coordinate_transform=None, allow_table_fallback=True,
)
if not isinstance(characters, list) or not characters:
return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox)
glyphs_in_table = _table_glyphs(characters, page_bbox)
visual_rows = _group_visual_rows(glyphs_in_table)
non_empty = 0
measurable = 0
for field in line_fields:
relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
if not isinstance(relative, dict):
continue
measurable += 1
absolute = _absolute_relative_region(page_bbox, relative)
if _region_is_covered(visual_rows=visual_rows, region=absolute):
non_empty += 1
total = measurable
return {
'coverage_ratio': non_empty / total if total else 1.0,
'empty_region_count': total - non_empty,
'total_region_count': total,
}
def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None:
"""读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。"""
reference = profile.reference_page_frames.get(1)
if reference is None:
return None
return reference.model_dump() if hasattr(reference, 'model_dump') else reference
def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any:
"""将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。"""
if isinstance(value, LayoutBBox):
return value
return LayoutBBox.model_validate(value)
def _locate_overlapping_raw_table(
*,
primary_region: Any,
layout: dict[str, Any],
page: dict[str, Any],
profile: OrderCoordinateProfile,
) -> dict[str, Any] | None:
"""在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。
命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取,
避免把无物理表的场景误判为已定位到明细表。
"""
if primary_region is None:
return None
reference_page_frame = _reference_page_frame_mapping(profile, page)
width, height = float(page['width']), float(page['height'])
projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width
projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height
if projection_width <= 0 or projection_height <= 0:
return None
relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region
if not isinstance(relative, dict):
return None
try:
absolute_region = {
'x0': float(relative['x0']) * projection_width,
'y0': float(relative['y0']) * projection_height,
'x1': float(relative['x1']) * projection_width,
'y1': float(relative['y1']) * projection_height,
}
except (KeyError, TypeError, ValueError):
return None
best: dict[str, Any] | None = None
best_overlap = 0.0
for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1:
continue
bbox = raw_table.get('bbox')
if not isinstance(bbox, dict):
continue
overlap_x = (
min(float(bbox.get('x1', 0)), absolute_region['x1'])
- max(float(bbox.get('x0', 0)), absolute_region['x0'])
)
overlap_y = (
min(float(bbox.get('y1', 0)), absolute_region['y1'])
- max(float(bbox.get('y0', 0)), absolute_region['y0'])
)
if overlap_x <= 0 or overlap_y <= 0:
continue
overlap_area = overlap_x * overlap_y
if overlap_area > best_overlap:
best_overlap = overlap_area
best = raw_table
return best
def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool:
"""判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。"""
for band in visual_rows:
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
if _text_in_horizontal_region(selected, region).strip():
return True
return False
def _estimate_line_count(
*,
profile: OrderCoordinateProfile,
@@ -1339,8 +1339,31 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE')
def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None:
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。"""
def promote_approved_suite_for_publish(
*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str,
actor_id: int | None = None,
) -> None:
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。
核心逻辑:
[STEP 1] 定位当前草稿 checksum 下已批准的盲测集;缺失时直接返回(生产调用方
已通过 assert_profile_publishable 门禁,此守卫仅防御测试夹具伪造凭证)。
[STEP 2] 同一 Profile 行重复发布相同内容时(如人工将已发布模板重置为草稿后
再次发布),发布 checksum 由规范化负载确定性复现,历史提升套件仍占用
(profile_id, profile_checksum) 唯一键。若占用者仍是有效发布凭证(approved 且
最近一次 Run 通过且 checksum 一致),则直接复用历史凭证:新草稿集转为
superseded 以保留其运行历史供审计,不再重写 checksum,避免唯一键冲突。
[STEP 3] 常规路径:重写套件与其 Run 的 checksum 为发布 checksum。
Args:
profile: 即将发布的 Profile ORM 记录(发布事务内调用,不自行提交)。
draft_checksum: 发布前草稿定义的规范化 checksum。
published_checksum: 本次发布冻结的正式 checksum。
actor_id: 触发发布的管理员主键,用于审计;允许为空。
Returns:
无返回值;套件状态变更随发布事务一并提交。
"""
suite = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
).one_or_none()
@@ -1348,6 +1371,31 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile,
# isolated lifecycle tests from fabricating a quality credential by monkeypatch.
if suite is None:
return
# [STEP 2] 唯一键占用检查:发布 checksum 相同意味着定义、Schema 与 adapter 证据
# 完全一致,历史凭证对本次发布同样有效,无需也不允许重写第二个套件。
occupant = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=published_checksum,
).one_or_none()
if occupant is not None and occupant.id != suite.id:
occupant_last_run = occupant.runs[-1] if occupant.runs else None
if (
occupant.status == 'approved' and occupant_last_run is not None
and occupant_last_run.status == 'passed'
and occupant_last_run.profile_checksum == published_checksum
):
suite.status = 'superseded'
_audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={
'suite_id': suite.id, 'reused_suite_id': occupant.id,
'reason_code': 'republish_identical_content',
})
return
# 占用者不是有效凭证(人工改动等异常数据):拒绝发布并给出可定位的错误码,
# 禁止静默覆盖或删除历史盲测证据。
raise ConflictError(
'Published checksum is already occupied by another test suite',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT',
details={'suite_id': occupant.id},
)
suite.profile_checksum = published_checksum
for run in suite.runs:
if run.profile_checksum == draft_checksum:
@@ -23,6 +23,7 @@ from app.models import (
ShippingOrderIntake,
ShippingOrderSnapshot,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.business_fingerprint import (
CONTENT_FINGERPRINT_VERSION,
@@ -40,19 +41,35 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
lifecycle = str(get('lifecycle_status', '') or '').strip().lower()
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
return 'closed'
upload = str(get('upload_status', '') or '').strip().lower()
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'):
upload = None
try:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if not isinstance(task, dict) and has_verified_upload_success(task):
upload = 'uploaded'
except Exception:
upload = None
if upload == 'uploaded':
return 'completed'
return 'active'
def is_irreversible_task(task: ShippingNotice) -> bool:
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
upload_status = str(task.upload_status or '').strip().lower()
return upload_status in {'uploaded', 'succeeded', 'success'}
try:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return has_verified_upload_success(task)
except Exception:
return False
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
if getattr(task, 'order_task_id', None) else None
)
return {
'task_no': task.task_no,
'document_version': int(task.document_version or 1),
@@ -60,14 +77,29 @@ def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: lis
'matched_fields': list(matched_fields),
'lifecycle': classify_task_lifecycle(task),
'created_at': utc_iso(task.created_at),
'content_fingerprint': task.content_fingerprint,
'content_fingerprint_version': task.content_fingerprint_version,
'content_fingerprint': getattr(candidate, 'content_fingerprint', None),
'content_fingerprint_version': getattr(candidate, 'content_fingerprint_version', None),
}
def _task_content_fingerprint(task: ShippingNotice) -> tuple[str | None, str | None]:
"""从建单来源 Candidate 读取内容指纹;正式 Notice 不再保存该投影。"""
if not getattr(task, 'order_task_id', None):
return None, None
candidate = (
db.session.query(ShippingOrderCandidate.content_fingerprint, ShippingOrderCandidate.content_fingerprint_version)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
return (candidate[0], candidate[1]) if candidate else (None, None)
def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]:
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
return []
proposed = {
@@ -158,10 +190,13 @@ def detect_duplicates_for_intake(
if content_hash:
hash_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
ShippingOrderTask.user_id == int(intake.user_id),
FileAsset.content_hash == content_hash,
ShippingOrderTask.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(10)
@@ -182,10 +217,12 @@ def detect_duplicates_for_intake(
if fingerprint and strength in {'strong', 'medium'}:
fp_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingOrderTask.user_id == int(intake.user_id),
ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingOrderCandidate.fingerprint_version == version,
)
.order_by(ShippingNotice.id.desc())
.limit(20)
@@ -206,12 +243,13 @@ def detect_duplicates_for_intake(
if matches and status == 'none':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
@@ -229,11 +267,13 @@ def detect_duplicates_for_intake(
# 弱指纹:仅标记疑似,不按 active 强阻断
fp_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active',
ShippingOrderTask.user_id == int(intake.user_id),
ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingOrderCandidate.fingerprint_version == version,
ShippingOrderTask.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(5)
@@ -498,11 +538,10 @@ def detect_duplicates_for_candidate(
if content_hash:
hash_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), FileAsset.content_hash == content_hash, ShippingOrderTask.lifecycle_status == 'active')
)
if skipped_ids:
hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -522,11 +561,9 @@ def detect_duplicates_for_candidate(
if fingerprint and strength in {'strong', 'medium'}:
fp_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version)
)
if skipped_ids:
fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -545,12 +582,13 @@ def detect_duplicates_for_candidate(
if matches and status == 'none':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
@@ -564,12 +602,9 @@ def detect_duplicates_for_candidate(
elif fingerprint and strength == 'weak' and status == 'none':
weak_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active',
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version, ShippingOrderTask.lifecycle_status == 'active')
)
if skipped_ids:
weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -570,7 +570,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'),
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
@@ -613,7 +613,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'),
'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'),
}
@@ -36,7 +36,7 @@ ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'consta
ALLOWED_ROW_MODES = {'header', 'line'}
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
ALLOWED_SYSTEM_FACTS = {
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'export_sequence',
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'notice_line_no',
}
+212 -59
View File
@@ -4,7 +4,9 @@ services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
"""
@@ -29,16 +31,55 @@ from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
ShippingOrderTask,
ShippingCustomer,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).distinct().all()
if row[0]
]
return codes[0] if len(codes) == 1 else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
).distinct().all()
]
return ids[0] if len(ids) == 1 else None
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
"""
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
@@ -73,16 +114,7 @@ def _storage_root() -> Path:
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
if notice.order_snapshot_id:
return notice
if notice.order_task_id:
source = ShippingNotice.query.filter(
ShippingNotice.order_task_id == int(notice.order_task_id),
ShippingNotice.order_snapshot_id.isnot(None),
).order_by(ShippingNotice.id.asc()).first()
if source is not None:
return source
"""返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。"""
return notice
@@ -90,7 +122,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
@@ -122,9 +156,10 @@ def _system_fact(
task: ShippingNotice,
key: str,
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
) -> Any:
"""
@@ -133,18 +168,16 @@ def _system_fact(
Args:
task: 发货任务。
key: 系统事实键;仅允许白名单内键。
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
Returns:
对应系统事实值;未知键返回 None。
"""
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'warehouse_id': notice_line_warehouse_id,
'inventory_source_code': _notice_source_code(task),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
'notice_line_no': notice_line_no,
}
return values.get(key)
@@ -164,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo
)
def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None:
"""
从表头可写的 Notice 行推导唯一 Warehouse ID。
核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头,
多库位冲突时失败,避免把某一行的库位误写到整单表头。
Args:
notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。
Returns:
唯一非空库位码;全部为空时返回 None。
Raises:
ValueError: 多行存在多个不同库位。
"""
warehouses = {
str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper()
for line in (notice_lines or [])
if str(getattr(line, 'inventory_warehouse_id', None) or '').strip()
}
if len(warehouses) > 1:
raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头')
if len(warehouses) == 1:
return next(iter(warehouses))
return None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
@@ -191,9 +252,11 @@ def _format_value(value: Any, formatter: str) -> Any:
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
header_values: dict[str, Any] | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> Any:
@@ -201,9 +264,7 @@ def _mapping_value(
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。
Args:
mapping: 已发布模板映射项。
@@ -211,7 +272,6 @@ def _mapping_value(
order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns:
@@ -224,13 +284,7 @@ def _mapping_value(
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
value = notice_line_no
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -238,13 +292,12 @@ def _mapping_value(
elif kind == 'system_fact':
value = _system_fact(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
notice_no=notice_no,
notice_line_no=notice_line_no,
notice_line_warehouse_id=notice_line_warehouse_id,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
else:
value = key
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
@@ -263,6 +316,50 @@ def _match_text(value: Any) -> str:
return str(value).strip().casefold()
def _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines: list[dict[str, Any]],
*,
inventory_field_keys: list[str],
wanted_keys: set[tuple[str, ...]],
) -> list[dict[str, Any]]:
"""
仅保留与本单导出行 match_keys 命中的库存行。
核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入
逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。
Args:
inventory_lines: 活动库存快照行。
inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。
wanted_keys: 本单导出行规范化后的键元组集合。
Returns:
子集库存行;无候选时为空列表。
"""
if not inventory_lines or not inventory_field_keys or not wanted_keys:
return []
return [
row for row in inventory_lines
if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys
]
def _wanted_order_match_keys(
order_lines: list[dict[str, Any]],
*,
order_field_ids: list[str],
) -> set[tuple[str, ...]]:
"""从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。"""
wanted: set[tuple[str, ...]] = set()
if not order_lines or not order_field_ids:
return wanted
for order_line in order_lines:
key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids)
if all(key):
wanted.add(key)
return wanted
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
@@ -447,13 +544,20 @@ def _filename(
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
customer_short_code = ''
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
facts = customer_resolution_facts(owner)
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
customer_short_code = str(getattr(customer, 'short_code', None) or '')
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
'source_code': task.inventory_source_code or '',
'source_code': _notice_source_code(task) or '',
'ts': now,
'date': now[:8],
'customer_short_code': task.customer_short_code_snapshot or '',
'customer_short_code': customer_short_code,
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
}
@@ -474,7 +578,7 @@ def _input_checksum(
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task),
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id,
}
@@ -499,24 +603,22 @@ def generate_shipment_excel(
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(task.inventory_source_code or '').strip().upper()
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
# [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None,
# 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。
first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).limit(1).first()
source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else ''
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
source = None
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
template = source.excel_template
@@ -528,13 +630,10 @@ def generate_shipment_excel(
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
# resolve it only after Reservation ID + Part Number matches. This requirement
# applies only when the published template actually consumes that system fact.
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
@@ -590,7 +689,7 @@ def generate_shipment_excel(
)
except ConflictError:
raise
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
# [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。
line_values = []
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
if line.id not in available_line_ids:
@@ -598,12 +697,40 @@ def generate_shipment_excel(
row = dict(values)
row['__order_line_index'] = source_index
line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
# [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part)
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all()
} if match_field_ids else {}
order_field_ids: list[str] = []
inventory_field_keys: list[str] = []
for item in match_keys:
if not isinstance(item, dict):
continue
inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip())
if not inv_key:
continue
order_field_ids.append(str(item.get('order_field_id') or ''))
inventory_field_keys.append(inv_key)
if order_field_ids and inventory_field_keys:
wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids)
inventory_lines = _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines,
inventory_field_keys=inventory_field_keys,
wanted_keys=wanted_keys,
)
release_overrides_by_line = _release_overrides_for_export_lines(
line_values=line_values,
release_overrides_by_source_line=release_overrides_by_source_line,
@@ -656,15 +783,32 @@ def generate_shipment_excel(
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
# [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
header_warehouse_id: str | None = None
header_warehouse_resolved = False
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
# PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。
mapping_warehouse_id = None
if _template_requires_system_warehouse_id([mapping]):
if not header_warehouse_resolved:
header_warehouse_id = _unique_notice_warehouse_id(notice_lines)
header_warehouse_resolved = True
if not header_warehouse_id:
raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头')
mapping_warehouse_id = header_warehouse_id
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
notice_line_no=None,
notice_line_warehouse_id=mapping_warehouse_id,
field_id_by_code=field_id_by_code,
)
continue
@@ -675,7 +819,16 @@ def generate_shipment_excel(
ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
notice_line_no=(
int(notice_lines[index].line_no)
if index < len(notice_lines) and notice_lines[index].line_no is not None
else None
),
notice_line_warehouse_id=(
notice_lines[index].inventory_warehouse_id
if index < len(notice_lines)
else None
),
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
@@ -691,7 +844,7 @@ def generate_shipment_excel(
artifact_no=artifact_no, task_id=task.id,
template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id),
@@ -37,7 +37,8 @@ def _select_tasks(
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None or (
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
if not isinstance(task, ShippingNotice) or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
):
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
@@ -61,7 +62,6 @@ def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExpo
artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
ShippingExportArtifact.file_path == task.export_file_path,
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
if artifact is not None:
result[int(task.id)] = [artifact]
@@ -317,3 +317,60 @@ def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[
'warnings': warnings,
'can_publish': not blocked,
}
def _definition_field_code_map(definition: dict[str, Any] | None) -> dict[str, str]:
"""提取版本定义中 field_id → field_code 映射,用于字段语义键跨版本一致性校验。"""
if not isinstance(definition, dict):
return {}
result: dict[str, str] = {}
for item in (definition.get('fields') or []):
if not isinstance(item, dict):
continue
field_id = str(item.get('field_id') or '').strip()
field_code = str(item.get('field_code') or '').strip()
if field_id and field_code:
result[field_id] = field_code
return result
def analyze_published_field_code_changes(
previous_definition: dict[str, Any] | None,
next_definition: dict[str, Any] | None,
) -> dict[str, Any]:
"""
已发布 field_code 不可变门禁:同一 field_id 不应在下一发布版本中更换 field_code。
核心逻辑:只比较上一已发布版本与当前草稿「同一 field_id」的 field_code 是否变化;
同一 field_code 漂移到新 field_id(废弃旧字段 + 新建)属于合法路径,不阻断。
仅在语义键被重命名时阻断,要求走「退役 + 新建」而非原地改名,保证 field_code 是
跨版本稳定引用锚点(供身份识别 resolver 等按语义键匹配)。
Args:
previous_definition: 上一已发布版本 definition;无则视为首次发布,不校验。
next_definition: 即将发布的草稿 definition。
Returns:
含 blocked、changed(field_id / previous_field_code / next_field_code)与
changed_field_ids 的字典;changed 为空时 can_publish=True。
"""
if previous_definition is None:
return {'blocked': False, 'changed': [], 'changed_field_ids': [], 'can_publish': True}
previous_map = _definition_field_code_map(previous_definition)
next_map = _definition_field_code_map(next_definition)
changed: list[dict[str, Any]] = []
for field_id in sorted(set(previous_map) & set(next_map)):
previous_code = previous_map[field_id]
next_code = next_map[field_id]
if previous_code != next_code:
changed.append({
'field_id': field_id,
'previous_field_code': previous_code,
'next_field_code': next_code,
})
return {
'blocked': bool(changed),
'changed': changed,
'changed_field_ids': [item['field_id'] for item in changed],
'can_publish': not changed,
}
@@ -16,8 +16,9 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.tool_common import task_event_task_id
def complete_freight_cancellation(
@@ -59,11 +60,16 @@ def complete_freight_cancellation(
old.voided_at = datetime.utcnow()
old.voided_by_id = int(actor_id)
old.void_reason = 'freight_cancellation_completed'
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required':
new.lifecycle_status = 'active'
new.pending_human_reason = None
# Notice 不再承载旧工作流阻断字段;解除修订阻断时更新其 OT 生命周期,
# 由 OT 的 Gate/状态投影重新计算当前工作面。
new_owner = (
db.session.get(ShippingOrderTask, int(new.order_task_id))
if new.order_task_id is not None else None
)
if new_owner is not None and new_owner.status == 'blocked':
new_owner.status = 'processing'
db.session.add(ShippingTaskEvent(
task_id=old.id,
task_id=task_event_task_id(old),
event_type='freight_cancellation_completed',
actor_id=actor_id,
detail_json={
@@ -74,7 +80,7 @@ def complete_freight_cancellation(
},
))
db.session.add(ShippingTaskEvent(
task_id=new.id,
task_id=task_event_task_id(new),
event_type='supersession_unblocked',
actor_id=actor_id,
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
@@ -109,12 +115,19 @@ def complete_freight_cancellation(
def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
"""构造取消处置前后快照(白名单字段)。"""
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
artifact = latest_export_artifact(task)
owner = (
db.session.get(ShippingOrderTask, int(task.order_task_id))
if task.order_task_id is not None else None
)
return {
'task_no': str(task.task_no),
'lifecycle_status': str(task.lifecycle_status or ''),
'export_file_name': task.export_file_name,
'export_file_name': getattr(artifact, 'file_name', None),
'void_reason': task.void_reason,
'pending_human_reason': task.pending_human_reason,
'owner_lifecycle_status': getattr(owner, 'lifecycle_status', None),
'owner_void_reason': getattr(owner, 'void_reason', None),
}
@@ -150,11 +163,10 @@ def mark_cancelled_task_readonly(
if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}:
task.lifecycle_status = 'pending_void'
task.void_reason = reason_text
task.pending_human_reason = 'pending_void'
# co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。
after = _task_cancel_snapshot(task)
db.session.add(ShippingTaskEvent(
task_id=int(task.id),
task_id=task_event_task_id(task),
event_type='task_pending_void',
actor_id=int(actor_id),
detail_json={
File diff suppressed because it is too large. Load diff
@@ -113,6 +113,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
"workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。",
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
"workflow.fulfillment.inventory_preparation_failed": "库存准备失败。请人工重试或上传库存文件后再继续。",
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
"workflow.fulfillment.generate_running": "正在生成发货 Excel",
@@ -238,6 +239,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
"workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.",
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
"workflow.fulfillment.inventory_preparation_failed": "Inventory preparation failed. Retry manually or upload an inventory file before continuing.",
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
"workflow.fulfillment.generate_running": "Generating shipment Excel.",
@@ -363,6 +365,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
"workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก",
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
"workflow.fulfillment.inventory_preparation_failed": "การเตรียมสต็อกล้มเหลว โปรดลองด้วยตนเองหรืออัปโหลดไฟล์สต็อกก่อนดำเนินการต่อ",
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
"workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel",
@@ -86,7 +86,7 @@ def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[Shipping
def definition_context_field_is_compatible(
definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str,
) -> bool:
"""校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。"""
"""字段绑定主谓词:先认定同一 UUID 即同字段;否则按 field_code + scope + value_type 判断语义兼容承接规则快照。"""
expected_id = str(definition.get('context_field_id') or '')
if actual_field_id == expected_id:
return True
@@ -111,15 +111,19 @@ def definition_context_field_is_compatible(
def _resolved_context_field_id(
definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]],
) -> str | None:
"""优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。"""
"""按 field_config.field_code 语义键定位当前字段;UUID 直配仅保留为同字段快速命中。
规则定义以 field_code(不随 Schema 版本重建而漂移)作为跨版本稳定引用锚点;
UUID 直接命中只作为无漂移时的快捷路径,避免 Schema 重发布打断识别链路。
旧快照若缺少 field_code,则回退到 UUID 直配路径,保证向后兼容。
"""
if extraction is not None:
for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id
expected_id = str(definition.get('context_field_id') or '')
if expected_id in header_values:
return expected_id
if extraction is None:
return None
for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id
return None
@@ -12,8 +12,6 @@ import hashlib
import json
import re
import uuid
from pathlib import Path
import urllib.request
from datetime import datetime
from typing import Any
@@ -112,19 +110,6 @@ def _published_schema_version() -> ShippingOrderSchemaVersion | None:
def _published_field_config(field_id: str) -> dict[str, Any] | None:
"""读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。"""
# #region debug-point A/B/C/E:published-schema-state
try:
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all()
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
published = _published_schema_version()
return next((
item for item in ((published.definition_json if published else {}) or {}).get('fields', [])
@@ -193,7 +193,7 @@ def _collect_order_line_candidates(
line_codes = list(task_level_source_codes_ordered)
line_projections.append({
'line_key': f'{task.id}:{line_no}',
# 该阶段只产生候选投影;冻结档建立后由 snapshot_line_id 作为唯一行身份。
'line_index': idx,
'line_no': line_no,
'source_line_no': source_line_no,
@@ -276,19 +276,13 @@ def _invalidate_task_candidate_outputs(
ShippingUploadAttempt,
)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.upload_status = None
payload = dict(task.step_payload_json or {})
payload.pop('line_inventory_resolutions', None)
payload.pop('resolved_ok_source_codes', None)
payload.pop('excel_binding_source_code', None)
payload.pop('multi_source_excel_block', None)
task.step_payload_json = payload
if task.__class__.__name__ != 'ShippingOrderTask':
task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}}
(
session.query(ShippingNoticeLineInventoryMatch)
@@ -306,12 +300,18 @@ def _invalidate_task_candidate_outputs(
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id == int(task.id),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
notice_ids = [
int(row.id)
for row in session.query(ShippingNotice.id).filter(
ShippingNotice.order_task_id == int(task.id),
).all()
]
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id.in_(notice_ids),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
).all()
] if notice_ids else []
if artifact_ids:
session.query(ShippingExportArtifact).filter(
ShippingExportArtifact.id.in_(artifact_ids),
@@ -358,6 +358,7 @@ def freeze_candidates_for_task(
execution_id: int | None = None,
frozen_by_id: int | None = None,
line_projections: list[dict[str, Any]] | None = None,
preserve_empty_line_candidates: bool = False,
session: Session | None = None,
) -> CandidateFreezeResult:
"""
@@ -370,7 +371,6 @@ def freeze_candidates_for_task(
[STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。
[STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。
[STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。
[STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。
Args:
task: 已 flush 的 ShippingNotice(有 id 字段)。
@@ -380,6 +380,8 @@ def freeze_candidates_for_task(
execution_id: 可选的 ProcessExecution 绑定 ID。
frozen_by_id: 人工覆盖冻结时的操作人 ID。
line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。
preserve_empty_line_candidates: 仅人工逐项选源时为 True;保留尚未选择源的
Snapshot 行为空列表,使 Gate 能继续阻断而不会误触发整单库存准备。
session: 可选的 SQLAlchemy Session(缺省用 db.session)。
Returns:
@@ -421,18 +423,14 @@ def freeze_candidates_for_task(
continue
codes_raw = item.get('candidate_inventory_source_codes') or []
codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()]
if not codes:
if not codes and not preserve_empty_line_candidates:
codes = list(task_source_codes_ordered)
line_index = item.get('line_index')
try:
line_no = int(item.get('line_no') or 0)
except (TypeError, ValueError):
line_no = 0
if line_no <= 0:
try:
line_no = int(line_index) + 1
except (TypeError, ValueError):
line_no = len(signatures) + 1
raise ValueError('候选行缺少持久化 line_no,禁止从 line_index 派生项次')
signatures.append((
line_no,
str(item.get('source_line_no') or '').strip() or None,
@@ -599,22 +597,22 @@ def freeze_candidates_for_task(
if getattr(task, 'id', None) is not None:
task.active_inventory_candidate_set_id = int(new_set.id)
# 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
# 人工逐项选源正由当前 GateAttempt 执行时,不能把它自己 supersede,
# 否则选源已落库但 Attempt 无法完成。该 Execution 只更新候选版本,仍停在
# routing Gate;所有项次选完后才进入库存准备。其他重冻结仍取消旧链。
current_execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None and int(current_execution_id or 0) == int(execution_id):
from app.models import ShippingProcessExecution
supersede_auto_progress_for_candidate_refreeze(task)
current_execution = session.get(ShippingProcessExecution, int(execution_id))
if current_execution is not None:
current_execution.candidate_set_id = int(new_set.id)
else:
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
# [STEP 5] 回填 task 字段(幂等覆盖)
task.inventory_source_status = 'candidates_frozen'
task.inventory_source_method = (
'manual_override_freeze' if frozen_by_id is not None
else (adjudication.method or 'rule_evaluation_freeze')
)
task.inventory_source_config_version = config_version
task.inventory_routing_fingerprint = routing_fingerprint
# 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节
supersede_auto_progress_for_candidate_refreeze(task)
return CandidateFreezeResult(
candidate_set_id=new_set.id,
@@ -624,3 +622,204 @@ def freeze_candidates_for_task(
manifest_snapshot_sha256=manifest_sha256,
set_version=set_version,
)
def freeze_manual_line_source_selection(
task: ShippingNotice,
*,
line_no: int,
source_code: str,
actor_id: int | None,
reason: str | None,
execution_id: int | None,
session: Session | None = None,
) -> tuple[CandidateFreezeResult, bool]:
"""
将通知准备的人工选源冻结为新的 CandidateSet 版本。
核心逻辑:以冻结 Snapshot 的全量 line_no 为骨架,继承当前候选行的选择后仅替换目标项次。
没有自动候选时也会先创建全量 CandidateLine;未选源项保持空数组,只有每一项都有源时才返回
``all_lines_selected=True``,调用方据此允许进入库存准备/RPA。
Args:
task: 已冻结订单对应的 OT。
line_no: 用户选择库存源的 Snapshot 项次,必须存在。
source_code: 已启用库存源编码。
actor_id: 操作人,用于候选源与候选行审计。
reason: 人工选择原因。
execution_id: 当前流程 Execution,用于绑定候选版本。
session: 可选数据库会话。
Returns:
(CandidateFreezeResult, all_lines_selected)。
Raises:
ValueError: OT 未冻结 Snapshot 或项次不存在。
"""
session = session or db.session
snapshot = (
session.query(ShippingOrderSnapshot)
.filter(ShippingOrderSnapshot.task_id == int(task.id))
.one_or_none()
)
if snapshot is None:
raise ValueError('人工选源前必须先冻结订单 Snapshot')
snapshot_lines = sorted(list(snapshot.lines or []), key=lambda row: int(row.line_no))
wanted_line = int(line_no)
if not any(int(row.line_no) == wanted_line for row in snapshot_lines):
raise ValueError('未找到该订单项次')
active_set = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if task.active_inventory_candidate_set_id is not None else None
)
existing_codes = {
int(row.line_no): [str(code).strip().upper() for code in (row.source_codes_json or []) if str(code).strip()]
for row in (active_set.lines if active_set is not None else [])
}
line_projections: list[dict[str, Any]] = []
for row in snapshot_lines:
current_line_no = int(row.line_no)
codes = [source_code] if current_line_no == wanted_line else existing_codes.get(current_line_no, [])
line_projections.append({
'line_no': current_line_no,
'source_line_no': str(row.line_no),
'part_number': row.part_number,
'reservation_id': row.reservation_id,
'candidate_inventory_source_codes': codes,
})
source_codes = []
for projection in line_projections:
for code in projection['candidate_inventory_source_codes']:
if code not in source_codes:
source_codes.append(code)
adjudication = InventorySourceAdjudication(
status='manual',
method='manual_line_selection',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
candidates=[{'source_code': code} for code in source_codes],
evidence=[{'line_no': wanted_line, 'source_code': source_code, 'reason': reason or '人工指定库存源'}],
reason='manual_line_selection',
)
result = freeze_candidates_for_task(
task,
adjudication=adjudication,
execution_id=execution_id,
frozen_by_id=actor_id,
line_projections=line_projections,
preserve_empty_line_candidates=True,
session=session,
)
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
source_notice: ShippingNotice | None = None,
) -> CandidateFreezeResult | None:
"""
按波次自身行重跑库存源路由并冻结候选集(设计 D8:波次不再继承首通知源)。
【AI 触发时机】建波次通知(post_ot_fulfillment_wave)且在写入波次 ShippingNoticeLine 后调用;
仅当波次行需要独立路由(不同行可能不同仓)时使用。
核心逻辑:以订单级 header(field_id 值)+ 波次行 ShippingNoticeLine.field_values_json
逐行调用 ``evaluate_inventory_source_rules_for_field_values(scope='line')`` 得到行级候选;
以全波次行候选并集作为任务级候选集,调用 ``freeze_candidates_for_task`` 冻结 Set/Source/Line
(候选快照已在本地,后续匹配不重复 RPA)。
Args:
notice: 已 flush 且已写入波次行的波次通知。
source_notice: 订单首个冻结通知(提供订单级 header 事实);缺省用 notice。
Returns:
CandidateFreezeResult;无任何波次行候选时返回 None(交由无候选阻断,不冻结)。
"""
from app.models.shipping_notice_line import ShippingNoticeLine
from app.services.shipping_notice.export import order_field_id_values
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules_for_field_values,
)
src = source_notice or notice
try:
header, _full_lines = order_field_id_values(src)
except ValueError:
header = {}
wave_lines = (
ShippingNoticeLine.query.filter_by(notice_id=int(notice.id)).order_by(ShippingNoticeLine.position).all()
if getattr(notice, 'id', None) is not None
else []
)
# [回退] 与首单路径一致(_collect_order_line_candidates):行级无规则命中时回退到订单级 task 候选集,
# 避免波次行「一条规则都不命中」时被算成无候选而卡死。
task_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header, scope='task',
)
task_source_codes = [str(c or '').strip().upper() for c in (getattr(task_result, 'source_codes', None) or []) if str(c or '').strip()]
line_projections: list[dict[str, Any]] = []
task_codes: list[str] = []
seen: set[str] = set()
for idx, line in enumerate(wave_lines):
line_values = dict(getattr(line, 'field_values_json', None) or {})
line_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header,
line_field_values=line_values,
scope='line',
)
resolved = str(getattr(line_result, 'status', '') or '') == 'resolved' and bool(getattr(line_result, 'source_codes', None))
if resolved:
codes = [str(c or '').strip().upper() for c in (getattr(line_result, 'source_codes', None) or []) if str(c or '').strip()]
else:
codes = list(task_source_codes)
if not codes:
codes = list(task_source_codes)
for code in codes:
if code not in seen:
seen.add(code)
task_codes.append(code)
line_projections.append({
'line_index': idx,
'line_no': idx + 1,
'source_line_no': str(getattr(line, 'line_no', None) or '').strip() or None,
'part_number': str(getattr(line, 'part_number', None) or '').strip() or None,
'reservation_id': str(getattr(line, 'reservation_id', None) or '').strip() or None,
'candidate_inventory_source_codes': codes,
'selection_mode': 'line_rule' if resolved else 'task_fallback',
'routing_status': str(getattr(line_result, 'status', '') or ''),
'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()),
})
if not task_codes:
return None
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
_candidate,
compute_routing_fingerprint,
extract_routing_context,
)
candidates = []
for code in task_codes:
src_cfg = get_database_inventory_source(code)
if src_cfg:
candidates.append(_candidate(src_cfg))
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='wave_line_routing',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(notice)),
candidates=candidates,
)
return freeze_candidates_for_task(
notice,
adjudication=adjudication,
line_projections=line_projections,
)
@@ -2,9 +2,9 @@
services/shipping_notice/inventory_candidate_projection.py
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
ShippingTaskInventoryRpaAttempt。
逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
"""
@@ -21,7 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
@@ -55,7 +55,7 @@ def _normalized_codes(codes: list[Any] | None) -> list[str]:
def _candidate_set_filter(
task: ShippingNotice,
task: ShippingOrderTask,
*,
include_drafts: bool = False,
session: Session | None = None,
@@ -83,14 +83,14 @@ def _candidate_set_filter(
def get_active_candidate_set(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
"""
读取正式 Task 当前 frozen CandidateSet。
核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id;
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
"""
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
@@ -107,7 +107,7 @@ def get_active_candidate_set(
def get_active_candidate_sources(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
@@ -129,7 +129,7 @@ def get_active_candidate_sources(
def get_active_candidate_lines(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
@@ -150,8 +150,51 @@ def get_active_candidate_lines(
return list(rows)
def active_inventory_runtime_facts(
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> dict[str, Any]:
"""
读取通知准备的当前运行事实,替代 OT 上的库存路由和快照投影列。
核心逻辑:库存源只读当前 CandidateSet/Source;库存文件只读 active Link;配置版本
取 CandidateSource 的冻结版本,不能回读 Task 的可变历史字段。
Args:
task: 当前订单任务。
session: 可选数据库会话。
Returns:
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
"""
from app.models import ShippingTaskInventoryLink
sess = _session(session)
candidate_set = get_active_candidate_set(task, session=sess)
sources = get_active_candidate_sources(task, session=sess)
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()]
link = (
sess.query(ShippingTaskInventoryLink)
.filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True))
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
if getattr(task, 'id', None) is not None else None
)
return {
'candidate_set': candidate_set,
'candidate_set_id': getattr(candidate_set, 'id', None),
'source_codes': source_codes,
'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None,
'active_link': link,
'inventory_file_id': getattr(link, 'inventory_file_id', None),
'inventory_file': getattr(link, 'inventory_file', None),
}
def get_candidate_set_by_version(
task: ShippingNotice,
task: ShippingOrderTask,
version: int,
*,
include_drafts: bool = False,
@@ -271,7 +314,7 @@ def _candidate_lines_for_set(
def build_inventory_candidate_blocking_reason(
code: str,
*,
task: ShippingNotice,
task: ShippingOrderTask,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""构造统一 blocking_reason DTO。"""
@@ -293,7 +336,7 @@ def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rule
}
def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
"""查询任务下每个候选源的最新 Attempt 摘要。"""
task_no = str(getattr(task, 'task_no', '') or '').strip()
if not task_no or not source_codes:
@@ -346,7 +389,7 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
return prepared, pending, failed
def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
"""读取任务当前生效的行级匹配事实。"""
if getattr(task, 'id', None) is None:
return []
@@ -367,7 +410,7 @@ def _current_match_rows(task: ShippingNotice, *, session: Session | None = None)
def project_inventory_candidate_detail(
task: ShippingNotice,
task: ShippingOrderTask,
*,
version: str | int = 'current',
session: Session | None = None,
@@ -426,7 +469,7 @@ def project_inventory_candidate_detail(
def project_inventory_candidate_facts(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
include_history: bool = False,
@@ -493,14 +536,20 @@ def project_inventory_candidate_facts(
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
'id': int(row.id),
'line_key': str(row.line_key or ''),
'snapshot_line_id': int(row.snapshot_line_id),
'line_no': int(row.line_no),
'line_index': getattr(row, 'line_index', None),
'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'),
'candidate_set_id': getattr(row, 'candidate_set_id', None),
'candidate_set_version': getattr(row, 'candidate_set_version', None),
'candidate_line_id': getattr(row, 'candidate_line_id', None),
'allowed_source_codes_snapshot': allowed_codes,
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
'resolved_inventory_source_code': (
getattr(row, 'inventory_source_code', None)
or (allowed_codes[0] if len(allowed_codes) == 1 else None)
),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
@@ -3,7 +3,9 @@ services/shipping_notice/inventory_file_store.py
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。
"""
from __future__ import annotations
@@ -19,7 +21,15 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingTaskEvent,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
@@ -29,10 +39,14 @@ from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
def _can_relink_inventory(task: ShippingNotice) -> bool:
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return not has_verified_upload_success(task) \
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
@@ -129,11 +143,28 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
"""读取任务当前 active link 指向的库存快照。"""
if task.id is None:
"""
读取任务当前 active link 指向的库存快照。
核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入
``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。
Args:
task: OT 或已绑定 ``order_task_id`` 的正式 Notice。
Returns:
当前有效库存文件;无 active Link 时返回 None。
"""
# [STEP] Link 归属 OT:Notice.id 与 OT.id 不同,禁止误用 Notice 主键查 Link。
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
ShippingTaskInventoryLink.query.filter_by(
task_id=int(task_id),
is_active=True,
invalidated_at=None,
)
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
)
@@ -162,24 +193,33 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] |
return path, filename
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
cached_rows = [
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_rows:
return cached_rows, {'source': 'inventory_file_cache'}
rows, column_meta = parse_inventory_snapshot_file(inv_file)
rows = [row for row in rows if isinstance(row, dict)]
if rows:
inv_file.inventory_lines_json = rows
inv_file.line_count = len(rows)
db.session.flush()
return rows, column_meta
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
"""读取任务活动库存文件的行事实;解析失败由调用方 Gate 转为可解释状态。"""
inv_file = active_inventory_file_for_task(task)
if inv_file and isinstance(inv_file.inventory_lines_json, list):
rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
if not rows and Path(inv_file.storage_path).is_file():
try:
reparsed, _meta = parse_inventory_snapshot_file(inv_file)
if reparsed:
inv_file.inventory_lines_json = reparsed
inv_file.line_count = len(reparsed)
db.session.flush()
rows = reparsed
except Exception: # noqa: BLE001
# 解析失败时保留原快照,交由上层 Gate 报告可解释错误。
pass
if inv_file is None:
return []
try:
rows, _column_meta = read_inventory_file_lines(inv_file)
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
except (OSError, ValueError, AppError):
return []
def resolve_inventory_lines_for_execution(
@@ -188,22 +228,42 @@ def resolve_inventory_lines_for_execution(
legacy_payload_lines: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""
解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。
解析库存匹配与导出的统一运行输入。
核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源
ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File;
否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。
Args:
task: 当前正式发货通知。
task: 当前正式发货通知 / OT。
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
Returns:
本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
"""
# [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
from app.services.shipping_notice.stp_line_inventory_match import (
prepare_candidate_inventory_lines,
)
if len(task_frozen_inventory_source_codes(task)) >= 1:
prep = prepare_candidate_inventory_lines(task)
if prep.get('status') == 'ready':
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
if rows:
return rows
# [STEP 2] 单源 / 无冻结:活动 Link 文件是行事实。
if active_inventory_file_for_task(task) is not None:
return active_inventory_lines_for_task(task)
if isinstance(legacy_payload_lines, list):
rows = [row for row in legacy_payload_lines if isinstance(row, dict)]
if rows:
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
return []
def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
@@ -214,6 +274,60 @@ def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
return False
def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
"""判断 OT 是否已绑定一份有效且已解析的库存文件。"""
inv_file = active_inventory_file_for_task(task)
return bool(
inv_file is not None
and str(inv_file.snapshot_status or '').strip().lower() == 'ready'
and inv_file.invalidated_at is None
and int(inv_file.line_count or 0) > 0
)
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
"""读取 OT 当前有效的行级库存匹配事实。"""
task_id = getattr(task, 'id', None)
if task_id is None:
return []
return ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task_id), is_current=True,
).all()
def inventory_matches_complete_for_task(task: ShippingNotice) -> bool:
"""判断当前 Match 是否已覆盖冻结订单全部项次且不在准备中。"""
task_id = getattr(task, 'id', None)
snapshot_id = getattr(task, 'order_snapshot_id', None)
if task_id is None or not snapshot_id:
return False
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is None or not snapshot.lines:
return False
matches = {
int(row.snapshot_line_id): row
for row in current_inventory_matches_for_task(task)
if row.snapshot_line_id is not None
}
expected = {int(line.id) for line in snapshot.lines}
return set(matches) == expected and all(
str(row.match_result or '').strip().lower() != 'preparing'
for row in matches.values()
)
def current_inventory_matches_have_shortage(task: ShippingNotice) -> bool:
"""判断当前行级匹配中是否存在尚未满足的缺口或匹配失败。"""
for row in current_inventory_matches_for_task(task):
try:
shortage = float(row.shortage_qty or 0)
except (TypeError, ValueError):
shortage = 0.0
if str(row.match_result or '').strip().lower() != 'matched' or shortage > 0:
return True
return False
def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool:
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
@@ -314,9 +428,11 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
mapping_source='parsing_profile',
mapping_confirmed=True,
source_code=source_code,
source_type=str(task.inventory_connector_type or "").strip() or None,
source_type=str(
(get_database_inventory_source(source_code) or {}).get('connector_type') or ''
).strip() or None,
warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
source_config_version=inventory_sources_runtime_version(),
source_query_json={'trigger_type': 'manual_upload'},
identity_status="pending",
snapshot_status="ready",
@@ -442,7 +558,7 @@ def replace_task_inventory_link(
db.session.add(new_link)
db.session.add(
ShippingTaskEvent(
task_id=task.id,
task_id=task_event_task_id(task),
event_type="inventory_file_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
@@ -524,8 +640,6 @@ def apply_inventory_parse_result_to_linked_tasks(
continue
if not _can_relink_inventory(link.task):
continue
link.task.inventory_snapshot_id = inv_file.id
link.task.inventory_lines_json = inventory_lines
linked_tasks.append(link.task)
return linked_tasks
@@ -569,7 +683,8 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
task = link.task
if not link.is_active or not task:
continue
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
step_key="step5_match_inventory",
@@ -3,7 +3,8 @@ services/shipping_notice/inventory_mapping_workflow.py
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析;
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。
"""
from __future__ import annotations
@@ -13,6 +14,7 @@ from typing import Any
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
@@ -36,9 +38,14 @@ def inventory_loaded_response(
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
commit: bool = True,
persist_lines: bool = True,
) -> dict[str, Any]:
"""
写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。
将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。
核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库)
写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
禁止覆盖共享 File 上已有行缓存。
Args:
task: 当前正式发货任务。
@@ -50,13 +57,18 @@ def inventory_loaded_response(
field_mapping: published Profile 的字段映射快照。
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
commit: False 时仅 flush,供批量回调维持外层事务边界。
persist_lines: False 时不写 File.inventory_lines_json(复用路径)。
Returns:
Tool 标准响应;成功后任务可直接进入库存匹配。
"""
inv_file = active_inventory_file_for_task(task)
if inv_file is None:
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
# [STEP] 首次落库写 File;复用只推进状态,避免共享快照被 OT 私有/合并行覆盖。
linked_tasks: list[ShippingNotice] = []
if inv_file:
if persist_lines:
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
inv_file,
inventory_lines,
@@ -65,7 +77,11 @@ def inventory_loaded_response(
mapping_confirmed=True,
)
else:
task.inventory_lines_json = inventory_lines
linked_tasks = [
link.task
for link in (inv_file.links or [])
if link.is_active and link.task and _can_relink_inventory(link.task)
]
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
@@ -73,9 +89,6 @@ def inventory_loaded_response(
for affected in [task, *linked_tasks]:
if affected is None:
continue
affected.match_status = None
affected.line_results_json = None
affected.shortage_json = None
try:
order_lines = task_line_purpose_values(task)
@@ -127,6 +140,7 @@ def inventory_loaded_response(
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
"persist_lines": bool(persist_lines),
},
)
if commit:
@@ -144,5 +158,6 @@ def inventory_loaded_response(
"inventory_row_count": len(inventory_lines),
"field_alignment": field_alignment,
"warnings": warnings or [],
"persist_lines": bool(persist_lines),
},
)
@@ -56,8 +56,37 @@ def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> se
return match_ids | quantity_ids
def _validate_definition(raw: Any) -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。"""
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
mapping = definition.get('field_mapping') or {}
mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()}
unknown = mapped_codes - movement_codes
if unknown:
raise ValidationError(
f'Movement parsing profile references unknown field: {sorted(unknown)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
if missing:
raise ValidationError(
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
return mapped_codes
def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
Args:
raw: 解析定义对象。
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
@@ -65,6 +94,19 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if purpose == 'movement':
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()},
'match_keys': [],
}
catalog_fields = _catalog_fields(field_mapping)
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
@@ -87,9 +129,6 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
@@ -151,7 +190,7 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
sample_analysis = profile.sample_analysis
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
'published_at': profile.published_at.isoformat() if profile.published_at else None,
'source_count': len(profile.sources),
@@ -193,6 +232,15 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
if purpose not in {'inventory', 'movement'}:
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
'Draft parsing profile purpose is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
profile.purpose = purpose
profile.display_name = str(data.get('display_name') or code).strip()
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
@@ -203,7 +251,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition'))
definition = _validate_definition(data.get('definition'), purpose=purpose)
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
@@ -16,16 +16,19 @@ from app.models import (
ShippingInventoryFile,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
ShippingNotice,
ShippingOrderTask,
ShippingOrderCandidate,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
def create_inventory_preparation_round(
*, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None,
*, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None,
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
gate_attempt_id: int | None = None,
) -> ShippingInventoryPreparationAttempt:
@@ -50,8 +53,7 @@ def create_inventory_preparation_round(
db.session.flush()
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
if not codes:
codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()]
codes = [code for code in codes if code]
codes = task_frozen_inventory_source_codes(task)
active_file = active_inventory_file_for_task(task)
for source_code in codes:
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
@@ -76,8 +78,14 @@ def create_inventory_preparation_round(
)
db.session.add(source)
db.session.flush()
source_candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == int(task.id))
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
task_snapshot_fingerprint=str(getattr(source_candidate, 'content_fingerprint', '') or ''),
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
sources=[
{
@@ -99,7 +107,7 @@ def create_inventory_preparation_round(
for item in round_row.source_attempts
],
reservation_version=str(getattr(task, 'order_data_version', '') or ''),
matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''),
matching_rule_version=str(active_inventory_runtime_facts(task).get('source_config_version') or ''),
)
db.session.flush()
return round_row
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff. Show more