feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能

包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
This commit is contained in:
hugo committed 2026-08-28 17:16:06 +08:00
1 parent f3050164d0
commit 6b53b563e7
177 files changed
+17260 -36

No files matched your search

+3 -3
View File
@@ -119,8 +119,8 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭)
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.230:8100/
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
@@ -140,7 +140,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
+18
View File
@@ -165,6 +165,24 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
# --- 9. 业务模块 ---
# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值)
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=2
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=2
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=1
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件)
# IN_TRANSIT_TRANSFER_ERP_ENDPOINT=
# IN_TRANSIT_TRANSFER_ERP_USERNAME=
# IN_TRANSIT_TRANSFER_ERP_PASSWORD=
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=
# 归档 bucket(MinIO;凭据复用 MINIO_*)
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
# chat回答的评分与评论
FEEDBACK_ENABLED=true
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
+4
View File
@@ -44,6 +44,8 @@ def register_blueprints(app: Flask) -> None:
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
from app.api.in_transit_transfer import in_transit_transfer_bp
from app.api.integration_connector import integration_connector_bp
app.register_blueprint(chat_bp, url_prefix='/api/chat')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
@@ -73,3 +75,5 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
+428
View File
@@ -0,0 +1,428 @@
"""backend/app/api/in_transit_transfer.py
用途:在途仓自动调拨用户态 API(仓库管理人员)。
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
"""
from __future__ import annotations
from functools import wraps
from typing import Any
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import Agent
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.cancellation import cancel_run
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
from app.services.in_transit_transfer.execution_service import (
execute_precheck,
get_run,
serialize_run_result,
)
from app.services.in_transit_transfer.manual_close_service import manual_close_item
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.retry_service import retry_item
from app.services.in_transit_transfer.serializers import (
serialize_item,
serialize_source,
serialize_summary,
)
in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__)
TRANSFER_AGENT_CODE = "in_transit_transfer"
def _require_user():
"""校验当前登录用户;未认证抛 UnauthorizedError。"""
user = get_current_user()
if not user:
raise UnauthorizedError("Unauthorized")
return user
def require_transfer_permission(f):
"""装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
@wraps(f)
def decorated(*args, **kwargs):
user = _require_user()
if user.role == "admin":
return f(*args, **kwargs)
agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first()
if agent is None or agent not in user.agents:
raise ForbiddenError("Transfer agent permission required")
return f(*args, **kwargs)
return decorated
def _ok(payload: Any, *, status: int = 200):
"""统一成功 envelope(带 request_id)。"""
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
@require_transfer_permission
def create_precheck_api():
"""创建或复用一次调拨预检(只读,不写 ERP)。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
raise ValidationError("request body must be a JSON object")
source_codes = body.get("source_codes")
if not isinstance(source_codes, list) or not source_codes:
raise ValidationError("source_codes is required")
business_date = str(body.get("business_date") or business_date_now())
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=[str(item).strip() for item in source_codes],
business_date=business_date,
deps=deps,
)
return _ok(serialize_summary(summary), status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
@require_transfer_permission
def get_precheck_api(precheck_id: str):
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
restored = restore_precheck(precheck_id)
return _ok({
"summary": serialize_summary(restored["summary"]),
"items": [serialize_item(item) for item in restored["items"]],
"sources": [serialize_source(source) for source in restored["sources"]],
})
@in_transit_transfer_bp.route("/prechecks/<precheck_id>/execute", methods=["POST"])
@require_transfer_permission
def execute_precheck_api(precheck_id: str):
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
"""
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
if invoice_nos is not None and not isinstance(invoice_nos, list):
raise ValidationError("invoice_nos must be a list")
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
return _ok({
"run_no": outcome.run_no,
"status": outcome.status,
"result": serialize_run_result(outcome.result),
}, status=201)
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
@require_transfer_permission
def get_run_api(run_no: str):
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
return _ok(get_run(run_no))
@in_transit_transfer_bp.route("/runs/<run_no>/cancel", methods=["POST"])
@require_transfer_permission
def cancel_run_api(run_no: str):
"""请求停止剩余任务(原因必填,已成功单据保留)。"""
body = request.get_json(silent=True) or {}
reason = body.get("reason") if isinstance(body, dict) else None
return _ok(cancel_run(run_no=run_no, reason=reason))
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
@require_transfer_permission
def retry_item_api(item_id: int):
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
"""
body = request.get_json(silent=True) or {}
kind = body.get("kind") if isinstance(body, dict) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
@require_transfer_permission
def manual_close_item_api(item_id: int):
"""人工关闭异常项(原因必填,永久排除)。"""
body = request.get_json(silent=True) or {}
reason = body.get("reason") if isinstance(body, dict) else None
return _ok(manual_close_item(item_id=item_id, reason=reason))
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
@require_transfer_permission
def exceptions_excel_api(run_no: str):
"""下载本次 Run 的七 Sheet 异常 Excel(下载行为记录访问审计)。"""
import io
from app import db
from app.services.in_transit_transfer.audit import build_transfer_audit_event
data = build_exceptions_workbook(run_no)
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_EXCEL_DOWNLOADED",
aggregate_type="transfer_run",
aggregate_id=run_no,
run_no=run_no,
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
))
db.session.commit()
return send_file(
io.BytesIO(data),
mimetype=_MIME,
as_attachment=True,
download_name=f"transfer-exceptions-{run_no}.xlsx",
)
@in_transit_transfer_bp.route("/runs/<run_no>/receipt-files", methods=["GET"])
@require_transfer_permission
def receipt_files_api(run_no: str):
"""下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。"""
import io
import json
import zipfile
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.audit import build_transfer_audit_event
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
precheck = run.prechecks[0] if run.prechecks else None
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {}
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
for source_code in run.source_codes_json:
manifest = {
"source_code": source_code,
"business_date": run.business_date,
**dict(file_snapshot.get(source_code) or {}),
}
archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2))
rows = []
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all():
for line in (item.raw_lines_json or []):
rows.append({
"invoice_no": item.invoice_no, "source_code": item.source_code,
"sheet": line.get("sheet", ""), "row_no": line.get("row_no", ""),
"file_version": line.get("file_version", ""),
})
archive.writestr("raw-line-trace.json", json.dumps(rows, ensure_ascii=False, indent=2))
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
aggregate_type="transfer_run",
aggregate_id=run_no,
run_no=run_no,
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
))
db.session.commit()
return send_file(
io.BytesIO(buffer.getvalue()),
mimetype="application/zip",
as_attachment=True,
download_name=f"receipt-files-{run_no}.zip",
)
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
@require_transfer_permission
def erp_inventory_api(run_no: str):
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
import io
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.audit import build_transfer_audit_event
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
lines.append(",".join([
str(item.invoice_no), str(item.source_code), str(item.material_no),
str(item.from_warehouse), str(item.to_warehouse),
str(item.receipt_quantity), str(item.erp_quantity or ""),
str(item.result_code or item.status), str(item.erp_document_no or ""),
]))
data = ("\n".join(lines) + "\n").encode("utf-8")
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
aggregate_type="transfer_run",
aggregate_id=run_no,
run_no=run_no,
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
))
db.session.commit()
return send_file(
io.BytesIO(data),
mimetype="text/csv",
as_attachment=True,
download_name=f"erp-inventory-{run_no}.csv",
)
@in_transit_transfer_bp.route("/metrics", methods=["GET"])
@require_transfer_permission
def transfer_metrics_api():
"""调拨运营指标(成功率/失败类型/待处理老化/通知失败),供运营看板。"""
from app.services.in_transit_transfer.metrics import collect_metrics
return _ok(collect_metrics())
@in_transit_transfer_bp.route("/sources", methods=["GET"])
@require_transfer_permission
def transfer_sources_api():
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
"""
from app.models import ShippingInventorySource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
rows = ShippingInventorySource.query.filter_by(enabled=True).order_by(
ShippingInventorySource.connector_type, ShippingInventorySource.source_code,
).all()
return _ok([
{
"source_code": source.source_code,
"display_name": source.display_name,
"platform": source.connector_type,
"enabled": bool(source.enabled),
**resolve_source_file_status(source_code=source.source_code),
}
for source in rows
])
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
@require_transfer_permission
def retry_source_rpa_api(source_code: str):
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。
"""
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from app.services.in_transit_transfer.date_policy import business_date_now
source_code = str(source_code).strip()
outcome = trigger_receipt_rpa(
source_code=source_code,
business_date=str(business_date_now()),
reason="transfer_retry_receipt",
)
status = resolve_source_file_status(source_code=source_code)
if not outcome.get("ok"):
return _ok({
"source_code": source_code,
"ok": False,
"file_status": status["file_status"],
"error_code": outcome.get("error_code"),
})
return _ok({
"source_code": source_code,
"ok": True,
"file_status": "fetching",
"callback_id": outcome.get("callback_id"),
}, status=202)
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
@require_transfer_permission
def backlog_api():
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。"""
from app import db
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.backlog_service import list_backlog
items = list_backlog()
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type='TRANSFER_BACKLOG_VIEWED',
aggregate_type='transfer_backlog',
aggregate_id='backlog',
actor_type='user',
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, 'name', '') or ''),
request_id=getattr(g, 'request_id', None),
result='success',
after={'item_count': len(items)},
))
db.session.commit()
return _ok([_serialize_backlog_item(item) for item in items])
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
@require_transfer_permission
def backlog_summary_api():
"""待处理异常汇总(含 3/5/7 天老化分级)。"""
from app.services.in_transit_transfer.backlog_service import backlog_summary
summary = backlog_summary()
return _ok({
'recoverable': summary.recoverable_count,
'closed': summary.closed_count,
'unknown': summary.unknown_count,
'aging': {
'warn_3d': summary.warn_3d,
'escalate_5d': summary.escalate_5d,
'critical_7d': summary.critical_7d,
},
})
def _serialize_backlog_item(item) -> dict[str, Any]:
"""待处理池项序列化。"""
return {
'item_id': item.item_id,
'source_code': item.source_code,
'invoice_no': item.invoice_no,
'material_no': item.material_no,
'status': item.status,
'reason': item.reason,
'age_days': item.age_days,
'aging_level': item.aging_level,
'last_attempt_at': item.last_attempt_at,
}
+302
View File
@@ -0,0 +1,302 @@
"""api/integration_connector.py
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
/api/integration Dify 文件代理)。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, request
from app.core.decorators import require_admin
from app.core.errors import NotFoundError, ValidationError
from app.core.response import ok
from app.models import (
IntegrationBinding,
IntegrationClientInstance,
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
from app.services.integration_connector.gateway import get_capability_gateway
from app.services.integration_connector.transports.base import IntegrationCallResult
integration_connector_bp = Blueprint('integration_connector', __name__)
VALID_CONNECTOR_TYPES = ('rest', 'soap')
VALID_STATUSES = ('draft', 'published', 'retired')
def _require(value, field: str) -> None:
"""字段必填校验。"""
if value is None or (isinstance(value, str) and not value.strip()):
raise ValidationError(f'{field} is required', details={'field': field})
def _serialize_client(client) -> dict:
return {
'id': client.id, 'code': client.code, 'name': client.name,
'connector_type': client.connector_type, 'environment': client.environment,
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
'enabled': client.enabled,
}
def _serialize_interface(iface) -> dict:
return {
'id': iface.id, 'code': iface.code, 'name': iface.name,
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
}
def _serialize_binding(binding) -> dict:
return {
'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {},
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
'mapping_version': binding.mapping_version, 'priority': binding.priority,
'environment': binding.environment, 'effective_from': binding.effective_from,
'effective_to': binding.effective_to, 'status': binding.status,
}
def _serialize_credential(cred) -> dict:
return {
'id': cred.id, '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,
}
def _result_to_dict(result: IntegrationCallResult) -> dict:
return {
'status': result.status,
'data': result.data,
'error_code': result.error_code,
'error_message': result.error_message,
'document_no': result.document_no,
'trace_id': result.trace_id,
}
# ---- 能力清单与调用 ----
@integration_connector_bp.route('/capabilities', methods=['GET'])
@require_admin
def list_capabilities_endpoint():
ensure_capabilities_loaded()
data = [{
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
} for spec in list_capabilities()]
return ok(data)
@integration_connector_bp.route('/capabilities/<capability>', methods=['POST'])
@require_admin
def call_capability(capability):
body = request.get_json(silent=True) or {}
if body.get('interface_id') is not None:
raise ValidationError(
'interface_id is not allowed for capability calls',
code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED',
)
params = body.get('params') or {}
context = body.get('context') or {}
operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}')
idempotency_key = body.get('idempotency_key')
result = get_capability_gateway().call(
capability=capability, context=context, params=params,
operation_id=operation_id, idempotency_key=idempotency_key,
)
return ok(_result_to_dict(result))
# ---- 客户端实例 ----
@integration_connector_bp.route('/client-instances', methods=['GET'])
@require_admin
def list_client_instances():
rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all()
return ok([_serialize_client(row) for row in rows])
@integration_connector_bp.route('/client-instances', methods=['POST'])
@require_admin
def create_client_instance():
body = request.get_json(silent=True) or {}
connector_type = str(body.get('connector_type') or '').strip()
_require(body.get('code'), 'code')
_require(body.get('name'), 'name')
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
client = IntegrationClientInstance(
code=str(body['code']).strip(), name=str(body['name']).strip(),
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
config_json=body.get('config_json') or {},
credential_ref_code=body.get('credential_ref_code'),
enabled=bool(body.get('enabled', True)),
)
from app import db
db.session.add(client)
db.session.commit()
return ok(_serialize_client(client), status=201)
@integration_connector_bp.route('/client-instances/<code>', methods=['GET'])
@require_admin
def get_client_instance(code):
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
return ok(_serialize_client(client))
@integration_connector_bp.route('/client-instances/<code>', methods=['DELETE'])
@require_admin
def delete_client_instance(code):
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found')
from app import db
db.session.delete(client)
db.session.commit()
return ok({'deleted': True})
# ---- 接口定义 ----
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
@require_admin
def list_interface_definitions():
rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all()
return ok([_serialize_interface(row) for row in rows])
@integration_connector_bp.route('/interface-definitions', methods=['POST'])
@require_admin
def create_interface_definition():
body = request.get_json(silent=True) or {}
code = str(body.get('code') or '').strip()
_require(code, 'code')
_require(body.get('client_instance_code'), 'client_instance_code')
connector_type = str(body.get('connector_type') or '')
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
status = str(body.get('status') or 'draft')
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface = IntegrationInterfaceDefinition(
code=code, name=str(body.get('name') or code).strip(),
client_instance_code=body['client_instance_code'], connector_type=connector_type,
request_spec_json=body.get('request_spec_json') or {},
input_schema_json=body.get('input_schema_json') or {},
response_mapping_json=body.get('response_mapping_json') or {},
output_schema_json=body.get('output_schema_json') or {},
version=int(body.get('version') or 1), status=status,
enabled=bool(body.get('enabled', True)),
)
from app import db
db.session.add(iface)
db.session.commit()
return ok(_serialize_interface(iface), status=201)
# ---- Binding ----
@integration_connector_bp.route('/bindings', methods=['GET'])
@require_admin
def list_bindings():
rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all()
return ok([_serialize_binding(row) for row in rows])
@integration_connector_bp.route('/bindings', methods=['POST'])
@require_admin
def create_binding():
body = request.get_json(silent=True) or {}
_require(body.get('capability'), 'capability')
_require(body.get('client_instance_code'), 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code')
status = str(body.get('status') or 'draft')
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
binding = IntegrationBinding(
capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {},
client_instance_code=body['client_instance_code'],
interface_definition_code=body['interface_definition_code'],
mapping_version=int(body.get('mapping_version') or 1),
priority=int(body.get('priority') or 0),
environment=str(body.get('environment') or 'prod').strip(),
status=status,
)
from app import db
db.session.add(binding)
db.session.commit()
return ok(_serialize_binding(binding), status=201)
# ---- 凭据引用 ----
@integration_connector_bp.route('/credential-references', methods=['GET'])
@require_admin
def list_credential_references():
rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all()
return ok([_serialize_credential(row) for row in rows])
@integration_connector_bp.route('/credential-references', methods=['POST'])
@require_admin
def create_credential_reference():
body = request.get_json(silent=True) or {}
_require(body.get('code'), 'code')
_require(body.get('secret_ref'), 'secret_ref')
from app import db
cred = IntegrationCredentialReference(
code=str(body['code']).strip(),
secret_ref=str(body['secret_ref']).strip(),
secret_provider=str(body.get('secret_provider') or 'env').strip(),
credential_type=str(body.get('credential_type') or 'password').strip(),
version=int(body.get('version') or 1),
status=str(body.get('status') or 'active'),
)
db.session.add(cred)
db.session.commit()
# 永不回显真实凭据值;只回元数据。
return ok(_serialize_credential(cred), status=201)
# ---- 连接测试 ----
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
@require_admin
def test_connection(code):
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found')
gateway = get_capability_gateway()
transport = gateway.transports.get(client.connector_type)
if transport is None:
raise ValidationError(
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
)
raw = transport.call(
client={'config_json': client.config_json or {}, 'credential': {}},
interface={'request_spec_json': {}},
request={},
)
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw})
+22
View File
@@ -260,6 +260,28 @@ class Config:
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
# 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1'))
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
)
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
# ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。
IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip()
IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip()
IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip()
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip()
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
)
+3
View File
@@ -7,6 +7,9 @@ backend/app/jobs/handlers/__init__.py
from app.jobs.handlers import ( # noqa: F401
file_check_run,
in_transit_transfer_item,
in_transit_transfer_precheck,
in_transit_transfer_run,
kb_clean,
kb_dify_sync,
procurement_contract_review,
@@ -0,0 +1,29 @@
"""backend/app/jobs/handlers/in_transit_transfer_item.py
用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。
依赖:execution_service.execute_item、transfer deps、Job 注册表。
逻辑:payload 携带 item_id;单项结果不影响其他项。
"""
from __future__ import annotations
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.execution_service import execute_item
@register_handler(JobType.TRANSFER_ITEM)
def run_in_transit_transfer_item(_ctx, payload: dict) -> None:
"""执行单个 Invoice(异步路径)。
【AI 触发时机】:仅由 Item 入队路径调用;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
item_id = payload.get("item_id")
if item_id is None:
raise RuntimeError("missing_transfer_item_id")
execute_item(
item_id=int(item_id),
deps=transfer_deps.get_transfer_dependencies(),
)
@@ -0,0 +1,55 @@
"""backend/app/jobs/handlers/in_transit_transfer_precheck.py
用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。
依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。
逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写
状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。
"""
from __future__ import annotations
from app import db
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import TransferPrecheck
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.precheck_service import run_precheck
@register_handler(JobType.TRANSFER_PRECHECK)
def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
"""执行一次预检 Job 并更新预检状态。
【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
precheck_no = str(payload.get("precheck_id") or "").strip()
if not precheck_no:
raise RuntimeError("missing_transfer_precheck_id")
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first()
if precheck is None:
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
deps = transfer_deps.get_transfer_dependencies()
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
precheck.scope_json, dict
) else []
result = run_precheck(
source_codes=source_codes,
business_date=precheck.business_date,
deps=deps,
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
)
summary = result.summary
precheck.status = summary.status
precheck.counts_json = {
"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,
}
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
precheck.precheck_hash = summary.precheck_hash
db.session.commit()
@@ -0,0 +1,29 @@
"""backend/app/jobs/handlers/in_transit_transfer_run.py
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
依赖:execution_service、transfer deps、Job 注册表。
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
"""
from __future__ import annotations
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.execution_service import execute_precheck
@register_handler(JobType.TRANSFER_RUN)
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
"""执行一个 Run(异步路径)。
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
"""
payload = payload if isinstance(payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
if not precheck_id:
raise RuntimeError("missing_transfer_precheck_id")
execute_precheck(
precheck_id=precheck_id,
deps=transfer_deps.get_transfer_dependencies(),
)
+7
View File
@@ -36,6 +36,10 @@ class JobType(StrEnum):
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review'
# 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。
TRANSFER_PRECHECK = 'in_transit_transfer_precheck'
TRANSFER_RUN = 'in_transit_transfer_run'
TRANSFER_ITEM = 'in_transit_transfer_item'
class JobStatus(StrEnum):
@@ -75,6 +79,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
}),
'contract': frozenset({'procurement_contract_review'}),
'schedule': frozenset({'schedule_run'}),
'transfer': frozenset({
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
}),
}
+28
View File
@@ -183,6 +183,22 @@ from app.models.shipping_inventory_preparation import (
ShippingInventoryPreparationSourceAttempt,
)
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
from app.models.in_transit_transfer import (
TransferArchive,
TransferAttempt,
TransferAuditEvent,
TransferInvoiceItem,
TransferPrecheck,
TransferRun,
TransferSourceJob,
)
from app.models.integration_connector import (
IntegrationBinding,
IntegrationCall,
IntegrationClientInstance,
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
@@ -356,4 +372,16 @@ __all__ = [
'ShippingTaskInventoryRpaAttempt',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
'TransferRun',
'TransferSourceJob',
'TransferPrecheck',
'TransferInvoiceItem',
'TransferAttempt',
'TransferAuditEvent',
'TransferArchive',
'IntegrationCredentialReference',
'IntegrationClientInstance',
'IntegrationInterfaceDefinition',
'IntegrationBinding',
'IntegrationCall',
]
+352
View File
@@ -0,0 +1,352 @@
"""models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
Attempt、AuditEvent 与 Archive。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
event,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.errors import ValidationError
from app.models.base import Base
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
TRANSFER_ITEM_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
TRANSFER_RUN_STATUSES = (
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
TRANSFER_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
TRANSFER_PRECHECK_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'failed', 'cancelled', 'expired',
)
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
TRANSFER_ATTEMPT_STATUSES = (
'queued', 'running', 'waiting_external', 'success', 'failed',
'result_unknown', 'superseded',
)
TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')
class TransferRun(Base):
"""一次调拨执行(或只读预检)的业务真相源。"""
__tablename__ = 'transfer_runs'
__table_args__ = (
UniqueConstraint('run_no', name='uq_transfer_runs_run_no'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_RUN_STATUSES)})",
name='ck_transfer_runs_status',
),
CheckConstraint(
"notification_status IN ('pending', 'success', 'failed')",
name='ck_transfer_runs_notification_status',
),
CheckConstraint(
"trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type',
),
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
Index('ix_transfer_runs_business_date', 'business_date'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
notification_status: Mapped[str] = mapped_column(
String(16), nullable=False, default='pending', server_default='pending',
)
notification_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
notification_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
back_populates='run', cascade='all, delete-orphan',
)
prechecks: Mapped[list['TransferPrecheck']] = relationship(
back_populates='run', cascade='all, delete-orphan',
)
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
class TransferSourceJob(Base):
"""来源实例级的文件准备/预检执行单元;来源间互不阻断。"""
__tablename__ = 'transfer_source_jobs'
__table_args__ = (
UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_SOURCE_JOB_STATUSES)})",
name='ck_transfer_source_jobs_status',
),
Index('ix_transfer_source_jobs_source_status', 'source_code', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
file_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
lease_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
class TransferPrecheck(Base):
"""一次冻结快照的预检结果;确认/执行绑定其 Hash。"""
__tablename__ = 'transfer_prechecks'
__table_args__ = (
UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})",
name='ck_transfer_prechecks_status',
),
Index('ix_transfer_prechecks_run_status', 'run_id', 'status'),
Index('ix_transfer_prechecks_business_date', 'business_date'),
)
id: Mapped[int] = mapped_column(primary_key=True)
precheck_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking')
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks')
items: Mapped[list['TransferInvoiceItem']] = relationship(
back_populates='precheck', cascade='all, delete-orphan',
)
class TransferInvoiceItem(Base):
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
name='ck_transfer_invoice_items_status',
),
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
Index('ix_transfer_invoice_items_run_id', 'run_id'),
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False)
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
manually_closed_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
precheck: Mapped[TransferPrecheck] = relationship(back_populates='items')
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
attempts: Mapped[list['TransferAttempt']] = relationship(
back_populates='item', cascade='all, delete-orphan',
)
class TransferAttempt(Base):
"""一次恢复/重查/执行尝试;每次恢复创建新 Attempt,旧记录不可覆盖。"""
__tablename__ = 'transfer_attempts'
__table_args__ = (
UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'),
CheckConstraint(
f"kind IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_KINDS)})",
name='ck_transfer_attempts_kind',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_STATUSES)})",
name='ck_transfer_attempts_status',
),
Index('ix_transfer_attempts_item_created', 'item_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
kind: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
request_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts')
class TransferAuditEvent(Base):
"""调拨领域只追加审计事件;禁止更新与删除。"""
__tablename__ = 'transfer_audit_events'
__table_args__ = (
CheckConstraint(
f"actor_type IN ({', '.join(repr(s) for s in TRANSFER_AUDIT_ACTOR_TYPES)})",
name='ck_transfer_audit_events_actor_type',
),
CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_transfer_audit_events_result',
),
Index('ix_transfer_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
Index('ix_transfer_audit_events_run_created', 'run_no', 'created_at'),
Index('ix_transfer_audit_events_invoice_created', 'invoice_no', 'created_at'),
Index('ix_transfer_audit_events_operation_created', 'operation_id', 'created_at'),
Index('ix_transfer_audit_events_event_hash', 'event_hash'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
actor_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
actor_display: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
result: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
before_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
after_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
before_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
after_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
event_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class TransferArchive(Base):
"""大对象归档索引(MinIO);Hash 用于归档完整性校验。"""
__tablename__ = 'transfer_archives'
__table_args__ = (
UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'),
UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'),
CheckConstraint("file_size >= 0", name='ck_transfer_archives_file_size'),
Index('ix_transfer_archives_object', 'object_type', 'object_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
archive_no: Mapped[str] = mapped_column(String(64), nullable=False)
object_type: Mapped[str] = mapped_column(String(64), nullable=False)
object_id: Mapped[str] = mapped_column(String(128), nullable=False)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(TransferAuditEvent, 'before_update')
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,确保审计事件不可改写。"""
raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE')
@event.listens_for(TransferAuditEvent, 'before_delete')
def _reject_transfer_audit_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,保留跨生命周期追溯事实。"""
raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE')
+193
View File
@@ -0,0 +1,193 @@
"""models/integration_connector.py
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import JSONB
from app.models.base import Base
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
CONNECTOR_TYPES = ('rest', 'soap')
CONFIG_STATUSES = ('draft', 'published', 'retired')
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
# context_selector_json 需要参与唯一约束/索引:PostgreSQL 的 JSON 无默认 btree 操作符表,
# 无法建唯一索引;映射为 JSONB 即可。SQLite/测试仍用 JSON(TEXT)。
CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
class IntegrationCredentialReference(Base):
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。"""
__tablename__ = 'integration_credential_references'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_credential_references_code'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CREDENTIAL_STATUSES)})",
name='ck_integration_credential_references_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
last_verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationClientInstance(Base):
"""客户端实例:一份到外部系统的连接配置(连到哪 + 凭据引用 + 超时/TLS/默认 org)。"""
__tablename__ = 'integration_client_instances'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_client_instances_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_client_instances_connector_type',
),
Index('ix_integration_client_instances_type_env', 'connector_type', 'environment'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationInterfaceDefinition(Base):
"""接口定义:一个可调操作(请求模板 + 入参 Schema + 返回值映射 + 出参 Schema)。"""
__tablename__ = 'integration_interface_definitions'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_interface_definitions_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_interface_definitions_connector_type',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_interface_definitions_status',
),
Index('ix_integration_interface_definitions_client', 'client_instance_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationBinding(Base):
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
__tablename__ = 'integration_bindings'
__table_args__ = (
UniqueConstraint(
'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_bindings_status',
),
CheckConstraint(
"priority >= 0", name='ck_integration_bindings_priority',
),
Index('ix_integration_bindings_cap_env_status', 'capability', 'environment', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
interface_definition_code: Mapped[str] = mapped_column(
ForeignKey('integration_interface_definitions.code'), nullable=False,
)
mapping_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationCall(Base):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
__tablename__ = 'integration_calls'
__table_args__ = (
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
operation_id: Mapped[str] = mapped_column(String(128), nullable=False)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
binding_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
request_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False)
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -158,16 +158,26 @@ class ShippingInventorySourceParsingBindingAudit(Base):
class ShippingInventoryParsingProfile(Base):
"""可跨库存源复用的库存文件结构、样本证据与订单匹配配置。"""
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
"""
__tablename__ = 'shipping_inventory_parsing_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
CheckConstraint(
"purpose IN ('inventory', 'movement')",
name='ck_shipping_inventory_parsing_profiles_purpose',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory')
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
@@ -30,6 +30,10 @@ class ShippingReceiptReportConfig(Base):
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
)
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
@@ -47,6 +51,7 @@ class ShippingReceiptReportConfig(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship()
class ShippingReceiptRpaUnitRun(Base):
@@ -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(
@@ -0,0 +1,157 @@
"""add integration connector tables
Revision ID: ic1a2b3c4d5f
Revises: it1a2b3c4d5e
Create Date: 2026-08-27 21:00:00.000000
用途:Integration Connector(外部系统连接器框架)P1 配置与运行模型建表:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:integration_* 全部新表;不依赖既有 shipping/transfer 表。
逻辑:配置层实体维护版本与状态;IntegrationCall 记录一次技术调用(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态用 CheckConstraint 兜底;fail-closed 语义在服务层。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ic1a2b3c4d5f'
down_revision = 'it1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 5 张连接器框架表(先建凭据/客户端,再建接口/绑定,最后调用记录)。"""
op.create_table(
'integration_credential_references',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('secret_ref', sa.String(length=128), nullable=False),
sa.Column('secret_provider', sa.String(length=32), nullable=False, server_default='env'),
sa.Column('credential_type', sa.String(length=32), nullable=False, server_default='password'),
sa.Column('version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=16), nullable=False, server_default='active'),
sa.Column('last_verified_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_credential_references_code'),
sa.CheckConstraint(
"status IN ('active', 'rotating', 'retired')",
name='ck_integration_credential_references_status',
),
)
op.create_table(
'integration_client_instances',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('connector_type', sa.String(length=16), nullable=False),
sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'),
sa.Column('config_json', sa.JSON(), nullable=False),
sa.Column('credential_ref_code', sa.String(length=64), sa.ForeignKey('integration_credential_references.code'), nullable=True),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_client_instances_code'),
sa.CheckConstraint(
"connector_type IN ('rest', 'soap')",
name='ck_integration_client_instances_connector_type',
),
)
op.create_index(
'ix_integration_client_instances_type_env',
'integration_client_instances', ['connector_type', 'environment'],
)
op.create_table(
'integration_interface_definitions',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False),
sa.Column('connector_type', sa.String(length=16), nullable=False),
sa.Column('request_spec_json', sa.JSON(), nullable=False),
sa.Column('input_schema_json', sa.JSON(), nullable=False),
sa.Column('response_mapping_json', sa.JSON(), nullable=False),
sa.Column('output_schema_json', sa.JSON(), nullable=False),
sa.Column('version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_integration_interface_definitions_code'),
sa.CheckConstraint(
"connector_type IN ('rest', 'soap')",
name='ck_integration_interface_definitions_connector_type',
),
sa.CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_integration_interface_definitions_status',
),
)
op.create_index(
'ix_integration_interface_definitions_client',
'integration_interface_definitions', ['client_instance_code'],
)
op.create_table(
'integration_bindings',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('capability', sa.String(length=128), nullable=False),
sa.Column('context_selector_json', sa.JSON().with_variant(sa.dialects.postgresql.JSONB(), 'postgresql'), nullable=False),
sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False),
sa.Column('interface_definition_code', sa.String(length=64), sa.ForeignKey('integration_interface_definitions.code'), nullable=False),
sa.Column('mapping_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('priority', sa.Integer(), nullable=False, server_default='0'),
sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'),
sa.Column('effective_from', sa.DateTime(), nullable=True),
sa.Column('effective_to', sa.DateTime(), nullable=True),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint(
'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx',
),
sa.CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_integration_bindings_status',
),
sa.CheckConstraint('priority >= 0', name='ck_integration_bindings_priority'),
)
op.create_index(
'ix_integration_bindings_cap_env_status',
'integration_bindings', ['capability', 'environment', 'status'],
)
op.create_table(
'integration_calls',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('operation_id', sa.String(length=128), nullable=False),
sa.Column('capability', sa.String(length=128), nullable=False),
sa.Column('binding_snapshot_json', sa.JSON(), nullable=False),
sa.Column('request_summary_json', sa.JSON(), nullable=False),
sa.Column('response_summary_json', sa.JSON(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('elapsed_ms', sa.Integer(), nullable=False, server_default='0'),
sa.Column('trace_id', sa.String(length=64), nullable=False, server_default=''),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
)
op.create_index('ix_integration_calls_capability_created', 'integration_calls', ['capability', 'created_at'])
op.create_index('ix_integration_calls_trace_id', 'integration_calls', ['trace_id'])
def downgrade() -> None:
"""回滚:按外键依赖逆序删除连接器表。"""
op.drop_index('ix_integration_calls_trace_id', table_name='integration_calls')
op.drop_index('ix_integration_calls_capability_created', table_name='integration_calls')
op.drop_table('integration_calls')
op.drop_index('ix_integration_bindings_cap_env_status', table_name='integration_bindings')
op.drop_table('integration_bindings')
op.drop_index('ix_integration_interface_definitions_client', table_name='integration_interface_definitions')
op.drop_table('integration_interface_definitions')
op.drop_index('ix_integration_client_instances_type_env', table_name='integration_client_instances')
op.drop_table('integration_client_instances')
op.drop_table('integration_credential_references')
@@ -0,0 +1,45 @@
"""add purpose to inventory parsing profiles
Revision ID: if1b2c3d4e5g
Revises: ic1a2b3c4d5f
Create Date: 2026-08-28 10:30:00.000000
用途:把库存解析规则泛化为通用文件解析规则——为 shipping_inventory_parsing_profiles
增 purpose 列(inventory / movement)。inventory 沿用库存字段目录;movement
端点用定死领域字段(MOVEMENT_FIELDS),供收料/异动文件映射。既有行默认 inventory,
不改变既有库存语义。
依赖:shipping_inventory_parsing_profiles 表。
逻辑:仅加列 + CheckConstraint,无数据回填(默认 inventory)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'if1b2c3d4e5g'
down_revision = 'ic1a2b3c4d5f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 purpose 列并加 CheckConstraint(inventory / movement)。"""
op.add_column(
'shipping_inventory_parsing_profiles',
sa.Column('purpose', sa.String(length=16), nullable=False, server_default='inventory'),
)
op.create_check_constraint(
'ck_shipping_inventory_parsing_profiles_purpose',
'shipping_inventory_parsing_profiles',
"purpose IN ('inventory', 'movement')",
)
def downgrade() -> None:
"""移除 purpose 约束与列。"""
op.drop_constraint(
'ck_shipping_inventory_parsing_profiles_purpose',
'shipping_inventory_parsing_profiles',
type_='check',
)
op.drop_column('shipping_inventory_parsing_profiles', 'purpose')
@@ -0,0 +1,53 @@
"""add parsing_profile_id to shipping_receipt_report_configs
Revision ID: if1b2c3d4e5h
Revises: if1b2c3d4e5g
Create Date: 2026-08-28 10:45:00.000000
用途:收料报表配置绑定其收料文件解析规则(purpose='movement')。空则无法解析收料文件。
依赖:shipping_receipt_report_configs 表 + shipping_inventory_parsing_profiles 表。
逻辑:仅新增可空外键列,无数据回填。
"""
from alembic import op
import sqlalchemy as sa
revision = 'if1b2c3d4e5h'
down_revision = 'if1b2c3d4e5g'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 parsing_profile_id 外键列。"""
op.add_column(
'shipping_receipt_report_configs',
sa.Column('parsing_profile_id', sa.Integer(), nullable=True),
)
op.create_index(
'ix_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
['parsing_profile_id'],
)
op.create_foreign_key(
'fk_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
'shipping_inventory_parsing_profiles',
['parsing_profile_id'],
['id'],
)
def downgrade() -> None:
"""移除外键、索引与列。"""
op.drop_constraint(
'fk_shipping_receipt_report_configs_parsing_profile',
'shipping_receipt_report_configs',
type_='foreignkey',
)
op.drop_index(
'ix_shipping_receipt_report_configs_parsing_profile',
table_name='shipping_receipt_report_configs',
)
op.drop_column('shipping_receipt_report_configs', 'parsing_profile_id')
@@ -0,0 +1,42 @@
"""add file_ready to transfer_source_jobs status constraint
Revision ID: if1b2c3d4e5i
Revises: if1b2c3d4e5h
Create Date: 2026-08-28 11:15:00.000000
用途:让 TransferSourceJob.status 状态集与来源准备流程阶段(file_ready)对齐。
原 CHECK 缺少 file_ready,导致来源文件就绪时 job 无法用 file_ready 表达
(create_precheck 只能硬映射为 pending)。
依赖:transfer_source_jobs 表。
逻辑:drop 旧 CHECK → 重新 create(追加 file_ready),无数据回填。
"""
from alembic import op
revision = 'if1b2c3d4e5i'
down_revision = 'if1b2c3d4e5h'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""更新 status 检查约束,允许 file_ready。"""
op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check')
op.create_check_constraint(
'ck_transfer_source_jobs_status',
'transfer_source_jobs',
"status IN ('pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', "
"'parsing', 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
)
def downgrade() -> None:
"""恢复原检查约束(不含 file_ready)。"""
op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check')
op.create_check_constraint(
'ck_transfer_source_jobs_status',
'transfer_source_jobs',
"status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', "
"'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
)
@@ -0,0 +1,275 @@
"""add in-transit transfer domain tables
Revision ID: it1a2b3c4d5e
Revises: hw6x7y8z9a0b
Create Date: 2026-08-27 14:00:00.000000
用途:在途仓自动调拨 Agent 一期领域模型建表:Run、SourceJob、Precheck、
InvoiceItem、Attempt、AuditEvent 与 Archive。
依赖:transfer_* 全部新表;不依赖既有 shipping 表(来源配置在服务层只读复用)。
逻辑:Run 为业务真相源;InvoiceItem 按 (precheck_id, invoice_no) 唯一;
AuditEvent 只追加;Archive 记录 MinIO 对象路径与 Hash。
"""
from alembic import op
import sqlalchemy as sa
revision = 'it1a2b3c4d5e'
down_revision = 'hw6x7y8z9a0b'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 7 张调拨领域表。"""
op.create_table(
'transfer_runs',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_no', sa.String(length=64), nullable=False),
sa.Column('trigger_type', sa.String(length=16), nullable=False, server_default='manual'),
sa.Column('business_date', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
sa.Column('source_codes_json', sa.JSON(), nullable=False),
sa.Column('counts_json', sa.JSON(), nullable=False),
sa.Column('result_summary_json', sa.JSON(), nullable=False),
sa.Column('notification_status', sa.String(length=16), nullable=False, server_default='pending'),
sa.Column('notification_error_code', sa.String(length=64), nullable=True),
sa.Column('notification_error_message', sa.Text(), nullable=True),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('completed_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('run_no', name='uq_transfer_runs_run_no'),
sa.CheckConstraint(
"status IN ('queued', 'preparing_files', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
name='ck_transfer_runs_status',
),
sa.CheckConstraint(
"notification_status IN ('pending', 'success', 'failed')",
name='ck_transfer_runs_notification_status',
),
sa.CheckConstraint(
"trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type',
),
)
op.create_index('ix_transfer_runs_status_created', 'transfer_runs', ['status', 'created_at'])
op.create_index('ix_transfer_runs_business_date', 'transfer_runs', ['business_date'])
op.create_table(
'transfer_source_jobs',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=False),
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('source_config_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('file_no', sa.String(length=64), nullable=True),
sa.Column('file_sha256', sa.String(length=64), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('lease_until', sa.DateTime(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('finished_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'),
sa.CheckConstraint(
"status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', "
"'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')",
name='ck_transfer_source_jobs_status',
),
)
op.create_index('ix_transfer_source_jobs_source_status', 'transfer_source_jobs', ['source_code', 'status'])
op.create_table(
'transfer_prechecks',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('precheck_no', sa.String(length=64), nullable=False),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True),
sa.Column('business_date', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='prechecking'),
sa.Column('scope_json', sa.JSON(), nullable=False),
sa.Column('file_snapshot_json', sa.JSON(), nullable=False),
sa.Column('mapping_version', sa.String(length=64), nullable=True),
sa.Column('strategy_version', sa.String(length=64), nullable=True),
sa.Column('counts_json', sa.JSON(), nullable=False),
sa.Column('estimated_transfer_quantity', sa.String(length=40), nullable=True),
sa.Column('estimated_erp_write_count', sa.Integer(), nullable=False, server_default='0'),
sa.Column('precheck_hash', sa.String(length=128), nullable=False),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('confirmed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
sa.CheckConstraint(
"status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'failed', 'cancelled', 'expired')",
name='ck_transfer_prechecks_status',
),
)
op.create_index('ix_transfer_prechecks_run_status', 'transfer_prechecks', ['run_id', 'status'])
op.create_index('ix_transfer_prechecks_business_date', 'transfer_prechecks', ['business_date'])
op.create_table(
'transfer_invoice_items',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('precheck_id', sa.Integer(), sa.ForeignKey('transfer_prechecks.id'), nullable=False),
sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True),
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('invoice_no', sa.String(length=64), nullable=False),
sa.Column('material_no', sa.String(length=64), nullable=False),
sa.Column('material_name', sa.String(length=200), nullable=False, server_default=''),
sa.Column('specification', sa.String(length=200), nullable=False, server_default=''),
sa.Column('receipt_date', sa.String(length=16), nullable=True),
sa.Column('from_warehouse', sa.String(length=64), nullable=False),
sa.Column('to_warehouse', sa.String(length=64), nullable=False),
sa.Column('receipt_quantity', sa.String(length=40), nullable=False),
sa.Column('erp_quantity', sa.String(length=40), nullable=True),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('result_code', sa.String(length=64), nullable=True),
sa.Column('result_message', sa.Text(), nullable=True),
sa.Column('erp_document_no', sa.String(length=64), nullable=True),
sa.Column('raw_lines_json', sa.JSON(), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False, server_default='0'),
sa.Column('manually_closed_reason', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
sa.CheckConstraint(
"status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', "
"'executing', 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', "
"'result_unknown', 'manually_closed', 'cancelled', 'notification_failed')",
name='ck_transfer_invoice_items_status',
),
)
op.create_index(
'ix_transfer_invoice_items_source_invoice_status',
'transfer_invoice_items', ['source_code', 'invoice_no', 'status'],
)
op.create_index('ix_transfer_invoice_items_run_id', 'transfer_invoice_items', ['run_id'])
op.create_index('ix_transfer_invoice_items_erp_document_no', 'transfer_invoice_items', ['erp_document_no'])
op.create_table(
'transfer_attempts',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('item_id', sa.Integer(), sa.ForeignKey('transfer_invoice_items.id'), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(length=16), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
sa.Column('request_snapshot_json', sa.JSON(), nullable=False),
sa.Column('response_summary_json', sa.JSON(), nullable=False),
sa.Column('operation_id', sa.String(length=128), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('completed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'),
sa.CheckConstraint(
"kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')",
name='ck_transfer_attempts_kind',
),
sa.CheckConstraint(
"status IN ('queued', 'running', 'waiting_external', 'success', 'failed', "
"'result_unknown', 'superseded')",
name='ck_transfer_attempts_status',
),
)
op.create_index('ix_transfer_attempts_item_created', 'transfer_attempts', ['item_id', 'created_at'])
op.create_table(
'transfer_audit_events',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('event_type', sa.String(length=64), nullable=False),
sa.Column('aggregate_type', sa.String(length=64), nullable=False),
sa.Column('aggregate_id', sa.String(length=128), nullable=False),
sa.Column('run_no', sa.String(length=64), nullable=True),
sa.Column('precheck_no', sa.String(length=64), nullable=True),
sa.Column('invoice_no', sa.String(length=64), nullable=True),
sa.Column('item_id', sa.String(length=64), nullable=True),
sa.Column('attempt_no', sa.Integer(), nullable=True),
sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'),
sa.Column('actor_id', sa.String(length=128), nullable=True),
sa.Column('actor_role', sa.String(length=64), nullable=True),
sa.Column('actor_display', sa.String(length=128), nullable=True),
sa.Column('request_id', sa.String(length=64), nullable=True),
sa.Column('operation_id', sa.String(length=64), nullable=True),
sa.Column('source', sa.String(length=32), nullable=True),
sa.Column('result', sa.String(length=16), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('before_json', sa.JSON(), nullable=False),
sa.Column('after_json', sa.JSON(), nullable=False),
sa.Column('diff_json', sa.JSON(), nullable=False),
sa.Column('before_hash', sa.String(length=64), nullable=True),
sa.Column('after_hash', sa.String(length=64), nullable=True),
sa.Column('event_hash', sa.String(length=64), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"actor_type IN ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')",
name='ck_transfer_audit_events_actor_type',
),
sa.CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_transfer_audit_events_result',
),
)
op.create_index(
'ix_transfer_audit_events_aggregate_created',
'transfer_audit_events', ['aggregate_type', 'aggregate_id', 'created_at'],
)
op.create_index('ix_transfer_audit_events_run_created', 'transfer_audit_events', ['run_no', 'created_at'])
op.create_index('ix_transfer_audit_events_invoice_created', 'transfer_audit_events', ['invoice_no', 'created_at'])
op.create_index('ix_transfer_audit_events_operation_created', 'transfer_audit_events', ['operation_id', 'created_at'])
op.create_index('ix_transfer_audit_events_event_hash', 'transfer_audit_events', ['event_hash'])
op.create_table(
'transfer_archives',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('archive_no', sa.String(length=64), nullable=False),
sa.Column('object_type', sa.String(length=64), nullable=False),
sa.Column('object_id', sa.String(length=128), nullable=False),
sa.Column('storage_provider', sa.String(length=32), nullable=False),
sa.Column('storage_bucket', sa.String(length=128), nullable=False),
sa.Column('storage_key', sa.String(length=1024), nullable=False),
sa.Column('original_filename', sa.String(length=255), nullable=False),
sa.Column('content_type', sa.String(length=128), nullable=True),
sa.Column('file_size', sa.Integer(), nullable=False),
sa.Column('sha256', sa.String(length=64), nullable=False),
sa.Column('archive_expires_at', sa.DateTime(), nullable=True),
sa.Column('archive_deleted_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'),
sa.UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'),
sa.CheckConstraint('file_size >= 0', name='ck_transfer_archives_file_size'),
)
op.create_index('ix_transfer_archives_object', 'transfer_archives', ['object_type', 'object_id'])
def downgrade() -> None:
"""回滚:按外键依赖逆序删除调拨表。"""
op.drop_index('ix_transfer_archives_object', table_name='transfer_archives')
op.drop_table('transfer_archives')
op.drop_index('ix_transfer_audit_events_event_hash', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_operation_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_invoice_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_run_created', table_name='transfer_audit_events')
op.drop_index('ix_transfer_audit_events_aggregate_created', table_name='transfer_audit_events')
op.drop_table('transfer_audit_events')
op.drop_index('ix_transfer_attempts_item_created', table_name='transfer_attempts')
op.drop_table('transfer_attempts')
op.drop_index('ix_transfer_invoice_items_erp_document_no', table_name='transfer_invoice_items')
op.drop_index('ix_transfer_invoice_items_run_id', table_name='transfer_invoice_items')
op.drop_index('ix_transfer_invoice_items_source_invoice_status', table_name='transfer_invoice_items')
op.drop_table('transfer_invoice_items')
op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_prechecks')
op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_prechecks')
op.drop_table('transfer_prechecks')
op.drop_index('ix_transfer_source_jobs_source_status', table_name='transfer_source_jobs')
op.drop_table('transfer_source_jobs')
op.drop_index('ix_transfer_runs_business_date', table_name='transfer_runs')
op.drop_index('ix_transfer_runs_status_created', table_name='transfer_runs')
op.drop_table('transfer_runs')
@@ -0,0 +1,448 @@
"""在途调拨预检 API 契约测试(L2,Flask test client)。
用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与
GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
in_transit_transfer Agent 授权校验。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import Agent, User
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
API_PREFIX = "/api/in-transit-transfer"
def _jwt_headers(user: User) -> dict:
"""为指定用户签发 Bearer JWT 请求头。"""
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture
def transfer_deps(monkeypatch, dbs_ready_file):
"""注入 Fake 预检依赖,并预置可执行库存。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
return deps
@pytest.fixture
def admin_headers(app):
"""创建 admin 用户并返回 JWT 请求头(token 在 app context 内签发)。"""
with app.app_context():
user = db.session.query(User).filter_by(username="admin").first()
if not user:
user = User(username="admin", email="admin@example.com", role="admin", status="active")
user.set_password("admin")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture
def warehouse_headers(app):
"""创建持有 in_transit_transfer Agent 权限的仓库管理员并返回 JWT 请求头。"""
with app.app_context():
agent = Agent.query.filter_by(agent_code="in_transit_transfer").first()
if not agent:
agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer",
type="api", is_active=True)
db.session.add(agent)
db.session.flush()
user = db.session.query(User).filter_by(username="warehouse").first()
if not user:
user = User(username="warehouse", email="warehouse@example.com",
role="user", status="active")
user.set_password("x")
db.session.add(user)
db.session.flush()
if agent not in user.agents:
user.agents.append(agent)
db.session.commit()
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture
def unauthorized_headers(app):
"""无 Agent 权限的普通用户 JWT 请求头。"""
with app.app_context():
user = db.session.query(User).filter_by(username="no_perm").first()
if not user:
user = User(username="no_perm", email="no_perm@example.com", role="user", status="active")
user.set_password("x")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps):
"""POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。"""
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
})
assert response.status_code == 201
body = response.get_json()
assert body["success"] is True
data = body["data"]
assert data["precheck_id"].startswith("TPC-")
assert data["precheck_hash"].startswith("sha256:")
assert data["estimated_erp_write_count"] == 2
assert body.get("request_id")
def test_create_precheck_requires_authentication(client):
"""未认证 → 401(envelope error)。"""
response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]})
assert response.status_code == 401
assert response.get_json()["success"] is False
def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers):
"""无 in_transit_transfer Agent 权限 → 403。"""
response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={
"source_codes": ["DBS-AWSBI"],
})
assert response.status_code == 403
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps):
"""持有 Agent 权限的仓库管理员可创建预检。"""
response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
})
assert response.status_code == 201
assert response.get_json()["data"]["precheck_id"]
def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps):
"""缺少 source_codes → 400 参数错误。"""
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"})
assert response.status_code == 400
assert response.get_json()["success"] is False
def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
"""GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers)
assert restored.status_code == 200
body = restored.get_json()["data"]
assert body["summary"]["precheck_hash"] == created["precheck_hash"]
assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"}
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
"""未知 precheck → 404。"""
response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers)
assert response.status_code == 404
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
"""执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
)
assert executed.status_code == 201
run_no = executed.get_json()["data"]["run_no"]
assert run_no.startswith("RUN-")
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers)
assert run.status_code == 200
result = run.get_json()["data"]["result"]
assert len(result["erp_documents"]) == 2
assert result["exceptions"] == []
def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps):
"""预检未就绪时执行 → 400 领域错误,不产生 Run。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
with app.app_context():
from app.models import TransferPrecheck
precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first()
precheck.status = "prechecking"
db.session.commit()
response = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001"]},
)
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps):
"""取消缺少原因 → 400。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={},
)
run_no = executed.get_json()["data"]["run_no"]
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""})
assert response.status_code == 400
def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps):
"""取消未开始项并保留成功单据。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
)
run_no = executed.get_json()["data"]["run_no"]
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
with app.app_context():
from app.models import TransferInvoiceItem, TransferRun
run = TransferRun.query.filter_by(run_no=run_no).first()
run.status = "executing"
item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first()
item.status = "ready_to_execute"
item.erp_document_no = None
db.session.commit()
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={
"reason": "货源调整,停止剩余",
})
assert response.status_code == 200
assert response.get_json()["data"]["cancelled_count"] == 1
def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps):
"""人工关闭缺少原因 → 400。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
item.status = "blocked_recoverable"
item.result_code = "blocked_quantity_mismatch"
db.session.commit()
item_id = item.id
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={"reason": ""})
assert response.status_code == 400
def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
"""人工关闭成功 → 状态 manually_closed。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
item.status = "blocked_recoverable"
item.result_code = "blocked_quantity_mismatch"
db.session.commit()
item_id = item.id
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={
"reason": "线下已处理",
})
assert response.status_code == 200
assert response.get_json()["data"]["status"] == "manually_closed"
def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps):
"""下载异常 Excel → 200 xlsx,且记录访问审计。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
)
run_no = executed.get_json()["data"]["run_no"]
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
assert response.status_code == 200
assert response.content_type.startswith("application/vnd.openxmlformats")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXCEL_DOWNLOADED").first()
assert audit is not None
assert audit.run_no == run_no
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载收料来源文件 → 200(zip),记录访问审计。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
)
run_no = executed.get_json()["data"]["run_no"]
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
assert response.status_code == 200
assert response.content_type.startswith("application/zip")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first()
assert audit is not None
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
)
run_no = executed.get_json()["data"]["run_no"]
response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers)
assert response.status_code == 200
assert "csv" in response.content_type
assert b"INV-001" in response.data
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first()
assert audit is not None
def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps):
"""无权限下载 → 403(越权检查)。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={},
)
run_no = executed.get_json()["data"]["run_no"]
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
f"{API_PREFIX}/runs/{run_no}/erp-inventory",
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
response = client.get(path, headers=unauthorized_headers)
assert response.status_code == 403, path
def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps):
"""前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。"""
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
executed = client.post(
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
headers=admin_headers, json={
"invoice_nos": ["INV-001"],
"from_warehouse": "FAKE-TRANSIT",
"to_warehouse": "FAKE-HUB",
"quantity": "1",
},
)
assert executed.status_code == 201
run_no = executed.get_json()["data"]["run_no"]
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"]
documents = run["result"]["erp_documents"]
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
assert documents[0]["to_warehouse"] == "HUB-CN01"
assert documents[0]["total_quantity"] == "1200"
def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps):
"""待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。"""
# 预检含 1 个数量不一致(blocked)项
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
item.status = "blocked_recoverable"
item.result_code = "blocked_quantity_mismatch"
item.result_message = "收料 1200 / ERP 1000"
db.session.commit()
listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
assert listed.status_code == 200
invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]}
assert "INV-001" in invoice_set
assert "INV-002" not in invoice_set # 可执行项不在待处理池
assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"}
summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers)
assert summary.status_code == 200
assert summary.get_json()["data"]["recoverable"] >= 1
def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthorized_headers, transfer_deps):
"""无权限访问待处理池 → 403(越权检查)。"""
response = client.get(f"{API_PREFIX}/backlog", headers=unauthorized_headers)
assert response.status_code == 403
def test_list_transfer_sources(app, client, admin_headers):
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
assert response.status_code == 200
sources = response.get_json()["data"]
assert isinstance(sources, list)
# 测试种子来源 DSV360_AWSDU(dbs)应在列表中
assert any(item["source_code"] == "DSV360_AWSDU" for item in sources)
for item in sources:
assert item["source_code"]
assert item["platform"] in {"dbs", "crane"}
assert item["enabled"] is True
def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
"""无权限查看来源实例 → 403。"""
response = client.get(f"{API_PREFIX}/sources", headers=unauthorized_headers)
assert response.status_code == 403
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
assert response.status_code == 200
data = response.get_json()["data"]
assert "runs" in data and "items" in data and "backlog" in data
assert "notification_failed_runs" in data["runs"]
@@ -0,0 +1,146 @@
"""tests/api/test_integration_connector_api.py
用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、
interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。
依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。
逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.integration_connector.transports.base import IntegrationCallResult
from app.services.integration_connector.gateway import set_capability_gateway
API_PREFIX = "/api/integration-connector"
class FakeTransport:
connector_type = "rest"
def call(self, *, client, interface, request):
return {"found": True, "quantity": "100"}
class _FakeGateway:
"""纯替代网关:call 直接返回,不解析绑定;transports 供连接测试。"""
def __init__(self):
self.transports = {"rest": FakeTransport()}
def call(self, **kwargs):
return IntegrationCallResult(status="success", data={"found": True, "quantity": None})
@pytest.fixture
def admin_headers(app):
with app.app_context():
user = db.session.query(User).filter_by(username="admin").first()
if not user:
user = User(username="admin", email="admin@example.com", role="admin", status="active")
user.set_password("admin")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture
def plain_headers(app):
with app.app_context():
user = db.session.query(User).filter_by(username="plain").first()
if not user:
user = User(username="plain", email="plain@example.com", role="user", status="active")
user.set_password("x")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture
def fake_gateway():
gw = _FakeGateway()
set_capability_gateway(gw)
yield gw
set_capability_gateway(None)
def _params():
return {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
def test_list_capabilities(app, client, admin_headers):
"""GET /capabilities → 200,含 3 个在途调拨能力。"""
response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers)
assert response.status_code == 200
names = {item["name"] for item in response.get_json()["data"]}
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
def test_create_and_list_client_instance(app, client, admin_headers):
"""POST /client-instances → 201;GET 列表可查。"""
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "ERP-T100", "name": "T100 ERP", "connector_type": "soap", "environment": "prod",
"config_json": {"endpoint": "https://t100.invalid/ws"},
})
assert created.status_code == 201
assert created.get_json()["data"]["code"] == "ERP-T100"
listed = client.get(f"{API_PREFIX}/client-instances", headers=admin_headers)
assert listed.status_code == 200
assert any(item["code"] == "ERP-T100" for item in listed.get_json()["data"])
def test_client_instance_invalid_connector_type(app, client, admin_headers):
"""非法 connector_type → 400。"""
response = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "X", "name": "x", "connector_type": "ftp",
})
assert response.status_code == 400
def test_call_capability_success(app, client, admin_headers, fake_gateway):
"""POST /capabilities/<name> → 200 success。"""
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
headers=admin_headers, json={"params": _params(), "context": {}})
assert response.status_code == 200
data = response.get_json()["data"]
assert data["status"] == "success"
assert data["data"]["found"] is True
def test_call_capability_rejects_interface_id(app, client, admin_headers, fake_gateway):
"""body 携带 interface_id → 400(禁止覆盖 Binding)。"""
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
headers=admin_headers, json={"params": _params(), "context": {}, "interface_id": "X"})
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_ID_NOT_ALLOWED"
def test_call_requires_authentication(client):
"""未认证 → 401。"""
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
json={"params": _params()})
assert response.status_code == 401
def test_admin_only_forbidden(app, client, plain_headers):
"""普通用户访问 Admin API → 403。"""
response = client.get(f"{API_PREFIX}/client-instances", headers=plain_headers)
assert response.status_code == 403
def test_client_instance_test_connection(app, client, admin_headers, fake_gateway):
"""POST /client-instances/<code>/test → 200(用注入的 Fake transport)。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-A", "name": "client", "connector_type": "rest", "environment": "prod",
"config_json": {"endpoint": "https://erp.invalid"},
})
response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers)
assert response.status_code == 200
assert response.get_json()["data"]["ok"] is True
+71
View File
@@ -651,6 +651,77 @@ def client(app):
return app.test_client()
@pytest.fixture
def dbs_ready_file() -> dict:
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_no": "REC-20260806-001",
"file_version": "v3",
"checksum": "d" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
],
}
@pytest.fixture
def crane_ready_file() -> dict:
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_no": "REC-20260806-002",
"file_version": "v4",
"checksum": "c" * 64,
"status": "ready",
"rows": [
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
],
}
@pytest.fixture
def same_day_receipt_file() -> dict:
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_no": "REC-20260806-003",
"file_version": "v2",
"checksum": "s" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
"material_name": "连接器组件", "specification": "C 型",
"receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"},
],
}
@pytest.fixture
def transfer_db(app):
"""请求 app 后返回 db 实例;表由 create_all/drop_all 随 app 生命周期隔离。"""
from app import db
return db
@pytest.fixture
def admin_headers():
return {
@@ -0,0 +1,101 @@
"""在途调拨预检 Job Handler 测试(L1)。
用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动
precheck_service 落库更新预检状态;缺失 precheck 时报错。
依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。
逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。
"""
from __future__ import annotations
import app.jobs.handlers # noqa: F401 —— 触发 @register_handler 注册
import pytest
from app import db
from app.jobs.registry import get_handler
from app.jobs.types import JobType
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer.precheck_service import create_precheck
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
@pytest.fixture
def transfer_deps(monkeypatch, dbs_ready_file):
"""注入 Fake 依赖并预置库存。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
return deps
def test_precheck_job_type_registered():
"""in_transit_transfer_precheck handler 必须注册于 JobType 注册表。"""
handler = get_handler(JobType.TRANSFER_PRECHECK)
assert handler is not None
def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps):
"""handler 执行后预检状态进入 ready_to_execute,明细落库。"""
summary = create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
)
handler = get_handler(JobType.TRANSFER_PRECHECK)
handler(None, {"precheck_id": summary.precheck_id})
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
assert precheck is not None
assert precheck.status == "ready_to_execute"
assert precheck.precheck_hash.startswith("sha256:")
assert len(precheck.items) == 2
def test_precheck_job_handler_missing_precheck_raises(transfer_db):
"""缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。"""
handler = get_handler(JobType.TRANSFER_PRECHECK)
with pytest.raises(RuntimeError):
handler(None, {"precheck_id": "TPC-NOT-EXIST"})
def test_run_and_item_job_types_registered():
"""TRANSFER_RUN / TRANSFER_ITEM handler 必须注册。"""
assert get_handler(JobType.TRANSFER_RUN) is not None
assert get_handler(JobType.TRANSFER_ITEM) is not None
def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps):
"""run handler 执行预检并创建成功 Run。"""
summary = create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
)
handler = get_handler(JobType.TRANSFER_RUN)
handler(None, {"precheck_id": summary.precheck_id})
from app.models import TransferRun as RunModel
run = db.session.query(RunModel).filter(
RunModel.status != "prechecking",
).order_by(RunModel.id.desc()).first()
assert run is not None
assert run.status == "success"
def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps):
"""item handler 执行单个 Invoice 写入并置 success。"""
summary = create_precheck(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
from app.services.in_transit_transfer.orchestrator import create_execution_run
create_execution_run(precheck, deps=transfer_deps, actor_id=None)
item = db.session.query(TransferInvoiceItem).filter_by(
invoice_no="INV-001",
).first()
handler = get_handler(JobType.TRANSFER_ITEM)
handler(None, {"item_id": item.id})
refreshed = db.session.get(TransferInvoiceItem, item.id)
assert refreshed.status == "success"
assert refreshed.erp_document_no
@@ -0,0 +1,53 @@
"""在途调拨性能与规模测试(Phase 4,L6 子集)。
用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。
依赖:transfer_db、precheck_service、repo_fakes。
逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。
"""
from __future__ import annotations
import time
import pytest
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _bulk_file(count: int) -> dict:
"""生成 count 行收料文件(每 Invoice 单行)。"""
rows = []
for index in range(1, count + 1):
rows.append({
"sheet": "Receipt",
"row_no": index,
"invoice_no": f"INV-BULK-{index:04d}",
"material_no": f"MAT-{index:04d}",
"material_name": "批量物料",
"specification": "T-100",
"receipt_date": "2026-08-05",
"receipt_quantity": "100",
"source_code": "DBS-AWSBI",
})
return {
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
"file_no": "REC-BULK", "file_version": "v1", "checksum": "b" * 64,
"status": "ready", "rows": rows,
}
def test_bulk_precheck_300_invoices(transfer_db):
"""300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。"""
deps, erp, _ = make_transfer_deps(_bulk_file(300))
for index in range(1, 301):
erp.seed_inventory(f"INV-BULK-{index:04d}", "100")
started = time.perf_counter()
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
elapsed = time.perf_counter() - started
assert summary.counts.executable_count == 300
assert summary.counts.file_invoice_count == 300
restored = restore_precheck(summary.precheck_id)
assert len(restored["items"]) == 300
print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s")
@@ -0,0 +1 @@
"""在途仓自动调拨 Agent 领域测试包。"""
@@ -0,0 +1,44 @@
"""在途调拨测试断言辅助。
用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。
依赖:fakes.ErpCallRecord。
逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP
def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None:
"""断言 ERP 调用次数(可按 Invoice 过滤)。"""
calls = erp.calls(invoice_no=invoice_no)
assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}"
def assert_erp_write_zero(erp: FakeERP) -> None:
"""断言没有任何 ERP 写调用(fail-closed 场景通用断言)。"""
writes = erp.write_calls()
assert not writes, f"unexpected ERP write calls: {writes}"
def assert_call_fields(record: ErpCallRecord) -> None:
"""断言单次 ERP 调用携带全部必需追踪字段。"""
assert record.operation_id
assert record.invoice_no
assert record.erp_org
assert record.from_warehouse
assert record.to_warehouse
assert isinstance(record.quantity, Decimal)
assert record.call_seq > 0
assert record.returned_status
def assert_audit_complete(event: dict[str, Any]) -> None:
"""断言一条审计事件字段完整(操作者、关联、前后快照、Hash)。"""
for key in ("event_type", "aggregate_type", "aggregate_id", "actor_type", "operation_id",
"request_id", "before_hash", "after_hash", "event_hash"):
assert event.get(key), f"audit event missing {key}: {event}"
@@ -0,0 +1,39 @@
"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
same_day_receipt_file),并组装 FakeERP/FakeRPA/FakeWeCom。
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
"""
from __future__ import annotations
import pytest
from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom
@pytest.fixture
def fixed_clock() -> FakeClock:
"""固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。"""
return FakeClock()
@pytest.fixture
def erp_fake() -> FakeERP:
"""FakeERP:账面库存与写响应全部可注入,调用记录可断言。"""
return FakeERP()
@pytest.fixture
def rpa_fake() -> FakeRPA:
"""FakeRPA:按来源实例独立注入失败/延迟。"""
return FakeRPA()
@pytest.fixture
def wecom_fake() -> FakeWeCom:
"""FakeWeCom:记录投递事实,可注入附件失败。"""
return FakeWeCom()
@@ -0,0 +1,63 @@
"""在途调拨领域测试的对象工厂。
用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。
依赖:标准库(dataclasses / decimal)。
逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
@dataclass(frozen=True)
class ReceiptRow:
"""单行收料文件记录(含 Sheet/行号追溯证据)。"""
sheet: str = "Receipt"
row_no: int = 1
invoice_no: str = "INV-001"
material_no: str = "MAT-001"
material_name: str = "连接器组件"
specification: str = "A 型 / 24PIN"
receipt_date: str = "2026-08-05"
receipt_quantity: str = "1200"
source_code: str = "DBS-AWSBI"
def to_dict(self) -> dict[str, Any]:
"""转 dict,供 parser/aggregator 输入。"""
return {
"sheet": self.sheet,
"row_no": self.row_no,
"invoice_no": self.invoice_no,
"material_no": self.material_no,
"material_name": self.material_name,
"specification": self.specification,
"receipt_date": self.receipt_date,
"receipt_quantity": self.receipt_quantity,
"source_code": self.source_code,
}
def make_invoice_item(
*,
invoice_no: str = "INV-001",
source_code: str = "DBS-AWSBI",
material_no: str = "MAT-001",
receipt_quantity: Decimal | str | int = "1200",
erp_quantity: Decimal | str | int | None = "1200",
receipt_date: str = "2026-08-05",
) -> dict[str, Any]:
"""构造一条预检明细项(默认严格匹配、可执行)。"""
return {
"invoice_no": invoice_no,
"source_code": source_code,
"material_no": material_no,
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"receipt_date": receipt_date,
"receipt_quantity": Decimal(str(receipt_quantity)),
"erp_quantity": None if erp_quantity is None else Decimal(str(erp_quantity)),
}
@@ -0,0 +1,242 @@
"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。
用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支,
并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。
依赖:标准库(dataclasses / decimal / zoneinfo)。
逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据;
create_transfer 按注入的 scenario 返回 success / duplicate_success /
business_failed / timeout_before_commit / timeout_after_commit;
所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、
来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from typing import Any
from zoneinfo import ZoneInfo
from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError
class FakeClock:
"""固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。"""
def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None:
self.now_value = datetime.fromisoformat(iso)
def now(self) -> datetime:
"""返回当前固定时刻(带 Asia/Shanghai 时区)。"""
return self.now_value
def advance(self, *, seconds: int = 0, days: int = 0) -> None:
"""按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。"""
self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
if seconds:
self.now_value = self.now_value + timedelta(seconds=seconds)
if days:
self.now_value = self.now_value + timedelta(days=days)
@dataclass(frozen=True)
class ErpCallRecord:
"""FakeERP 单次调用的事实记录;测试断言优先读取该记录。"""
operation_id: str
invoice_no: str
erp_org: str
from_warehouse: str
to_warehouse: str
quantity: Decimal
call_seq: int
returned_status: str
method: str
document_no: str | None = None
class FakeERP:
"""可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。"""
def __init__(self) -> None:
self.inventory: dict[str, dict[str, Any]] = {}
self.documents: dict[str, str] = {}
self.verified_posted: dict[str, bool] = {}
self.query_scenario: str = "normal"
self.write_scenario: str = "success"
# 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。
self.write_scenarios: dict[str, str] = {}
self.call_log: list[ErpCallRecord] = []
self._seq = 0
# -- 控制注入 ----------------------------------------------------------
def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None:
"""设置指定 Invoice 的账面库存。"""
self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))}
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
"""预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。"""
self.documents[str(invoice_no).strip()] = document_no
self.verified_posted[str(invoice_no).strip()] = posted
def set_query_scenario(self, scenario: str) -> None:
"""normal | inventory_not_found | timeout。"""
self.query_scenario = scenario
def set_write_scenario(self, scenario: str) -> None:
"""success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。"""
self.write_scenario = scenario
# -- ERP 能力 ----------------------------------------------------------
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) -> dict[str, Any]:
"""按 Invoice 返回账面库存;timeout 场景抛超时异常。"""
self._seq += 1
key = str(invoice_no).strip()
if self.query_scenario == "timeout":
raise TimeoutError(f"query timeout operation_id={operation_id}")
if self.query_scenario == "inventory_not_found" or key not in self.inventory:
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "inventory_not_found", "query_inventory")
self.call_log.append(record)
return {"found": False, "quantity": Decimal("0")}
qty = self.inventory[key]["quantity"]
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "success", "query_inventory")
self.call_log.append(record)
return {"found": True, "quantity": qty}
def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int,
invoice_no: str, erp_org: str, from_warehouse: str,
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
"""原子建单/审核/过账;按注入场景返回结果并记录调用。"""
self._seq += 1
key = str(invoice_no).strip()
scenario = self.write_scenarios.get(key, self.write_scenario)
if scenario == "timeout_before_commit":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "timeout_before_commit", "create_transfer")
self.call_log.append(record)
raise ErpWriteTimeoutError(
"write timeout before commit", committed=False, operation_id=operation_id,
)
if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit":
# 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。
self.documents.setdefault(key, f"TRF-{self._seq:05d}")
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "timeout_after_commit", "create_transfer",
self.documents[key])
self.call_log.append(record)
raise ErpWriteTimeoutError(
"write timeout after commit", committed=True,
document_no=self.documents[key], operation_id=operation_id,
)
if scenario == "business_failed" or self.write_scenario == "business_failed":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "business_failed", "create_transfer")
self.call_log.append(record)
return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True}
if key in self.documents:
document_no = self.documents[key]
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "duplicate_success", "create_transfer",
document_no)
self.call_log.append(record)
return {
"status": "duplicate_success",
"document_no": document_no,
"verified_posted": self.verified_posted.get(key, False),
}
document_no = f"TRF-{self._seq:05d}"
self.documents[key] = document_no
self.verified_posted[key] = True
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "success", "create_transfer", document_no)
self.call_log.append(record)
return {"status": "success", "document_no": document_no, "posted": True}
def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int,
invoice_no: str, erp_org: str, from_warehouse: str,
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
"""核实重复 Invoice 原单状态(已审核过账/未确认)。"""
self._seq += 1
key = str(invoice_no).strip()
if key not in self.documents:
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "duplicate_unverified", "verify_duplicate")
self.call_log.append(record)
return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False}
document_no = self.documents[key]
posted = self.verified_posted.get(key, False)
status = "duplicate_success" if posted else "duplicate_unverified"
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, status, "verify_duplicate", document_no)
self.call_log.append(record)
return {"status": status, "document_no": document_no, "verified_posted": posted}
# -- 断言辅助 ----------------------------------------------------------
def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]:
"""按 Invoice 过滤调用记录(默认返回全部)。"""
if invoice_no is None:
return list(self.call_log)
return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()]
def write_calls(self) -> list[ErpCallRecord]:
"""仅返回 create_transfer 调用记录(写副作用断言)。"""
return [record for record in self.call_log if record.method == "create_transfer"]
class FakeRPA:
"""可独立按来源注入失败/延迟的收料 RPA 替身。"""
def __init__(self) -> None:
self.triggered: list[dict[str, Any]] = []
self.fail_on: set[str] = set()
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次来源收料抓取并记录。"""
self.triggered.append({
"source_code": source_code,
"business_date": business_date,
"reason": reason,
})
if source_code in self.fail_on:
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
class FakeWeCom:
"""企业微信通知替身;记录投递事实,可注入附件失败。"""
def __init__(self) -> None:
self.deliveries: list[dict[str, Any]] = []
self.attach_fail = False
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""发送一次汇总通知;附件失败时返回 failed 但不抛异常。"""
if self.attach_fail and excel_path:
record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
self.deliveries.append(record)
return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path}
self.deliveries.append(record)
return {"status": "success"}
@dataclass
class FakeAuditSink:
"""审计落点替身;记录 before/after、Diff、Hash 与关联上下文。"""
events: list[dict[str, Any]] = field(default_factory=list)
def append(self, event: dict[str, Any]) -> None:
"""追加一条审计事件 dict。"""
self.events.append(event)
def utc_now_iso() -> str:
"""返回当前 UTC 时间的 ISO 字符串(测试断言用)。"""
return datetime.now(timezone.utc).isoformat()
@@ -0,0 +1,88 @@
"""在途调拨测试的仓库/路由/依赖替身。
用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。
依赖:app.services.in_transit_transfer(仅类型)、fakes。
逻辑:所有替身只返回测试注入的值,不触碰真实存储;
TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。
"""
from __future__ import annotations
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps
from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA
class FakeReceiptFileRepository:
"""按 (source_code, business_date) 返回可注入 ready 文件。"""
def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None:
self.files = files or {}
self.lookups: list[tuple[str, str]] = []
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""记录查询并返回匹配文件。"""
self.lookups.append((source_code, business_date))
return self.files.get((source_code, business_date))
def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。"""
repository = FakeReceiptFileRepository()
for item in files:
repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile(
source_code=item["source_code"],
business_date=item["business_date"],
file_no=item["file_no"],
file_version=item["file_version"],
checksum=item["checksum"],
rows=tuple(item["rows"]),
)
return repository
def make_transfer_deps(
*files: dict,
erp: FakeERP | None = None,
rpa: FakeRPA | None = None,
routes: dict[str, RouteMapping] | None = None,
) -> tuple[TransferDeps, FakeERP, FakeRPA]:
"""组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。
Returns:
(deps, erp_fake, rpa_fake) 元组。
"""
erp = erp or FakeERP()
rpa = rpa or FakeRPA()
deps = TransferDeps(
file_repository=make_ready_repo(*files),
rpa_trigger=rpa,
route_resolver=FakeRouteResolver(routes=routes),
erp=ErpAdapter(transport=erp, default_org="HX-CN01"),
)
return deps, erp, rpa
class FakeRouteResolver:
"""按来源返回固定路由(ERP 组织/拨出仓/拨入仓)。"""
def __init__(self, routes: dict[str, RouteMapping] | None = None) -> None:
self.routes = routes if routes is not None else {
"DBS-AWSBI": RouteMapping(erp_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
"DBS-AWSSG": RouteMapping(erp_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
"CRANE-SZ": RouteMapping(erp_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"),
}
self.raised_on: set[str] = set()
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回来源路由;未配置来源抛 RouteNotResolvedError。"""
if source_code in self.raised_on:
raise RuntimeError("route resolution failed")
mapping = self.routes.get(source_code)
if mapping is None:
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
raise RouteNotResolvedError(source_code=source_code)
return mapping
@@ -0,0 +1,97 @@
"""在途调拨 MinIO 归档与 Hash 校验测试(Phase 4,L1)。
用途:验证归档对象写入 MinIO(Fake 替身)并持久化索引记录,
归档 Hash 可复算,损坏数据复核失败。
依赖:transfer_db、archive、FakeObjectStore。
逻辑:归档记录含 provider/bucket/key/sha256;校验重新下载并复算。
"""
from __future__ import annotations
import hashlib
import pytest
from app import db
from app.models import TransferArchive, TransferAuditEvent
from app.services.in_transit_transfer.archive import (
archive_snapshot,
restore_archive_bytes,
verify_archive_hash,
)
class FakeObjectStore:
"""内存对象存储替身(Key → bytes)。"""
def __init__(self) -> None:
self.objects: dict[str, bytes] = {}
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""保存对象并返回对象键。"""
self.objects[f"{bucket}/{key}"] = data
return key
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
return self.objects[f"{bucket}/{key}"]
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
self.objects.pop(f"{bucket}/{key}", None)
def _sample_data() -> bytes:
return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
def test_archive_snapshot_persists_index_and_audit(transfer_db):
"""归档后记录 TransferArchive(含 sha256)并写入审计。"""
store = FakeObjectStore()
data = _sample_data()
archive = archive_snapshot(
object_type="erp_inventory_snapshot",
object_id="TPC-20260806-001",
data=data,
original_filename="erp-inventory-20260806.csv",
content_type="text/csv",
object_store=store,
bucket="hxops-transfer",
)
assert archive.sha256 == hashlib.sha256(data).hexdigest()
assert archive.storage_provider == "minio"
assert archive.object_type == "erp_inventory_snapshot"
assert store.objects # 对象已写入存储
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first()
assert audit is not None
assert audit.aggregate_id == "TPC-20260806-001"
def test_verify_archive_hash_ok_and_corruption_detected(transfer_db):
"""Hash 复算一致;对象损坏 → 复核失败。"""
store = FakeObjectStore()
data = _sample_data()
archive = archive_snapshot(
object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data,
original_filename="a.csv", content_type="text/csv",
object_store=store, bucket="hxops-transfer",
)
assert verify_archive_hash(archive, object_store=store) is True
# 篡改存储对象后复核必须失败
key = f"{archive.storage_bucket}/{archive.storage_key}"
store.objects[key] = data + b"tampered"
assert verify_archive_hash(archive, object_store=store) is False
def test_restore_archive_bytes_roundtrip(transfer_db):
"""归档对象可恢复为原始字节。"""
store = FakeObjectStore()
data = _sample_data()
archive = archive_snapshot(
object_type="erp_inventory_snapshot", object_id="OBJ-2", data=data,
original_filename="a.csv", content_type="text/csv",
object_store=store, bucket="hxops-transfer",
)
restored = restore_archive_bytes(archive, object_store=store)
assert restored == data
@@ -0,0 +1,145 @@
"""在途调拨审计完整性测试(L0 纯单元 + 一次 DB 落库冒烟)。
用途:验证审计快照脱敏(Secret 不进快照/Hash)、Hash 可复算、Diff 语义正确,
以及审计事件携带操作者、operation_id、request_id 等关联上下文。
依赖:app.services.in_transit_transfer.audit(纯函数)+ transfer_db(模型冒烟)。
逻辑:L0 部分不创建 Flask;模型冒烟用例请求 app fixture 验证落库字段。
"""
from __future__ import annotations
import pytest
from app.services.in_transit_transfer.audit import (
canonical_hash,
build_transfer_audit_event,
compute_event_hash,
sanitize_snapshot,
snapshot_diff,
)
@pytest.mark.pure_unit
def test_canonical_hash_is_deterministic():
"""相同快照两次计算 Hash 必须一致(键排序 + 紧凑 JSON)。"""
snapshot = {"invoice_no": "INV-001", "quantity": "1200", "org": "HX-CN01"}
assert canonical_hash(snapshot) == canonical_hash(snapshot)
@pytest.mark.pure_unit
def test_hash_changes_when_snapshot_changes():
"""任一字段变化 Hash 必须变化。"""
before = {"invoice_no": "INV-001", "quantity": "1200"}
after = {"invoice_no": "INV-001", "quantity": "1201"}
assert canonical_hash(before) != canonical_hash(after)
@pytest.mark.pure_unit
def test_hash_ignores_key_order():
"""字段顺序不影响 Hash。"""
a = {"x": 1, "y": 2}
b = {"y": 2, "x": 1}
assert canonical_hash(a) == canonical_hash(b)
@pytest.mark.pure_unit
def test_sanitize_snapshot_strips_secrets():
"""快照必须剔除密码/Token/密钥等敏感字段,绝不进入 Hash。"""
snapshot = {
"invoice_no": "INV-001",
"password": "P@ssw0rd",
"credential": {"api_key": "sk-xxx", "username_ciphertext": "abc"},
"webhook_url": "https://hooks.example/secret-token",
}
clean = sanitize_snapshot(snapshot)
serialized = str(clean)
assert "P@ssw0rd" not in serialized
assert "sk-xxx" not in serialized
assert "abc" not in serialized
assert "secret-token" not in serialized
assert clean["invoice_no"] == "INV-001"
@pytest.mark.pure_unit
def test_snapshot_diff_reports_added_removed_changed():
"""Diff 必须区分新增/删除/修改三类变化。"""
diff = snapshot_diff(
{"invoice_no": "INV-001", "quantity": "1200", "old_key": "x"},
{"invoice_no": "INV-001", "quantity": "1100", "new_key": "y"},
)
assert diff["changed"]["quantity"] == ("1200", "1100")
assert diff["removed"] == {"old_key": "x"}
assert diff["added"] == {"new_key": "y"}
@pytest.mark.pure_unit
def test_build_event_carries_actor_and_correlation_ids():
"""审计事件必须包含 actor、operation_id、request_id 与前后快照 Hash。"""
event = build_transfer_audit_event(
event_type="TRANSFER_CONFIRMED",
aggregate_type="transfer_item",
aggregate_id="item-1",
run_no="RUN-20260806-001",
precheck_no="TPC-20260806-001",
invoice_no="INV-001",
actor_type="user",
actor_id="u-42",
actor_role="warehouse_manager",
actor_display="李仓储",
request_id="req_001",
operation_id="op_001",
result="success",
before={"status": "prechecking"},
after={"status": "ready_to_execute"},
)
assert event.actor_id == "u-42"
assert event.operation_id == "op_001"
assert event.request_id == "req_001"
assert event.run_no == "RUN-20260806-001"
assert event.before_hash and event.after_hash and event.event_hash
@pytest.mark.pure_unit
def test_event_hash_recomputable_from_fields():
"""审计 Hash 必须可由存储字段复算(Phase 4 Hash 校验基础)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_EXECUTED",
aggregate_type="transfer_item",
aggregate_id="item-2",
run_no="RUN-20260806-001",
invoice_no="INV-002",
actor_type="worker",
operation_id="op_002",
result="success",
after={"erp_document_no": "TRF-10001"},
)
assert compute_event_hash(event) == event.event_hash
def test_audit_event_persists_with_required_fields(transfer_db):
"""DB 冒烟:审计事件可落库并回读(含 Hash 与关联字段)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_CREATED",
aggregate_type="transfer_run",
aggregate_id="RUN-20260806-001",
run_no="RUN-20260806-001",
actor_type="user",
actor_id="u-1",
operation_id="op_003",
request_id="req_003",
result="success",
after={"status": "queued"},
)
transfer_db.session.add(event)
transfer_db.session.commit()
from app.models import TransferAuditEvent
loaded = transfer_db.session.get(TransferAuditEvent, event.id)
assert loaded is not None
assert loaded.run_no == "RUN-20260806-001"
assert loaded.operation_id == "op_003"
assert loaded.event_hash == event.event_hash
# 复算一致率 100% 的落库断言
assert compute_event_hash(loaded) == loaded.event_hash
@@ -0,0 +1,75 @@
"""在途调拨历史待处理池与老化测试(Phase 3,L1)。
用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。
依赖:transfer_db、precheck_service、backlog_service、repo_fakes。
逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer.backlog_service import (
aging_level_for,
backlog_summary,
list_backlog,
)
from app.services.in_transit_transfer.precheck_service import create_precheck
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _blocked_precheck(dbs_ready_file):
"""构造含数量不一致(blocked)项的预检。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1000") # 1200 ≠ 1000 → blocked
erp.seed_inventory("INV-002", "1200") # executable
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
return summary
def test_aging_level_thresholds():
"""3/5/7 天老化阈值正确。"""
assert aging_level_for(0) == "normal"
assert aging_level_for(1) == "normal"
assert aging_level_for(2) == "normal"
assert aging_level_for(3) == "warn_3d"
assert aging_level_for(5) == "escalate_5d"
assert aging_level_for(7) == "critical_7d"
assert aging_level_for(10) == "critical_7d"
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
_blocked_precheck(dbs_ready_file)
items = list_backlog()
invoice_set = {item.invoice_no for item in items}
assert "INV-001" in invoice_set
assert "INV-002" not in invoice_set
def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
"""老化等级按明细更新日期计算。"""
_blocked_precheck(dbs_ready_file)
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
item.updated_at = datetime.utcnow() - timedelta(days=6)
db.session.commit()
items = list_backlog(now=datetime.utcnow())
target = next(item_dto for item_dto in items if item_dto.invoice_no == "INV-001")
assert target.age_days == 6
assert target.aging_level == "escalate_5d"
def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file):
"""汇总包含可恢复/已关闭/未知计数与老化分级。"""
_blocked_precheck(dbs_ready_file)
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
item.status = "manually_closed"
item.manually_closed_reason = "线下处理"
db.session.commit()
summary = backlog_summary()
assert summary.closed_count == 1
assert summary.recoverable_count == 0
@@ -0,0 +1,59 @@
"""在途调拨请求停止(取消)测试(Phase 2,L1)。
用途:验证停止剩余任务只取消未开始项、已成功单据保留、原因必填。
依赖:transfer_db、execution_service、cancellation、repo_fakes。
逻辑:取消前快照与原因写入审计;成功后不可取消。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.errors import ValidationError
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.cancellation import cancel_run
from app.services.in_transit_transfer.execution_service import execute_precheck
from app.services.in_transit_transfer.precheck_service import create_precheck
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _ready_precheck(dbs_ready_file):
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeERP"]).FakeERP()
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp)
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
return deps, summary
def test_cancel_requires_reason(transfer_db, dbs_ready_file):
"""取消原因必填;无副作用(不创建执行 Run)。"""
deps, summary = _ready_precheck(dbs_ready_file)
with pytest.raises(ValidationError):
cancel_run(run_no="RUN-X", reason="")
# 仅存在预检关联 Run(prechecking),无执行 Run
runs = db.session.query(TransferRun).all()
assert len(runs) == 1
assert runs[0].status != "executing"
def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file):
"""取消只作用于未开始项;已成功单据保留。"""
deps, summary = _ready_precheck(dbs_ready_file)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
# 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success
run.status = "executing"
item = db.session.query(TransferInvoiceItem).filter_by(
run_id=run.id, invoice_no="INV-002",
).first()
item.status = "ready_to_execute"
item.erp_document_no = None
db.session.commit()
result = cancel_run(run_no=outcome.run_no, reason="业务原因")
items = {i.invoice_no: i for i in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()}
assert items["INV-001"].status == "success" # 已成功单据保留
assert items["INV-002"].status == "cancelled" # 未开始项取消
assert result["cancelled_count"] == 1
@@ -0,0 +1,114 @@
"""在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。
用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、
stream 产出结构化卡片事件(transfer-precheck / transfer-result)。
依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。
逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。
"""
from __future__ import annotations
import pytest
from app.core.errors import ForbiddenError
from app.services.chat.action_registry import ACTION_AGENT_CODES, ensure_handlers_loaded, resolve_action_handler
from app.services.chat.action_schema import TurnInput
from app.services.chat.turn_context import TurnContext
from app.services.in_transit_transfer.chat_actions import (
ACTION_TRANSFER_EXECUTE,
ACTION_TRANSFER_PRECHECK,
TransferExecuteAction,
TransferPrecheckAction,
)
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
class _Agent:
"""带 agent_code 的假 Agent。"""
def __init__(self, agent_code: str) -> None:
self.agent_code = agent_code
self.id = 1
self.name = "test-agent"
class _User:
id = 99
def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext:
return TurnContext(
turn_id="turn-1",
run_id="run-1",
session_id="session-1",
request_id="req-1",
user=_User(),
agent=_Agent(agent_code),
input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload),
refs={},
)
def test_transfer_actions_registered():
"""两个 transfer action 必须注册。"""
ensure_handlers_loaded()
assert "transfer." in ACTION_AGENT_CODES
assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",)
assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK
assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE
def test_transfer_action_agent_permission_enforced():
"""transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。"""
ensure_handlers_loaded()
ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
with pytest.raises(ForbiddenError):
resolve_action_handler(ctx)
allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK
def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
"""transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {
"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06",
})))
assert len(events) == 1
event = events[0]
assert event.event == "message.completed"
assert event.data["message_type"] == "transfer-precheck"
payload = event.data["payload"]
assert payload["kind"] == "precheck"
assert payload["summary"]["estimated_erp_write_count"] == 2
assert {item["invoice_no"] for item in payload["items"]} == {"INV-001", "INV-002"}
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch):
"""transfer.execute 流式产出 transfer-result 卡片(按 ERP 单号聚合)。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
# 先跑预检拿 precheck_id
precheck_events = list(TransferPrecheckAction().stream(_ctx(
"in_transit_transfer", ACTION_TRANSFER_PRECHECK,
{"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"},
)))
precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"]
execute_events = list(TransferExecuteAction().stream(_ctx(
"in_transit_transfer", ACTION_TRANSFER_EXECUTE,
{"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]},
)))
assert len(execute_events) == 1
payload = execute_events[0].data["payload"]
assert payload["kind"] == "result"
assert payload["status"] == "success"
assert len(payload["run"]["result"]["erp_documents"]) == 2
@@ -0,0 +1,145 @@
"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。
用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
依赖:app.services.in_transit_transfer.contracts。
逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from app.services.in_transit_transfer.contracts import (
KNOWN_TRANSFER_ERROR_CODES,
TRANSFER_PERMISSION_DENIED,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_RESULT_UNKNOWN,
PrecheckCountsDTO,
PrecheckInvoiceItemDTO,
PrecheckSummaryDTO,
aggregate_erp_documents,
require_known_error_code,
)
pytestmark = pytest.mark.pure_unit
EXPECTED_ERROR_CODES = {
"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 test_error_codes_match_tdd_frozen_list():
"""TDD §7.3 冻结的 15 个错误码必须全部存在且唯一。"""
assert EXPECTED_ERROR_CODES <= KNOWN_TRANSFER_ERROR_CODES
assert len(KNOWN_TRANSFER_ERROR_CODES) == len(EXPECTED_ERROR_CODES)
def test_require_known_error_code_accepts_frozen_codes():
"""冻结错误码可被契约校验接受。"""
require_known_error_code(TRANSFER_QUANTITY_MISMATCH)
require_known_error_code(TRANSFER_PRECHECK_EXPIRED)
require_known_error_code(TRANSFER_RESULT_UNKNOWN)
require_known_error_code(TRANSFER_PERMISSION_DENIED)
def test_require_known_error_code_rejects_unknown():
"""未知错误码必须抛 ValueError。"""
with pytest.raises(ValueError):
require_known_error_code("TRANSFER_NO_SUCH_CODE")
def test_precheck_counts_dto_fields():
"""预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。"""
counts = PrecheckCountsDTO(
file_invoice_count=40, not_matured_count=8, prechecked_count=32,
executable_count=27, blocked_count=5,
)
assert counts.executable_count == 27
assert counts.not_matured_count == 8
def test_precheck_summary_dto_carries_estimate_and_hash():
"""预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。"""
summary = PrecheckSummaryDTO(
precheck_id="TPC-20260806-001",
status="ready_to_execute",
business_date="2026-08-06",
eligible_receipt_date_to="2026-08-05",
expires_at="2026-08-06T09:20:00+08:00",
counts=PrecheckCountsDTO(40, 8, 32, 27, 5),
estimated_transfer_quantity="18460",
estimated_erp_write_count=27,
precheck_hash="sha256:abc",
)
assert summary.estimated_transfer_quantity == "18460"
assert summary.estimated_erp_write_count == 27
assert summary.precheck_hash.startswith("sha256:")
def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
"""预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。"""
item = PrecheckInvoiceItemDTO(
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", invoice_no="INV-001",
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
result="executable",
)
assert item.from_warehouse == "DBS-TRANSIT"
assert item.to_warehouse == "HUB-CN01"
assert item.from_quantity == item.to_quantity
def test_aggregate_erp_documents_groups_by_document_no():
"""结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
items = [
PrecheckInvoiceItemDTO(
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", invoice_no="INV-001",
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"),
to_warehouse="HUB-CN01", to_quantity=Decimal("500"),
result="success", erp_document_no="TRF-10001",
),
PrecheckInvoiceItemDTO(
source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件",
specification="标准型 / 48V", invoice_no="INV-002",
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
result="success", erp_document_no="TRF-10001",
),
PrecheckInvoiceItemDTO(
source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组",
specification="SZ-8 / IP67", invoice_no="INV-008",
from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"),
to_warehouse="HUB-SH", to_quantity=Decimal("600"),
result="success", erp_document_no="TRF-10008",
),
]
documents = aggregate_erp_documents(items)
assert len(documents) == 2
by_no = {document.document_no: document for document in documents}
first = by_no["TRF-10001"]
assert first.material_count == 2
assert first.total_quantity == Decimal("1700")
assert first.from_warehouse == "DBS-TRANSIT"
assert first.to_warehouse == "HUB-CN01"
assert first.posting_status == "posted"
assert [line.invoice_no for line in first.lines] == ["INV-001", "INV-002"]
@@ -0,0 +1,78 @@
"""在途调拨日期成熟度策略测试(L0 纯单元)。
用途:验证 D+1 成熟规则、当天 not_matured、未来日期阻断与上海业务时区。
依赖:app.services.in_transit_transfer.date_policy(纯函数)。
逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。
"""
from __future__ import annotations
from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
import pytest
from app.services.in_transit_transfer.date_policy import (
business_date_now,
eligible_receipt_date_to,
maturity_status,
)
pytestmark = pytest.mark.pure_unit
BUSINESS_T = date(2026, 8, 6)
def test_same_day_receipt_is_not_matured():
"""当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。"""
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
def test_yesterday_receipt_is_eligible():
"""昨天(T-1)收料进入预检。"""
assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "eligible"
def test_older_receipt_is_eligible():
"""更早收料同样可预检。"""
assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible"
def test_future_receipt_is_blocked():
"""未来日期收料返回结构化阻断值。"""
assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future"
def test_maturity_status_accepts_iso_strings():
"""字符串日期与 date 对象等价。"""
assert maturity_status("2026-08-05", "2026-08-06") == "eligible"
assert maturity_status("2026-08-06", "2026-08-06") == "not_matured"
def test_eligible_receipt_date_to_is_previous_day():
"""可调拨收料截止日期 = 业务日期 - 1 天。"""
assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 5)
def test_business_date_now_uses_shanghai_across_utc_midnight():
"""UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。"""
moment = datetime(2026, 8, 5, 17, 0, 0, tzinfo=timezone.utc)
assert business_date_now(moment) == date(2026, 8, 6)
def test_business_date_now_naive_moment_treated_as_utc():
"""naive 时刻按 UTC 兼容处理(与 business_numbering_service 口径一致)。"""
moment = datetime(2026, 8, 6, 0, 30, 0)
assert business_date_now(moment) == date(2026, 8, 6)
def test_business_date_now_defaults_to_shanghai_now():
"""无参调用返回 Asia/Shanghai 当前日期。"""
today = datetime.now(ZoneInfo("Asia/Shanghai")).date()
assert business_date_now() == today
def test_invalid_date_string_raises():
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
with pytest.raises(ValueError):
maturity_status("2026/13/99", BUSINESS_T)
@@ -0,0 +1,219 @@
"""在途调拨 ERP Adapter 查询契约测试(L0 纯单元)。
用途:验证 query_inventory 请求携带全部必需追踪字段(operation_id/run_no/
attempt_no/invoice_no/erp_org/拨出仓/拨入仓/数量),并正确分类
有库存/无库存/超时;SOAP 传输在 WSDL 未冻结前 fail-closed。
依赖:app.services.in_transit_transfer.erp_adapter + fakes.FakeERP。
逻辑:Adapter 是唯一 ERP 访问边界;测试注入 FakeERP 作为 transport。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from app.services.in_transit_transfer.erp_adapter import (
ErpAdapter,
ErpNotFrozenError,
ErpQueryTimeoutError,
ErpTransport,
ErpWriteTimeoutError,
InventoryQuery,
SoapErpTransport,
TransferWriteResult,
)
from tests.services.in_transit_transfer.assertions import assert_call_fields
from tests.services.in_transit_transfer.fakes import FakeERP
pytestmark = pytest.mark.pure_unit
def _adapter(erp: FakeERP) -> ErpAdapter:
return ErpAdapter(transport=erp, default_org="HX-CN01")
def _query_kwargs(**overrides):
kwargs = {
"operation_id": "op-001",
"run_no": "RUN-20260806-001",
"attempt_no": 1,
"invoice_no": "INV-001",
"erp_org": "HX-CN01",
"from_warehouse": "DBS-TRANSIT",
"to_warehouse": "HUB-CN01",
"quantity": Decimal("1200"),
}
kwargs.update(overrides)
return kwargs
def test_query_inventory_found():
"""有库存 → InventoryQuery(found=True, quantity)。"""
erp = FakeERP()
erp.seed_inventory("INV-001", "1200")
adapter = _adapter(erp)
result = adapter.query_inventory(**_query_kwargs())
assert isinstance(result, InventoryQuery)
assert result.found is True
assert result.quantity == Decimal("1200")
def test_query_inventory_not_found():
"""无库存 → found=False。"""
erp = FakeERP()
adapter = _adapter(erp)
result = adapter.query_inventory(**_query_kwargs())
assert result.found is False
assert result.quantity is None
def test_query_request_carries_all_trace_fields():
"""调用记录包含全部追踪字段(提示词 §五 强制字段)。"""
erp = FakeERP()
erp.seed_inventory("INV-001", "1200")
adapter = _adapter(erp)
adapter.query_inventory(**_query_kwargs())
records = erp.calls(invoice_no="INV-001")
assert len(records) == 1
assert_call_fields(records[0])
assert records[0].operation_id == "op-001"
assert records[0].erp_org == "HX-CN01"
assert records[0].from_warehouse == "DBS-TRANSIT"
assert records[0].to_warehouse == "HUB-CN01"
def test_query_timeout_classified_retryable():
"""查询超时 → ErpQueryTimeoutError(可重试,只读路径不落未知态)。"""
erp = FakeERP()
erp.set_query_scenario("timeout")
adapter = _adapter(erp)
with pytest.raises(ErpQueryTimeoutError) as excinfo:
adapter.query_inventory(**_query_kwargs())
assert excinfo.value.retryable is True
def test_soap_transport_fails_closed_before_wsdl_frozen():
"""WSDL/endpoint 未冻结 → SoapErpTransport 调用必须抛 ErpNotFrozenError。"""
transport = SoapErpTransport(config={})
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
with pytest.raises(ErpNotFrozenError):
adapter.query_inventory(**_query_kwargs())
def test_soap_transport_refuses_without_frozen_config():
"""未配置 endpoint 的传输对象直接拒绝查询。"""
transport = SoapErpTransport(config={})
with pytest.raises(ErpNotFrozenError):
transport.query_inventory(**_query_kwargs())
def test_request_payload_never_contains_credentials():
"""Adapter 请求体不得携带任何凭据字段(Secret 边界)。"""
class RecordingTransport:
def __init__(self) -> None:
self.seen: dict | None = None
def query_inventory(self, **kwargs):
self.seen = kwargs
return {"found": True, "quantity": Decimal("1200")}
def create_transfer(self, **kwargs):
self.seen = kwargs
return {"status": "success", "document_no": "TRF-1", "posted": True}
def verify_duplicate(self, **kwargs):
return {"status": "duplicate_success", "document_no": "TRF-1", "verified_posted": True}
transport = RecordingTransport()
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
adapter.query_inventory(**_query_kwargs())
serialized = str(transport.seen)
for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key"):
assert fragment not in serialized.lower()
# ---- Phase 2:create_transfer / verify_duplicate ---------------------------
def test_create_transfer_success():
"""成功写入 → TransferWriteResult(success, document_no)。"""
erp = FakeERP()
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert isinstance(result, TransferWriteResult)
assert result.status == "success"
assert result.document_no.startswith("TRF-")
def test_create_transfer_duplicate_success_when_posted():
"""重复 Invoice 且原单已审核过账 → duplicate_success(含原单号)。"""
erp = FakeERP()
erp.seed_document("INV-001", "TRF-00001", posted=True)
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert result.status == "duplicate_success"
assert result.document_no == "TRF-00001"
assert result.verified_posted is True
def test_create_transfer_duplicate_unverified_blocks():
"""重复 Invoice 但无法证明原单已过账 → duplicate_unverified(阻断)。"""
erp = FakeERP()
erp.seed_document("INV-001", "TRF-00001", posted=False)
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert result.status == "duplicate_unverified"
assert result.document_no == "TRF-00001"
assert result.verified_posted is False
def test_create_transfer_business_failed():
"""明确业务失败且原子回滚 → business_failed(不得产生单据)。"""
erp = FakeERP()
erp.set_write_scenario("business_failed")
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert result.status == "business_failed"
assert result.error_code == "ERP_BUSINESS_REJECT"
assert result.document_no is None
def test_create_transfer_timeout_before_commit_is_technical_failed():
"""提交前超时(可证明未落单)→ technical_failed,非 result_unknown。"""
erp = FakeERP()
erp.set_write_scenario("timeout_before_commit")
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert result.status == "technical_failed"
assert result.document_no is None
def test_create_transfer_timeout_after_commit_is_result_unknown():
"""提交后超时(无法确认是否落单)→ result_unknown,禁止自动重试。"""
erp = FakeERP()
erp.set_write_scenario("timeout_after_commit")
adapter = _adapter(erp)
result = adapter.create_transfer(**_query_kwargs())
assert result.status == "result_unknown"
assert result.document_no is not None # Fake 已知落单,但业务层视为无法确认
def test_verify_duplicate_returns_original_document():
"""verify_duplicate 获取原 ERP 单号并确认已过账。"""
erp = FakeERP()
erp.seed_document("INV-001", "TRF-OLD-1", posted=True)
adapter = _adapter(erp)
result = adapter.verify_duplicate(**_query_kwargs())
assert result.status == "duplicate_success"
assert result.document_no == "TRF-OLD-1"
def test_verify_duplicate_unverified_when_not_posted():
"""原单未确认过账 → duplicate_unverified。"""
erp = FakeERP()
erp.seed_document("INV-001", "TRF-OLD-1", posted=False)
adapter = _adapter(erp)
result = adapter.verify_duplicate(**_query_kwargs())
assert result.status == "duplicate_unverified"
assert result.verified_posted is False
@@ -0,0 +1,79 @@
"""在途调拨七 Sheet 异常 Excel 测试(Phase 3,L1)。
用途:验证异常 Excel 七 Sheet 齐全、内容按状态归类、原始行追溯存在、
Secret 明文不出现(凭据不出现在 Excel)。
依赖:transfer_db、execution_service、excel_export、openpyxl。
逻辑:以真实 Run 数据生成 workbook 字节并回读断言。
"""
from __future__ import annotations
import io
import pytest
from openpyxl import load_workbook
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook
from app.services.in_transit_transfer.execution_service import execute_precheck
from app.services.in_transit_transfer.precheck_service import create_precheck
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _executed_run(dbs_ready_file):
"""构造含 1 成功 + 1 业务失败(未生成单据)的 Run。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_inventory("INV-001", "1200")
erp.seed_inventory("INV-002", "1200")
erp.write_scenarios["INV-001"] = "business_failed"
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
return outcome.run_no, deps
def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file):
"""异常 Excel 必须包含规格定义的 7 个 Sheet。"""
run_no, _ = _executed_run(dbs_ready_file)
data = build_exceptions_workbook(run_no)
workbook = load_workbook(io.BytesIO(data))
assert workbook.sheetnames == EXCEL_SHEET_NAMES
def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file):
"""业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。"""
run_no, _ = _executed_run(dbs_ready_file)
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
summary_sheet = workbook["执行汇总"]
summary_text = _sheet_text(summary_sheet)
assert "INV-002" in summary_text
failed_sheet = workbook["ERP技术失败"]
failed_text = _sheet_text(failed_sheet)
assert "INV-001" in failed_text
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file):
"""原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。"""
run_no, _ = _executed_run(dbs_ready_file)
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
trace_sheet = workbook["原始文件追溯"]
text = _sheet_text(trace_sheet)
assert "Receipt" in text and "10" in text
def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file):
"""Secret 明文不得出现在 Excel(密码/Token/密文片段)。"""
run_no, _ = _executed_run(dbs_ready_file)
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
for sheet in workbook.worksheets:
text = _sheet_text(sheet).lower()
for fragment in ("password", "secret", "token", "ciphertext", "api_key", "webhook"):
assert fragment not in text
def _sheet_text(sheet) -> str:
"""拼接 Sheet 全部单元格文本。"""
rows = []
for row in sheet.iter_rows(values_only=True):
rows.append(" ".join(str(cell) for cell in row if cell is not None))
return "\n".join(rows)
@@ -0,0 +1,224 @@
"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。
用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
选择子集执行、重复点击防重与按 ERP 单号投影最终结果。
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。
逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.core.errors import AppError
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
)
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
from app.services.in_transit_transfer.precheck_service import create_precheck
from tests.services.in_transit_transfer.fakes import FakeERP
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple:
"""创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。"""
deps, erp_fake, _ = make_transfer_deps(*files, erp=erp)
source_codes = source_codes or [files[0]["source_code"]]
summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps)
return deps, erp_fake, summary
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeERP:
"""按 Invoice 预置账面库存的 FakeERP。"""
erp = FakeERP()
for invoice_no, quantity in seeds:
erp.seed_inventory(invoice_no, quantity)
return erp
def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
return {
item.invoice_no: item
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
}
def test_execute_happy_path(transfer_db, dbs_ready_file):
"""两个可执行 Invoice → Run 成功,按 ERP 单号投影两张单据,Attempt 落库。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert outcome.status == "success"
assert outcome.run_no.startswith("RUN-")
assert len(outcome.result.erp_documents) == 2
assert outcome.result.exceptions == ()
items = _load_items(outcome.run_no)
assert all(item.status == "success" for item in items.values())
assert all(item.erp_document_no for item in items.values())
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter(
TransferInvoiceItem.run_id == run.id,
).all()
assert len([a for a in attempts if a.kind == "erp_write"]) == 2
def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file):
"""重复 Invoice(原单已过账)→ item duplicate_success + 原单号。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
erp.seed_document("INV-002", "TRF-OLD-002", posted=True)
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert outcome.status == "success"
items = _load_items(outcome.run_no)
assert items["INV-002"].status == "duplicate_success"
assert items["INV-002"].erp_document_no == "TRF-OLD-002"
# 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用
assert len(erp.write_calls()) == 2
def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file):
"""单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
erp.write_scenarios["INV-001"] = "business_failed"
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert outcome.status == "partial_failed"
items = _load_items(outcome.run_no)
assert items["INV-001"].status == "blocked_recoverable"
assert items["INV-002"].status == "success"
# 异常项进入结果页"未生成单据"区
assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions)
def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
"""result_unknown:状态终态、每 Invoice 写调用仅 1 次。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
erp.set_write_scenario("timeout_after_commit")
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert outcome.status == "partial_failed"
items = _load_items(outcome.run_no)
assert all(item.status == "result_unknown" for item in items.values())
# 禁止自动重试:每个 Invoice 写调用恰 1 次
assert len(erp.write_calls()) == 2
def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
"""预检未就绪(prechecking)→ 拒绝执行,ERP 写入为 0。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
precheck.status = "prechecking"
db.session.commit()
with pytest.raises(AppError) as excinfo:
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED
assert erp.write_calls() == []
def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
"""确认过期(超过 10 分钟)→ 拒绝执行,ERP 写入为 0。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
precheck.expires_at = datetime.utcnow() - timedelta(seconds=1)
db.session.commit()
with pytest.raises(AppError) as excinfo:
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
assert erp.write_calls() == []
def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
"""预检快照(数量)变化 → fail-closed,ERP 写入为 0。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first()
item.receipt_quantity = "999"
db.session.commit()
with pytest.raises(AppError) as excinfo:
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
assert erp.write_calls() == []
def test_execute_selected_subset_only(transfer_db, dbs_ready_file):
"""仅选择 INV-001 → 只写入该 Invoice。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"],
)
assert outcome.status == "success"
assert len(outcome.result.erp_documents) == 1
assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"]
def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file):
"""勾选当天收料项 → 拒绝,ERP 写入为 0。"""
deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"])
with pytest.raises(AppError):
execute_precheck(
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"],
)
assert erp_fake.write_calls() == []
def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
"""重复点击执行 → 第二次 409,不创建重复 Run。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
first = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
with pytest.raises(AppError) as excinfo:
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
assert excinfo.value.http_status == 409
# 只存在一个执行 Run(其余为预检关联 Run)
execution_runs = db.session.query(TransferRun).filter(
TransferRun.status != "prechecking",
).count()
assert execution_runs == 1
assert first.run_no
def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file):
"""写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
erp.seed_inventory("INV-001", "999") # 预检后库存变化
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
items = _load_items(outcome.run_no)
assert items["INV-001"].status == "blocked_recoverable"
assert items["INV-002"].status == "success"
assert [record.invoice_no for record in erp.write_calls()] == ["INV-002"]
def test_get_run_restores_document_projection(transfer_db, dbs_ready_file):
"""GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。"""
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
erp.write_scenarios["INV-001"] = "business_failed"
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
restored = get_run(outcome.run_no)
assert restored["run_no"] == outcome.run_no
assert len(restored["result"]["erp_documents"]) == 1
assert any(exc["invoice_no"] == "INV-001" for exc in restored["result"]["exceptions"])
@@ -0,0 +1,128 @@
"""在途调拨文件 Ready 复用与 RPA 触发测试(L0 纯单元)。
用途:验证当日 ready 文件可复用(不触发 RPA)、缺文件时同一来源只触发一次
RPA、存在活动 Source Job 时绑定已有任务、触发失败 fail-closed。
依赖:app.services.in_transit_transfer.file_preparation + fakes。
逻辑:仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身。
"""
from __future__ import annotations
import pytest
from app.services.in_transit_transfer.file_preparation import (
FilePreparationResult,
ReadyReceiptFile,
ReceiptFileRepository,
ensure_receipt_file_ready,
)
from tests.services.in_transit_transfer.fakes import FakeRPA
from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile:
return ReadyReceiptFile(
source_code=source_code,
business_date=business_date,
file_no=f"REC-{source_code}-001",
file_version="v3",
checksum="d" * 64,
rows=(),
)
def test_ready_file_reused_without_rpa_trigger():
"""当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。"""
repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
rpa = FakeRPA()
result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
assert result.stage == "file_ready"
assert result.file is not None
assert rpa.triggered == []
def test_missing_file_triggers_rpa_once():
"""缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。"""
repository = FakeReceiptFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
assert result.stage == "waiting_rpa_callback"
assert result.file is None
assert len(rpa.triggered) == 1
assert rpa.triggered[0]["source_code"] == "DBS-AWSBI"
def test_active_source_job_binds_existing_task_no_new_trigger():
"""存在活动 Source Job → 绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
assert result.stage == "waiting_rpa_callback"
assert rpa.triggered == []
def test_concurrent_requests_share_one_trigger():
"""并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
rpa = FakeRPA()
for _ in range(3):
result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
assert result.stage == "waiting_rpa_callback"
assert rpa.triggered == []
def test_without_active_key_each_call_triggers_once():
"""无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。"""
repository = FakeReceiptFileRepository()
rpa = FakeRPA()
ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
assert len(rpa.triggered) == 2
def test_rpa_trigger_failure_is_fail_closed():
"""RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。"""
repository = FakeReceiptFileRepository()
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
assert result.stage == "failed"
assert result.error_code == "RPA_TRIGGER_FAILED"
def test_dbs_and_crane_sources_isolated():
"""DBS 失败不影响 Crane 的文件准备(来源隔离)。"""
repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
dbs_result = ensure_receipt_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
crane_result = ensure_receipt_file_ready(
source_code="CRANE-SZ", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
assert dbs_result.stage == "failed"
assert crane_result.stage == "file_ready"
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more