feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能
包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
This commit is contained in:
1 parent
f3050164d0
commit
6b53b563e7
177 files changed
+17260
-36
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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 = 2
|
||||
ERP_QUERY_CONCURRENCY = 2
|
||||
ERP_WRITE_CONCURRENCY = 1
|
||||
|
||||
|
||||
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,105 @@
|
||||
"""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)
|
||||
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=client.config_json or {},
|
||||
request_spec=iface.request_spec_json or {},
|
||||
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,28 @@
|
||||
"""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 {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
wsdl = str(config.get('wsdl') or '').strip()
|
||||
if not endpoint or not wsdl:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing endpoint/wsdl)')
|
||||
|
||||
# 真实 SOAP 调用(zeep.Client(action=...,构造请求体、解析响应))待 WSDL 冻结后落地。
|
||||
raise NotImplementedError('SOAP implementation pending frozen WSDL')
|
||||
@@ -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,
|
||||
)
|
||||
@@ -141,6 +141,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
)
|
||||
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
|
||||
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",
|
||||
@@ -366,6 +368,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()
|
||||
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user