This commit is contained in:
sophie committed 2026-09-08 08:58:14 +08:00
commit 21d41acf50
732 files changed
+55672 -15251

No files matched your search

+2 -2
View File
@@ -125,7 +125,7 @@ SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
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
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=3
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
@@ -147,7 +147,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/u
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
# 本地 RPA(scripts/rpa/inventory/inventory_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
+4 -4
View File
@@ -119,12 +119,12 @@ 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
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=3
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
@@ -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
+33 -2
View File
@@ -54,8 +54,6 @@ CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE={year}年设备合同书
CONTRACT_DMS_TEMP_FOLDER_NAME=暂存
CONTRACT_DMS_LOOKUP_WINDOW_DAYS=30
# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*)
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=727c3683-dcdb-4d62-a5b1-b164224162bc
CONTRACT_PAYMENT_ENABLED=true
CONTRACT_PAYMENT_OA_BASE_URL=http://192.168.100.221:8888
CONTRACT_PAYMENT_OA_USERNAME=AIuser
@@ -76,6 +74,21 @@ CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD=bm
CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD=zz
CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD=jfl
# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*)
VOUCHER_CHECK_LOCAL_ROOT=
VOUCHER_CHECK_SHARE_UNC=
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=
# VOUCHER_CHECK_ERP_DSN=
# VOUCHER_CHECK_ERP_USERNAME=
# VOUCHER_CHECK_ERP_PASSWORD=
VOUCHER_CHECK_DMS_BASE_URL=http://192.168.8.158:8071
VOUCHER_CHECK_DMS_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=727c3683-dcdb-4d62-a5b1-b164224162bc
VOUCHER_CHECK_DMS_USERNAME=AIuser
VOUCHER_CHECK_DMS_PASSWORD=123456
# chat回答的评分与评论
FEEDBACK_ENABLED=true
@@ -200,6 +213,24 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
# --- 9. 业务模块 ---
# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值)
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=3
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=3
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 表)
+2 -2
View File
@@ -160,7 +160,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
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
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
@@ -174,7 +174,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queu
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
+4
View File
@@ -45,6 +45,8 @@ def register_blueprints(app: Flask) -> None:
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
from app.api.contract_payment import contract_payment_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')
@@ -75,3 +77,5 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
@@ -26,10 +26,8 @@ from app.services.shipping_notice.customer_shadow_resolution import (
label_shadow_resolution,
)
from app.services.shipping_notice.customer_auto_resolution import (
correct_numbered_task_customer,
get_auto_resolution_metrics,
)
from app.services.shipping_notice.query_service import get_task_by_ref
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
@@ -287,32 +285,6 @@ def get_shipping_customer_shadow_report():
return jsonify(report)
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
@require_admin
def correct_shipping_numbered_task_customer():
"""管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。"""
data = request.get_json(silent=True) or {}
task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper()
if not task_ref:
raise ValidationError(
'Task reference is required',
code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED',
)
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc
task = get_task_by_ref(task_ref)
if task is None:
raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING')
return jsonify(correct_numbered_task_customer(
task,
customer_id=customer_id,
reason=str(data.get('reason') or ''),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customer-shadow-resolutions/<int:resolution_id>/label', methods=['PUT'])
@require_admin
def label_shipping_customer_shadow_resolution(resolution_id: int):
+8 -11
View File
@@ -234,25 +234,22 @@ def simulate_shipping_order_schema_derivation(version_id: int):
"""
对 Schema 版本派生规则做样本模拟(不创建或修改订单)。
请求体:lines[] 或 sample_ref=`extraction:<id>`;可选 derivation_rules。
事务:服务层只写入审计实体,本路由统一 commit。
硬切换后该能力已停用;line_no 由系统按单据内顺序生成。
"""
payload = service.simulate_derivation(
version_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
db.session.commit()
return _ok(payload)
@admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET'])
@require_admin
def list_shipping_order_schema_derivation_simulate_samples():
"""列出可供派生规则模拟的历史 Extraction 样本摘要。"""
limit = request.args.get('limit', 20, type=int)
return _ok(service.list_derivation_simulate_samples(limit=limit or 20))
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
@require_admin
+8 -1
View File
@@ -5,7 +5,7 @@ from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_kb_version
from app.services.training_config_service import create_config, delete_config, list_configs, list_resource_candidates, update_config
from app.services.training_config_service import create_config, delete_config, list_configs, list_resource_candidates, list_training_type_codes, update_config
@admin_bp.route("/training-configs", methods=["GET"])
@@ -14,6 +14,13 @@ def list_training_configs():
return jsonify(list_configs())
@admin_bp.route("/training-configs/types", methods=["GET"])
@require_admin
def list_published_training_types():
"""返回已发布培训类型的编码与名称,供管理端动态展示。"""
return jsonify(list_training_type_codes())
@admin_bp.route("/training-configs/resource-candidates", methods=["GET"])
@require_admin
def list_training_config_resource_candidates():
+17 -1
View File
@@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__)
# 子模块导入时在同一 Blueprint 上注册原有 URL。
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from .shared import ( # noqa: E402, F401
CHAT_USER_ATTACHMENT_LIMIT,
CHAT_USER_ATTACHMENT_MAX_SIZE,
CHAT_USER_ATTACHMENT_SOURCES,
CHAT_USER_ATTACHMENT_TYPES,
_merge_user_attachments_from_terminal_event,
_normalize_user_attachments,
)
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
register_chat_turn_routes(chat_bp)
__all__ = ['chat_bp']
__all__ = [
'chat_bp',
'CHAT_USER_ATTACHMENT_LIMIT',
'CHAT_USER_ATTACHMENT_MAX_SIZE',
'CHAT_USER_ATTACHMENT_SOURCES',
'CHAT_USER_ATTACHMENT_TYPES',
'_merge_user_attachments_from_terminal_event',
'_normalize_user_attachments',
]
+20 -6
View File
@@ -8,6 +8,7 @@ api/chat/sessions.py
from __future__ import annotations
from .shared import * # noqa: F403
from .shared import _normalize_user_attachments
from . import chat_bp
from .core import (
_chat_logs_for_session,
@@ -194,19 +195,32 @@ def get_chat_messages():
messages = []
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
raw_payload = log.payload if isinstance(log.payload, dict) else {}
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
assistant_payload = {
key: value
for key, value in raw_payload.items()
if key != 'user_attachments'
}
if log.query or user_attachments:
user_msg = {
'role': 'user',
'content': _user_facing_chat_query(log.query or '', agent_code=agent_code),
}
if user_attachments:
user_msg['attachments'] = user_attachments
messages.append(user_msg)
if (
not log.answer
and not log.message_type
and not log.payload
and not assistant_payload
):
continue
if (
log.query
and log.answer == log.query
and (not log.message_type or log.message_type == 'text')
and not log.payload
and not assistant_payload
):
continue
assistant_msg = {
@@ -220,8 +234,8 @@ def get_chat_messages():
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
assistant_msg['payload'] = log.payload
if assistant_payload:
assistant_msg['payload'] = assistant_payload
messages.append(assistant_msg)
return jsonify(messages)
+90
View File
@@ -12,6 +12,7 @@ import ntpath
import posixpath
import tempfile
import os
import re
import subprocess
import uuid
import json
@@ -41,6 +42,95 @@ from app.core.errors import (
)
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
"""
if not isinstance(value, list):
return []
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
basename = re.split(r'[\\/]+', raw_name)[-1]
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
attachment_type = str(item.get('type') or '').strip().lower()
source = str(item.get('source') or '').strip().lower()
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
continue
snapshot = {
'name': name,
'type': attachment_type,
'source': source,
}
extension = str(item.get('extension') or '').strip().lower()
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
snapshot['extension'] = extension
try:
size = int(item.get('size')) if item.get('size') is not None else None
except (TypeError, ValueError):
size = None
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
snapshot['size'] = size
normalized.append(snapshot)
return normalized
def _merge_user_attachments_from_terminal_event(
event_data: dict,
*,
user_id: int,
agent_id: int,
session_id: str,
user_attachments: list[dict],
) -> bool:
"""
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
Args:
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
session_id: 当前 HXOPS 本地会话 ID。
user_attachments: 已完成白名单校验的附件快照。
Returns:
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
"""
if not user_attachments:
return False
try:
chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
return False
if chat_log_id <= 0:
return False
from app.services.chat.log_service import merge_chat_log_payload
return merge_chat_log_payload(
chat_log_id=chat_log_id,
user_id=int(user_id or 0),
agent_id=int(agent_id or 0),
session_id=session_id,
payload_patch={'user_attachments': user_attachments},
)
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
+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,
}
+447
View File
@@ -0,0 +1,447 @@
"""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,
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
'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,
'http_method': iface.http_method, 'request_path': iface.request_path,
'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 {},
'context_source_code': binding.context_source_code,
'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(),
endpoint=(str(body.get('endpoint') or '').strip() or None),
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
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('/client-instances/<code>', methods=['PUT'])
@require_admin
def update_client_instance(code):
"""更新客户端实例(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')
body = request.get_json(silent=True) or {}
connector_type = str(body.get('connector_type') or client.connector_type)
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
if body.get('name') is not None:
_require(body.get('name'), 'name')
client.name = str(body['name']).strip()
if body.get('connector_type') is not None:
client.connector_type = connector_type
if body.get('environment') is not None:
client.environment = str(body['environment']).strip()
if 'endpoint' in body:
client.endpoint = str(body.get('endpoint') or '').strip() or None
if 'timeout_seconds' in body:
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
if 'config_json' in body:
client.config_json = body.get('config_json') or {}
if 'credential_ref_code' in body:
client.credential_ref_code = body.get('credential_ref_code')
if 'enabled' in body:
client.enabled = bool(body.get('enabled', True))
from app import db
db.session.commit()
return ok(_serialize_client(client))
# ---- 接口定义 ----
@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,
http_method=(str(body.get('http_method') or '').strip().upper() or None),
request_path=(str(body.get('request_path') or '').strip() or None),
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)
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
@require_admin
def update_interface_definition(code):
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
body = request.get_json(silent=True) or {}
if body.get('name') is not None:
_require(body.get('name'), 'name')
iface.name = str(body['name']).strip()
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
iface.client_instance_code = body['client_instance_code']
if body.get('connector_type') is not None:
connector_type = str(body['connector_type'])
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
iface.connector_type = connector_type
if 'http_method' in body:
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
if 'request_path' in body:
iface.request_path = str(body.get('request_path') or '').strip() or None
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
if json_field in body:
setattr(iface, json_field, body.get(json_field) or {})
if body.get('version') is not None:
iface.version = int(body.get('version') or 1)
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface.status = status
if 'enabled' in body:
iface.enabled = bool(body.get('enabled', True))
from app import db
db.session.commit()
return ok(_serialize_interface(iface))
# ---- 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 {},
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
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('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin
def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
if binding is None:
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
body = request.get_json(silent=True) or {}
if body.get('capability') is not None:
_require(body.get('capability'), 'capability')
binding.capability = body['capability']
if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {}
if 'context_source_code' in body:
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
binding.client_instance_code = body['client_instance_code']
if body.get('interface_definition_code') is not None:
_require(body.get('interface_definition_code'), 'interface_definition_code')
binding.interface_definition_code = body['interface_definition_code']
if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None:
binding.priority = int(body.get('priority') or 0)
if body.get('environment') is not None:
binding.environment = str(body['environment']).strip()
if body.get('effective_from') is not None:
binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not None:
binding.effective_to = body['effective_to'] or None
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
binding.status = status
from app import db
db.session.commit()
return ok(_serialize_binding(binding))
# ---- 凭据引用 ----
@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('/credential-references/<code>', methods=['PUT'])
@require_admin
def update_credential_reference(code):
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
if cred is None:
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
body = request.get_json(silent=True) or {}
if body.get('secret_ref') is not None:
_require(body.get('secret_ref'), 'secret_ref')
cred.secret_ref = str(body['secret_ref']).strip()
if body.get('secret_provider') is not None:
cred.secret_provider = str(body['secret_provider']).strip()
if body.get('credential_type') is not None:
cred.credential_type = str(body['credential_type']).strip()
if body.get('status') is not None:
cred.status = str(body['status']).strip()
from app import db
db.session.commit()
return ok(_serialize_credential(cred))
# ---- 连接测试 ----
@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})
-9
View File
@@ -256,15 +256,6 @@ def tool_match_inventory():
resume_gate_code='inventory_matching',
))
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
def tool_submit_decision():
"""
提交人工决策。
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
def tool_confirm_customer():
"""
+14 -1
View File
@@ -22,7 +22,7 @@ from app.services.training_service import (
summarize_training_records,
upsert_user_training_record,
)
from app.services.training_config_service import get_published_config
from app.services.training_config_service import get_published_config, list_training_type_codes
training_user_bp = Blueprint("training_user", __name__)
training_admin_bp = Blueprint("training_admin", __name__)
@@ -58,6 +58,19 @@ def get_my_training_record():
return jsonify(serialize_training_record(record) if record else None)
@training_user_bp.route("/training-types", methods=["GET"])
def list_my_training_types():
"""
返回当前员工可见的已发布培训类型目录。
用途:为员工动态培训 Tabs 和 HR 类型名称映射提供统一的 code/name 数据源。
Returns:
已发布培训类型列表;每项包含非空 code 与管理员配置的展示名称。
"""
_require_user()
return jsonify(list_training_type_codes())
@training_user_bp.route("/training-config", methods=["GET"])
def get_my_training_config():
_require_user()
+1 -1
View File
@@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
+95 -135
View File
@@ -22,12 +22,12 @@ from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import (
AUTO_CHAIN_FALLBACK,
CP_EXPORT_GENERATED,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
POSITION_EXPORT_GENERATED,
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
)
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
from app.services.shipping_notice.query_service import (
@@ -53,7 +53,6 @@ from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
list_customer_options,
)
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -145,6 +144,16 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No
)
def _require_formal_notice(task: Any) -> ShippingNotice:
"""正式 Notice 专属接口的实体守卫;OT 在库存门禁前不得进入通知/上传写路径。"""
if not isinstance(task, ShippingNotice):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -214,7 +223,7 @@ def _batch_task_nos(data: dict) -> list[str]:
return normalized
def _can_dispose_task(user, task: ShippingNotice) -> bool:
def _can_dispose_task(user, task) -> bool:
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
@@ -372,96 +381,6 @@ def workspace_confirm_shipping_customer(task_no: str):
return _ok(serialize_task_detail(updated))
@workspace_shipping_notice_bp.route(
'/shipping-order-extractions/<int:extraction_id>/customer-matches/<role>/confirm',
methods=['POST'],
)
def workspace_confirm_order_customer_match(extraction_id: int, role: str):
"""确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。"""
user = _require_user()
extraction = (
db.session.query(ShippingOrderExtraction)
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
.filter(
ShippingOrderExtraction.id == extraction_id,
ShippingOrderIntake.user_id == user.id,
)
.one_or_none()
)
if extraction is None:
raise NotFoundError(
'Order extraction not found',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
site_id = int(data['site_id']) if data.get('site_id') is not None else None
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.ORDER_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
result = confirm_order_customer_match(
extraction.id,
role=role,
customer_id=customer_id,
site_id=site_id,
actor_id=user.id,
reason=str(data.get('reason') or ''),
commit=False,
)
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
if role == 'bill_to':
from app.models import (
ShippingOrderCandidate,
ShippingOrderReviewCase,
ShippingOrderReviewStream,
)
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
_TERMINAL = frozenset({
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
})
candidates = list(
ShippingOrderCandidate.query
.filter_by(order_extraction_id=int(extraction.id))
.all()
)
candidate_ids = {int(c.id) for c in candidates}
case = None
if candidate_ids:
case = (
ShippingOrderReviewCase.query
.join(
ShippingOrderReviewStream,
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
.first()
)
if case is None and extraction.run_id:
case = (
ShippingOrderReviewCase.query
.join(
ShippingOrderReviewStream,
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
.first()
)
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
reconcile_single_case_for_auto_progress(
case=case,
trigger='extraction_customer_confirmed',
refresh_validation=True,
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
@@ -491,12 +410,15 @@ def workspace_create_shipping_task_from_notice():
task_no=task_id,
)
if not intake.accepted:
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
task = ShippingNotice.query.filter_by(task_no=task_id).first()
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED})
from app.models import ShippingOrderTask
from app.models import ShippingOrderIntake
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = intake.text
task.source_file_name = intake.filename or task.source_file_name
task.source_file_type = intake.source_file_type or task.source_file_type
intake_row = db.session.get(ShippingOrderIntake, task.intake_id) if task.intake_id else None
if intake_row is not None:
intake_row.extracted_text = intake.text
intake_row.parse_warnings_json = list(intake.warnings or [])
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
@@ -540,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str):
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
@@ -548,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
# [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段,
# 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。
# [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich;
# 缺省/非法值一律回退 full,保持兼容。
view = str(request.args.get('view', 'full') or 'full').strip().lower()
if view not in ('full', 'workbench'):
view = 'full'
@@ -637,6 +559,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
@@ -683,6 +606,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
@@ -771,6 +695,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {}
line = data.get('line')
if not isinstance(line, dict) or not line:
@@ -796,6 +721,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
@@ -834,11 +760,15 @@ def workspace_auto_progress_shipping_task(task_no: str):
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
)
# 兼容旧前端:若仍有 export 路径则附带 download_url。
# 导出下载路径只从当前有效 Artifact 读取,Notice 不再保存文件投影。
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
refreshed = get_task_for_user(task_no, user.id)
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None
artifact = None
if refreshed is not None:
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
artifact = latest_export_artifact(refreshed)
export_path = getattr(artifact, 'file_path', None)
if export_path:
result = {
**result,
@@ -862,6 +792,7 @@ def workspace_mark_manual_uploaded(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
_assert_fulfillment_task_ownership(task, user.id)
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
@@ -1139,6 +1070,7 @@ def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
task = _require_formal_notice(task)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
@@ -1900,19 +1832,17 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/fields/<field_id>', methods=['PATCH'])
def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str):
"""修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。"""
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/fields/<field_id>', methods=['PATCH'])
def workspace_patch_shipping_order_review_line_field(case_no: str, draft_line_id: str, field_id: str):
"""修改或恢复一个复核订单行字段;行只接受服务端返回的 draft_line_id。"""
user = _require_user()
from app.services.shipping_notice.order_review_draft_service import patch_line_field
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed')
result = patch_line_field(
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'),
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, field_id=field_id, value=payload.get('value'),
expected_draft_version=payload.get('expected_draft_version'),
restore_machine=bool(payload.get('restore_machine')),
override_reason_code=payload.get('override_reason_code'),
override_reason_text=payload.get('override_reason_text'),
)
db.session.commit()
return _ok(result)
@@ -1930,30 +1860,30 @@ def workspace_add_shipping_order_review_line(case_no: str):
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/copy', methods=['POST'])
def workspace_copy_shipping_order_review_line(case_no: str, line_key: str):
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/copy', methods=['POST'])
def workspace_copy_shipping_order_review_line(case_no: str, draft_line_id: str):
"""复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。"""
user = _require_user()
from app.services.shipping_notice.order_review_draft_service import copy_line
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied')
result = copy_line(
user_id=user.id, case_no=case_no, line_key=line_key,
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
expected_draft_version=payload.get('expected_draft_version'),
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>', methods=['DELETE'])
def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>', methods=['DELETE'])
def workspace_delete_shipping_order_review_line(case_no: str, draft_line_id: str):
"""删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。"""
user = _require_user()
from app.services.shipping_notice.order_review_draft_service import delete_line
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted')
result = delete_line(
user_id=user.id, case_no=case_no, line_key=line_key,
user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
expected_draft_version=payload.get('expected_draft_version'),
)
db.session.commit()
@@ -1992,7 +1922,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
"""
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。
核心逻辑:可选 draft_line_id;携带 expected_draft_version 与幂等键。
"""
user = _require_user()
from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing
@@ -2005,7 +1935,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
case_no=case_no,
expected_draft_version=payload.get('expected_draft_version'),
idempotency_key=payload.get('idempotency_key'),
line_key=payload.get('line_key'),
draft_line_id=payload.get('draft_line_id'),
)
db.session.commit()
return _ok(result)
@@ -2122,7 +2052,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
"""
写入行级履约决定。
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version?
Body: draft_line_id, decision_code, reason?, release_field_values?, expected_draft_version?
"""
user = _require_user()
data = request.get_json(silent=True) or {}
@@ -2134,7 +2064,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
result = decide_review_line_fulfillment(
user_id=user.id,
case_no=case_no,
line_key=str(data.get('line_key') or ''),
draft_line_id=str(data.get('draft_line_id') or ''),
decision_code=str(data.get('decision_code') or ''),
reason=str(data.get('reason') or '').strip() or None,
release_field_values=(
@@ -2156,7 +2086,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
"""
为选中完整明细行创建履约波次。
Body: line_keys[], expected_draft_version, idempotency_key, reason?
Body: snapshot_line_ids[], expected_draft_version, idempotency_key, reason?
只允许正式 OT 走 create_post_ot_fulfillment_wave +
schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须
先完成正式建单,避免同一业务动作存在两套推进事实。
@@ -2171,14 +2101,14 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False}
line_keys = list(data.get('line_keys') or [])
snapshot_line_ids = list(data.get('snapshot_line_ids') or [])
idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key')
reason = str(data.get('reason') or '').strip() or None
if formal.get('has_formal_ot'):
result = create_post_ot_fulfillment_wave(
case_no=str(case_no),
line_keys=line_keys,
snapshot_line_ids=snapshot_line_ids,
decision_source='user',
actor_user_id=int(user.id),
reason=reason,
@@ -2190,7 +2120,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or line_keys),
snapshot_line_ids=list(result.get('accepted_snapshot_line_ids') or snapshot_line_ids),
review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None,
idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None,
@@ -2223,7 +2153,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
"""
关闭行级或 Case 剩余开放行。
Body: reason, line_keys?, expected_draft_version?
Body: reason, draft_line_ids?, expected_draft_version?
"""
user = _require_user()
data = request.get_json(silent=True) or {}
@@ -2236,7 +2166,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
user_id=user.id,
case_no=case_no,
reason=str(data.get('reason') or ''),
line_keys=list(data.get('line_keys') or []) or None,
draft_line_ids=list(data.get('draft_line_ids') or []) or None,
expected_draft_version=data.get('expected_draft_version'),
actor_is_admin=is_admin,
)
@@ -2349,9 +2279,7 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
user = _require_user()
from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case,
finalize_sync_auto_progress_after_commit,
resolve_confirm_outcome,
schedule_auto_progress_after_review_confirm,
)
payload = _review_draft_payload(
@@ -2366,14 +2294,22 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
warning_acknowledgements=payload.get('warning_acknowledgements'),
)
# [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。
# 复核确认只产生 OT;正式 ShippingNotice 尚未生成,不能把 OT 编号投递到
# 旧的 notice-run Job。库存源候选的裁决/冻结确认后由正式 inventory_source_routing
# Gate 负责;通过 schedule_auto_progress_after_review_confirm 入队自动推进,
# 使 OT 在不冻结候选的情况下仍能走到库存链路。
from app.services.shipping_notice.order_review_confirmation_service import (
finalize_sync_auto_progress_after_commit,
schedule_auto_progress_after_review_confirm,
)
progress = schedule_auto_progress_after_review_confirm(
task_no=result.get('task_no'),
task_no=str(result.get('task_no')),
idempotent_replay=bool(result.get('idempotent_replay')),
created_by_id=int(user.id),
commit=False,
)
# [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op)
if result.get('task_no') and not result.get('idempotent_replay'):
if result.get('shipping_notice_no') and not result.get('idempotent_replay'):
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
@@ -2383,8 +2319,8 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
commit=False,
)
db.session.commit()
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
progress = finalize_sync_auto_progress_after_commit(progress)
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
result = dict(result)
result.pop('trigger_auto_progress', None)
result['confirm_ok'] = True
@@ -2395,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
'message': '无需调度自动推进,或任务已离开待推进态',
}
else:
# [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。
position = progress.get('position')
user_mode = progress.get('user_mode')
if not position or not user_mode:
try:
from app.models import ShippingOrderTask
from app.services.shipping_notice.progress_workflow import (
_entry_position,
_entry_user_mode,
)
ot = (
db.session.query(ShippingOrderTask)
.filter(
ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper()
)
.first()
)
if ot is not None:
position = position or _entry_position(ot)
user_mode = user_mode or _entry_user_mode(ot)
except Exception:
pass
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
result['auto_progress'] = {
'status': progress.get('status'),
'message': progress.get('message'),
'enqueue_result': progress.get('enqueue_result'),
'checkpoint': progress.get('checkpoint'),
'position': position,
'user_mode': user_mode,
}
result['confirm_outcome'] = resolve_confirm_outcome(
{
@@ -2632,7 +2592,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
user_id=user.id,
case_no=case_no,
field_id=str(payload.get('field_id') or ''),
line_key=payload.get('line_key'),
draft_line_id=payload.get('draft_line_id'),
evidence_level=payload.get('evidence_level'),
issue_code=payload.get('issue_code'),
allow_full_pdf=bool(payload.get('allow_full_pdf')),
+18 -2
View File
@@ -3,7 +3,7 @@ backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 兼容旧状态)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;POST runs 仅 admin,以 force_all 入队周批排程。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
"""
from __future__ import annotations
@@ -73,7 +73,7 @@ def workspace_voucher_force_run():
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
"""
_require_user()
data = query_service.list_run_items(
@@ -85,6 +85,22 @@ def workspace_voucher_run_items(run_id: int):
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
def workspace_voucher_notifications():
"""
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
"""
_require_user()
data = query_service.list_notifications(
period=request.args.get("period"),
send_status=request.args.get("send_status"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
def workspace_voucher_states():
"""
+38 -5
View File
@@ -216,8 +216,8 @@ class Config:
# 统一改用通用 ERP 连接变量(ERP_DB_DSN / ERP_USERNAME / ERP_PASSWORD / ERP_TIMEOUT_SECONDS,已并入 env.shared),
# 并保留模块级 CONTRACT_PAYMENT_ERP_* 覆盖与旧回退(VOUCHER_CHECK_ERP_*)兼容。
CONTRACT_PAYMENT_ERP_DSN = os.getenv('CONTRACT_PAYMENT_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') or os.getenv('VOUCHER_CHECK_ERP_USERNAME', '')
CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') or os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME')
CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD')
CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30')
CONTRACT_DMS_BASE_URL = os.getenv('CONTRACT_DMS_BASE_URL', '').strip().rstrip('/')
CONTRACT_DMS_USERNAME = os.getenv('CONTRACT_DMS_USERNAME', '')
@@ -329,6 +329,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')
)
@@ -637,10 +659,21 @@ class Config:
'VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH',
'.hxops-share-ready',
).strip() or '.hxops-share-ready'
# 专用 VOUCHER_CHECK_ERP_* 优先;否则复用通用 ERP_*,再回退合同付款已配置的同一套只读账号。
VOUCHER_CHECK_ERP_DSN = os.getenv('VOUCHER_CHECK_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
VOUCHER_CHECK_ERP_USERNAME = os.getenv('VOUCHER_CHECK_ERP_USERNAME', '').strip()
VOUCHER_CHECK_ERP_PASSWORD = os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS', '30') or '30')
VOUCHER_CHECK_ERP_USERNAME = (
os.getenv('VOUCHER_CHECK_ERP_USERNAME')
or os.getenv('ERP_USERNAME')
or os.getenv('CONTRACT_PAYMENT_ERP_USERNAME', '')
).strip()
VOUCHER_CHECK_ERP_PASSWORD = (
os.getenv('VOUCHER_CHECK_ERP_PASSWORD')
or os.getenv('ERP_PASSWORD')
or os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD', '')
)
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(
os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30'
)
VOUCHER_CHECK_DMS_BASE_URL = os.getenv('VOUCHER_CHECK_DMS_BASE_URL', '').strip().rstrip('/')
VOUCHER_CHECK_DMS_USERNAME = os.getenv('VOUCHER_CHECK_DMS_USERNAME', '').strip()
VOUCHER_CHECK_DMS_PASSWORD = os.getenv('VOUCHER_CHECK_DMS_PASSWORD', '')
+3
View File
@@ -8,6 +8,9 @@ backend/app/jobs/handlers/__init__.py
from app.jobs.handlers import ( # noqa: F401
contract_payment,
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(),
)
@@ -35,15 +35,24 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
result_data = result.get('data') if isinstance(result, dict) else None
transport_status = str(
result.get('status') if isinstance(result, dict) else ''
).strip().lower()
result_status = str(
(result_data or {}).get('result_status') if isinstance(result_data, dict) else ''
).strip().lower()
if result_status in {'failed', 'partial_failed'}:
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
settle_failed_inventory_callback(
dict(job.payload_json or {}),
error=str(first_error or (result or {}).get('message') or 'inventory_callback_processing_failed'),
)
fail_job(
job.id,
error=str(first_error or f'inventory_callback_business_{result_status}'),
error=str(first_error or (result or {}).get('message') or f'inventory_callback_business_{result_status or transport_status}'),
result={'status': 'processed', 'callback_result': result},
retryable=False,
owned_attempt=owned_attempt,
@@ -16,9 +16,9 @@ from datetime import datetime
from sqlalchemy import and_, or_, update
from app import db
from app.core.errors import AppError, NotFoundError
from app.core.errors import NotFoundError
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.queue import _is_retryable_exc, fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingOrderIntake
@@ -120,15 +120,6 @@ def _claim_intake_for_parsing(
return intake, lease
def _is_retryable_exc(exc: BaseException) -> bool:
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
"""
@@ -264,7 +255,9 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
return
retryable = False
# 失败收口按异常类型分级:业务失败(NotFound/AppError.retryable=False)停排,
# 瞬时基础设施异常才允许重试;不按业务域一刀切。
retryable = _is_retryable_exc(exc)
if job_id is not None:
fail_job(
job_id,
@@ -272,3 +265,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
retryable=retryable,
owned_attempt=owned_attempt,
)
# 重试类异常交由外层运行时统一收口(fail_job 已 requeue);非重试业务失败已直接
# fail_job 为 failed,不再重抛,避免向上滚动。
if retryable:
raise
@@ -67,7 +67,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'snapshot_line_ids': list(frozen.get('snapshot_line_ids') or []),
'post_ot_wave': True,
'_orchestrator_internal_dispatch': True,
})
@@ -84,6 +84,18 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
attempt_id = int(payload.get('attempt_id') or 0)
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
external_wait_poll_gate_id = int(payload.get('external_wait_poll_gate_id') or 0)
if external_wait_poll_gate_id and job is not None:
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
if str(result.get('gate_status') or '') == 'waiting_external':
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
if gate is not None and gate.latest_attempt_id:
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
db.session.commit()
return
if attempt_id <= 0 or job is None:
raise RuntimeError('missing_attempt_id_or_job_id')
@@ -10,7 +10,8 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
成功 finish,附加 task_no / idempotent_replay;
失败统一走 _classify_stp_result:
- 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
- 临时基础设施异常 → retryable=true(保留普通重试入口)
"""
from __future__ import annotations
@@ -51,11 +52,10 @@ def _classify_stp_job_result(
【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
核心逻辑(fail-closed):
[STEP 1] build_stp_job_blocked_manual_result:
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
details 合并至 blocking_reason_details。
[STEP 2] 返回三元组(False, normalized_result_dict, next_action)。
核心逻辑:
[STEP 1] temporary_storage_error 走技术失败契约,允许普通重试;
[STEP 2] 其他错误走 build_stp_job_blocked_manual_result,要求人工裁决;
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
Args:
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
@@ -71,6 +71,23 @@ def _classify_stp_job_result(
# 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
message = '自动建单失败,已停止,等待用户选择下一步动作'
if category_hint == 'temporary_storage_error':
next_action = 'retry_stp_auto_create'
return True, {
'status': 'failed',
'retryable': True,
'error_code': str(error_code or '').strip(),
'message': str(message or ''),
'next_action': next_action,
'contract_version': 'shipping-recovery-v1-phase1',
'decision_trace': {
'contract_version': 'shipping-recovery-v1-phase1',
'stage': 'stp_classify_error',
'retryable': True,
'matched_rule': 'temporary_storage_error',
'category_hint': category_hint,
},
}, next_action
actions = derive_blocking_next_actions(blocking_reason=error_code)
next_action = actions[0] if actions else 'open_order_review'
blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
+18 -5
View File
@@ -23,7 +23,7 @@ from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import Session
from app import db
from app.core.errors import ValidationError
from app.core.errors import AppError, NotFoundError, ValidationError
from app.jobs.types import JobType
from app.models import Job
@@ -43,6 +43,19 @@ def _orm_session() -> Session:
return db.session()
def _is_retryable_exc(exc: BaseException) -> bool:
"""按异常类型分级判断任务失败是否可重试(通用裁定,不区分业务域)。
业务 NotFound / AppError.retryable=False(含 ValidationError)视为不可再排队;
仅瞬时基础设施异常(503 ServiceUnavailable 或未归类异常)才允许重试。
"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
def _ensure_outer_dbapi_transaction(session: Session) -> None:
"""
确保 begin_nested() 不会成为数据库最外层事务。
@@ -582,7 +595,7 @@ def recover_stale_jobs(
sibling: Job | None = None
rowcount = 0
if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts:
if snap_attempts < max_attempts:
if _subject_to_parse_queued_unique(str(job.job_type or "")):
try:
sibling = _resolve_safe_supersede_sibling(
@@ -1069,12 +1082,12 @@ def process_next_job(
return True, job_type_value
except Exception as exc:
db.session.rollback()
# 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。
# 其它领域维持既有技术重试策略。
# 失败收口的可重试性由异常类型分级裁定,不按业务域一刀切;
# handler 已自行 fail_job 收敛的绝不应进入此处,此处仅兜底 handler 逃逸的异常。
fail_job(
job_id,
error=str(exc),
retryable=(str(domain or '').strip() != 'shipping_notice'),
retryable=_is_retryable_exc(exc),
owned_attempt=owned_attempt,
)
raise
+7
View File
@@ -39,6 +39,10 @@ class JobType(StrEnum):
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
# 在途仓自动调拨:文件准备 + 只读预检(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):
@@ -78,6 +82,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
}),
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
'schedule': frozenset({'schedule_run'}),
'transfer': frozenset({
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
}),
}
+28 -2
View File
@@ -79,7 +79,6 @@ from app.models.shipping_order_schema import (
ShippingOrderSchemaVersion,
ShippingSchemaFamily,
)
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
from app.models.shipping_order_snapshot import (
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
@@ -192,6 +191,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 (
@@ -264,7 +279,6 @@ __all__ = [
'ShippingOrderFieldObservation',
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderCustomerMatch',
'ShippingOrderSnapshot',
'ShippingOrderSnapshotLine',
'ShippingOrderReviewEvent',
@@ -402,4 +416,16 @@ __all__ = [
'ContractPaymentAlert',
'ContractPaymentAlertBatch',
'ContractPaymentSyncState',
'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')
+202
View File
@@ -0,0 +1,202 @@
"""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')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
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)
# 关键强类型字段独立列(JSON 保留作兜底)。
http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
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)
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
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)
+12 -137
View File
@@ -5,13 +5,12 @@ backend/app/models/shipping.py
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
ShippingNotice.idempotency_key 为货代上传幂等;
ShippingUploadAttempt.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Intake/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
OT 的 order_data_version/current_order_extraction_id/order_snapshot_id 仅作为任务流程指针;
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
"""
@@ -53,18 +52,7 @@ class ShippingNotice(Base):
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
Index('ix_shipping_notices_business_no', 'business_no'),
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'),
Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'),
Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'),
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_task_id'),
@@ -72,11 +60,6 @@ class ShippingNotice(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'), index=True, nullable=True,
)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
# 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True)
@@ -85,9 +68,6 @@ class ShippingNotice(Base):
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
source_intake_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_intakes.id'),
@@ -113,10 +93,6 @@ class ShippingNotice(Base):
nullable=True,
index=True,
)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'),
@@ -128,99 +104,6 @@ class ShippingNotice(Base):
)
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_inventory_candidate_sets.id',
name='fk_shipping_notices_active_inventory_candidate_set_id',
use_alter=True,
),
nullable=True,
)
# P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_process_executions.id',
name='fk_shipping_notices_active_process_execution_id',
use_alter=True,
),
nullable=True,
)
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 动态订单 FieldValue 编辑的乐观锁版本。
order_data_version: Mapped[int] = mapped_column(
Integer,
default=1,
server_default=text('1'),
nullable=False,
)
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_extractions.id',
name='fk_shipping_notices_current_order_extraction_id',
use_alter=True,
),
nullable=True,
index=True,
)
# 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_snapshots.id',
name='fk_shipping_notices_order_snapshot_id',
use_alter=True,
),
nullable=True,
unique=True,
index=True,
)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
export_version: Mapped[int] = mapped_column(Integer, default=1)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 任务处置与业务阶段正交:生命周期负责作废/归档。
lifecycle_status: Mapped[str] = mapped_column(
@@ -241,17 +124,6 @@ class ShippingNotice(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined')
events: Mapped[List['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent',
back_populates='task',
cascade='all, delete-orphan',
)
field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship(
'ShippingTaskFieldConflict',
back_populates='task',
cascade='all, delete-orphan',
)
class ShippingTaskEvent(Base):
@@ -260,7 +132,10 @@ class ShippingTaskEvent(Base):
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', name='fk_shipping_task_events_task_id_order_task'),
index=True,
)
event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
@@ -271,7 +146,7 @@ class ShippingTaskEvent(Base):
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='events')
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='events')
class ShippingTaskPurgeAudit(Base):
@@ -397,7 +272,7 @@ class ShippingTaskInventoryLink(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
@@ -418,7 +293,7 @@ class ShippingTaskInventoryLink(Base):
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id])
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
back_populates='links',
@@ -515,7 +390,7 @@ class ShippingOrderIntake(Base):
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -697,7 +572,7 @@ class ShippingOrderCandidate(Base):
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'),
ForeignKey('shipping_order_tasks.id'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -1,9 +1,10 @@
"""
backend/app/models/shipping_customer_resolution.py
用途:保存订单候选的客户影子识别结果与人工标签。
用途:保存订单候选的正式客户识别结果、识别证据与人工标签。
依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。
逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。
逻辑:订单候选抽取后幂等刷新识别证据和候选;确认字段独立保存最终客户,
不得以订单中的任一字段(例如 bill_to)充当客户身份真相。
"""
from __future__ import annotations
@@ -11,19 +12,19 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy import CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerShadowResolution(Base):
"""每个订单候选唯一一条影子识别快照,可追加管理员真值标签。"""
"""每个订单候选唯一一条正式客户识别快照,可追加确认和质量标签。"""
__tablename__ = 'shipping_customer_shadow_resolutions'
__table_args__ = (
CheckConstraint(
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')",
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
name='ck_shipping_customer_shadow_status',
),
Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'),
@@ -56,6 +57,12 @@ class ShippingCustomerShadowResolution(Base):
resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 客户确认是识别结果的独立事实;不得覆盖 evidence_json 或原始身份指纹。
confirmed_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
confirmation_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
+2 -2
View File
@@ -32,7 +32,7 @@ class ShippingReservation(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
@@ -59,7 +59,7 @@ class ShippingInventoryVerification(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -5,7 +5,7 @@ models/shipping_inventory_candidates.py
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingNotice、ShippingProcessExecution、ShippingOrderReviewCase、users、
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
@@ -81,7 +81,7 @@ class ShippingInventoryCandidateSet(Base):
id: Mapped[int] = mapped_column(primary_key=True)
set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=True,
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=True,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True,
@@ -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'))
@@ -2,7 +2,7 @@
models/shipping_inventory_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
"""
@@ -31,7 +31,7 @@ class ShippingInventoryPreparationAttempt(Base):
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True)
gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True)
+11 -3
View File
@@ -28,19 +28,27 @@ class ShippingNoticeLine(Base):
__tablename__ = 'shipping_notice_lines'
__table_args__ = (
UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
UniqueConstraint('notice_id', 'line_no', name='uq_shipping_notice_lines_line_no'),
Index('ix_shipping_notice_lines_notice_id', 'notice_id'),
Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
snapshot_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True,
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), nullable=False,
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
# 发货通知项次:每个 Notice 从 1 开始连续编号,禁止使用导出序号或客户 PO 行号。
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True,
)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -37,7 +37,7 @@ class ShippingNoticeLineInventoryMatch(Base):
__table_args__ = (
UniqueConstraint(
'task_id',
'line_key',
'snapshot_line_id',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
@@ -45,7 +45,7 @@ class ShippingNoticeLineInventoryMatch(Base):
Index(
'uq_shipping_notice_line_inv_match_current',
'task_id',
'line_key',
'snapshot_line_id',
unique=True,
postgresql_where=text('is_current IS TRUE'),
),
@@ -70,14 +70,19 @@ class ShippingNoticeLineInventoryMatch(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
@@ -1,63 +0,0 @@
"""
backend/app/models/shipping_order_customer_match.py
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
依赖:ShippingOrderExtraction、ShippingCustomer、users。
逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。
"""
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
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderCustomerMatch(Base):
"""一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。"""
__tablename__ = 'shipping_order_customer_matches'
__table_args__ = (
UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True,
)
role: Mapped[str] = mapped_column(String(16), nullable=False)
raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_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,
)
extraction = relationship('ShippingOrderExtraction')
customer = relationship('ShippingCustomer')
site = relationship('ShippingCustomerSite')
+5 -5
View File
@@ -7,7 +7,7 @@
逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本;
Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
行级决定支持完整明细先行履约波次,禁止拆分数量;
wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。
wave_lines 保证同一 (case, snapshot_line_id) 最多关联一个 task_id。
"""
from __future__ import annotations
@@ -109,7 +109,7 @@ class ShippingOrderReviewCase(Base):
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
nullable=True,
)
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
confirmed_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)
@@ -140,13 +140,13 @@ class ShippingOrderReviewCase(Base):
'ShippingOrderReviewLineDecision',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version',
order_by='ShippingOrderReviewLineDecision.draft_line_id, ShippingOrderReviewLineDecision.decision_version',
)
wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship(
'ShippingOrderReviewWaveLine',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key',
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.snapshot_line_id',
)
@@ -212,7 +212,7 @@ class ShippingOrderReviewConfirmedRevision(Base):
case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -2,8 +2,8 @@
models/shipping_order_review_line_decision.py
用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。
依赖:ShippingOrderReviewCase、ShippingNotice、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一;
依赖:ShippingOrderReviewCase、ShippingOrderTask、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, draft_line_id, version) 唯一;
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联;
decision_source 区分 system/user(历史可空)。
"""
@@ -26,7 +26,7 @@ class ShippingOrderReviewLineDecision(Base):
__table_args__ = (
UniqueConstraint(
'review_case_id',
'line_key',
'draft_line_id',
'decision_version',
name='uq_shipping_review_line_decisions_case_line_ver',
),
@@ -49,7 +49,7 @@ class ShippingOrderReviewLineDecision(Base):
name='ck_shipping_review_line_decisions_source',
),
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'draft_line_id'),
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
Index('ix_shipping_review_line_decisions_task', 'task_id'),
)
@@ -59,7 +59,7 @@ class ShippingOrderReviewLineDecision(Base):
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
draft_line_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
decision_code: Mapped[str] = mapped_column(String(48), nullable=False)
@@ -70,7 +70,7 @@ class ShippingOrderReviewLineDecision(Base):
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。
decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
@@ -69,7 +69,7 @@ class ShippingOrderReviewSuggestion(Base):
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
field_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
draft_line_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header')
evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
@@ -2,7 +2,7 @@
models/shipping_order_review_wave_idempotency.py
用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。
依赖:shipping_order_review_cases、shipping_notices。
依赖:shipping_order_review_cases、shipping_order_tasks。
逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409;
progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。
"""
@@ -39,15 +39,15 @@ class ShippingOrderReviewWaveIdempotency(Base):
nullable=False,
)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
)
task_no: Mapped[str] = mapped_column(String(64), nullable=False)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_source: Mapped[str] = mapped_column(String(16), nullable=False)
# 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。
line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 稳定排序后的冻结订单行 ID 数组指纹(冲突比对)。
snapshot_line_ids_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
snapshot_line_ids_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='')
@@ -2,9 +2,9 @@
models/shipping_order_review_wave_line.py
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。
依赖:ShippingOrderReviewCase、ShippingOrderTask、ShippingOrderReviewConfirmedRevision。
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。
(review_case_id, snapshot_line_id) 数据库唯一约束防并发重复入波次。
"""
from __future__ import annotations
@@ -25,7 +25,7 @@ class ShippingOrderReviewWaveLine(Base):
__table_args__ = (
UniqueConstraint(
'review_case_id',
'line_key',
'snapshot_line_id',
name='uq_shipping_review_wave_lines_case_line',
),
Index('ix_shipping_review_wave_lines_task', 'task_id'),
@@ -37,8 +37,11 @@ class ShippingOrderReviewWaveLine(Base):
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
wave_no: Mapped[int] = mapped_column(Integer, nullable=False)
confirmed_revision_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
+9 -6
View File
@@ -4,7 +4,7 @@ backend/app/models/shipping_order_schema.py
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum);
definition_json 含 fields / auto_creation_policy;
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
"""
@@ -138,8 +138,7 @@ class ShippingOrderSchemaVersion(Base):
definition_json 契约要点:
- fields[]:字段采用与识别规则
- auto_creation_policy:自动建单策略
- derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no)
- derivation_rules_checksum:派生规则稳定校验和
- line_no:运行时按 Extraction 内明细顺序生成,不属于 Schema 配置或派生规则。
"""
__tablename__ = 'shipping_order_schema_versions'
@@ -232,7 +231,7 @@ class ShippingOrderExtraction(Base):
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
@@ -264,12 +263,16 @@ class ShippingOrderLine(Base):
"""动态订单解析中的行身份;业务值全部位于 FieldValue。"""
__tablename__ = 'shipping_order_lines'
__table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),)
__table_args__ = (
UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),
UniqueConstraint('extraction_id', 'line_no', name='uq_shipping_order_lines_line_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
draft_line_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines')
@@ -2,10 +2,9 @@
backend/app/models/shipping_order_snapshot.py
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
依赖:shipping_order_schema 的 Extraction、shipping_notices、shipping_customers 与 users。
依赖:shipping_order_schema 的 Extraction、shipping_order_tasks、shipping_customers 与 users。
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum;
source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。
source_manifest_json 可含 field_lineage(值来源、覆盖原因、证据引用)。
"""
from __future__ import annotations
@@ -31,13 +30,13 @@ class ShippingOrderSnapshot(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, index=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
# 可含 derivation_rules_snapshot / derivation_rules_checksum 等规则版本投影。
# 保存冻结时采用的业务规则版本,不保存已下线的派生规则。
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实;
# 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。
@@ -84,7 +83,8 @@ class ShippingOrderSnapshotLine(Base):
id: Mapped[int] = mapped_column(primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 冻结订单项次:每个 Snapshot 从 1 开始连续编号,冻结后不可修改。
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -111,7 +111,7 @@ class ShippingOrderReviewEvent(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
+42 -8
View File
@@ -2,8 +2,8 @@
backend/app/models/shipping_order_task.py
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_notices。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;建单成功后挂 shipping_notice_id。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
"""
@@ -19,12 +19,13 @@ from sqlalchemy import (
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
@@ -45,6 +46,7 @@ class ShippingOrderTask(Base):
__tablename__ = 'shipping_order_tasks'
__table_args__ = (
UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'),
CheckConstraint("lifecycle_status IN ('active', 'voided', 'archived')", name='ck_shipping_order_tasks_lifecycle_status'),
CheckConstraint(
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
name='ck_shipping_order_tasks_source_type',
@@ -53,7 +55,6 @@ class ShippingOrderTask(Base):
Index('ix_shipping_order_tasks_conversation', 'conversation_id'),
Index('ix_shipping_order_tasks_status', 'status'),
Index('ix_shipping_order_tasks_extraction_run_id', 'extraction_run_id'),
Index('ix_shipping_order_tasks_shipping_notice_id', 'shipping_notice_id'),
# 一 Candidate 一 OT;NULL candidate_id 仅遗留行,新创建路径禁止。
Index(
'uq_shipping_order_tasks_candidate_id',
@@ -79,13 +80,12 @@ class ShippingOrderTask(Base):
extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
shipping_notice_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id', name='fk_shipping_order_tasks_shipping_notice_id', use_alter=True),
nullable=True,
)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='processing')
stage: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
progress_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -94,3 +94,37 @@ class ShippingOrderTask(Base):
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# OT 的客户确认事实由 ShippingCustomerShadowResolution 承载。
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extractions.id', name='fk_shipping_order_tasks_current_extraction', use_alter=True), nullable=True, index=True,
)
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True,
)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True,
)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id', use_alter=True), nullable=True, index=True,
)
# OT 在正式通知创建前也必须具备独立的回收/归档生命周期,不能借用 Notice 字段。
lifecycle_status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
deleted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
deletion_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
voided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
voided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
void_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archived_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
events: Mapped[list['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent', back_populates='task', cascade='all, delete-orphan',
)
field_conflicts: Mapped[list['ShippingTaskFieldConflict']] = relationship(
'ShippingTaskFieldConflict', back_populates='task', cascade='all, delete-orphan',
)
+2 -2
View File
@@ -2,7 +2,7 @@
models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingNotice、Job;状态枚举与 process_gate_contract 对齐。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
@@ -74,7 +74,7 @@ class ShippingProcessExecution(Base):
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'), nullable=True,
ForeignKey('shipping_order_tasks.id'), nullable=True,
)
# 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column(
@@ -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):
+3 -3
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_task_line.py
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
依赖:models.base.Base、shipping_notices、users。
依赖:models.base.Base、shipping_order_tasks、users。
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
"""
@@ -60,7 +60,7 @@ class ShippingTaskFieldConflict(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
@@ -91,4 +91,4 @@ class ShippingTaskFieldConflict(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='field_conflicts')
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='field_conflicts')
@@ -39,7 +39,7 @@ class ShippingTemporaryInventorySession(Base):
analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
@@ -23,7 +23,7 @@ from app.models import (
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingOrderTask,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
@@ -62,10 +62,19 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
'shipping_notices': (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == customer.id,
)
.distinct()
.count()
),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
@@ -25,6 +25,8 @@ from app.models import (
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
ShippingOrderTask,
ShippingCustomerShadowResolution,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -144,7 +146,16 @@ def serialize_customer(
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
'notice_count': notice_count if notice_count is not None else (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == record.id,
)
.distinct()
.count()
),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
@@ -174,8 +185,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
items、total、page、page_size、pages。
"""
notice_counts = (
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.group_by(ShippingNotice.customer_id)
db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id)
.filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None))
.group_by(ShippingCustomerShadowResolution.confirmed_customer_id)
.subquery()
)
identifier_counts = (
@@ -19,6 +19,7 @@ from app.models import (
ShippingOrderField,
ShippingInventoryParsingProfile,
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
ShippingExcelTemplate,
ShippingInventorySourceParsingBindingAudit,
ShippingReceiptReportConfig,
@@ -497,7 +498,11 @@ def delete_source(source_id: int) -> None:
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter(
ShippingNoticeLineInventoryMatch.inventory_source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
@@ -12,4 +12,5 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -129,3 +129,35 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
- TransferRun
- TransferPrecheck
- TransferInvoiceItem
required_fields: []
default_capabilities:
task_progress: true
human_confirm: true
forced_capabilities:
human_confirm: true
progress_contract:
enabled: true
data_source:
type: domain_state
domain: in_transit_transfer
update:
transport: sse
event: transfer_ui_state
binding:
type: conversation_context
keys:
- run_no
- precheck_id
requires_schedule_task: false
presentation:
layout: card
visualization: stepper
handler_config_schema: {}
@@ -30,10 +30,12 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
_handlers_loaded = True
@@ -0,0 +1,34 @@
"""
用途:在途仓自动调拨 Hybrid Handler。
依赖:agent_registry.handlers.base/registry。
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute)
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
Dify Chatflow 生命周期。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('in_transit_transfer')
class InTransitTransferHandler(AgentHandler):
"""
在途仓自动调拨业务 Handler。
核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
+ Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""构造 transfer_ui_state SSE 事件(预留;进度由卡片消息 + Run API 提供)。"""
return None
@@ -89,10 +89,10 @@ class ShippingNoticeHandler(AgentHandler):
if str(event.get('event') or '') != 'shipping_ui_state':
return None
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
checkpoint = ui_state.get('checkpoint')
return json.dumps({
'task_no': event.get('task_no'),
'checkpoint': checkpoint,
'position': ui_state.get('position'),
'user_mode': ui_state.get('user_mode'),
'updated_at': ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
@@ -17,6 +17,7 @@ from app.services.chat.turn_context import TurnContext
# action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。
ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = {
"shipping.": ("shipping_notice",),
"transfer.": ("in_transit_transfer",),
}
@@ -79,5 +80,7 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
from app.services.in_transit_transfer import chat_actions as _transfer_actions # noqa: F401
_ = _shipping_extended
_ = _transfer_actions
+5 -4
View File
@@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes(
expires_at=expires_at,
)
# [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
# [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。
# 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session
# 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。
try:
with db.session.begin_nested():
db.session.add(asset)
db.session.flush()
db.session.add(asset)
db.session.flush()
except IntegrityError:
raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
if raced is not None:
@@ -0,0 +1,8 @@
"""backend/app/services/in_transit_transfer/__init__.py
用途:在途仓自动调拨 Agent 一期独立领域模块入口。
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
Phase 1 起扩展 file_preparation / precheck_service 等。
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -0,0 +1,168 @@
"""在途调拨 MinIO 归档与 Hash 校验。
用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库;
归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。
依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。
逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。
凭据只来自环境/配置,绝不写入归档内容或索引。
"""
from __future__ import annotations
import hashlib
import io
import uuid
from datetime import datetime
from typing import Any, Protocol
from app import db
from app.core.errors import AppError
from app.models import TransferArchive
from app.services.in_transit_transfer.audit import build_transfer_audit_event
ARCHIVE_STORAGE_PROVIDER = "minio"
DEFAULT_ARCHIVE_BUCKET = "hxops-transfer"
class ObjectStore(Protocol):
"""对象存储协议(MinIO 或测试替身)。"""
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象,返回对象键。"""
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
class MinioObjectStore:
"""默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。"""
def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None:
from flask import current_app
self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket)
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip()
secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip()
secure = bool(current_app.config.get("MINIO_SECURE", False))
if not endpoint:
raise AppError(
code="TRANSFER.ARCHIVE_NOT_CONFIGURED",
message="MinIO endpoint not configured",
http_status=503,
)
from minio import Minio
self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure)
def _ensure_bucket(self) -> None:
"""确保 bucket 存在(幂等)。"""
if not self.client.bucket_exists(self.bucket):
self.client.make_bucket(self.bucket)
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象并返回键。"""
self._ensure_bucket()
self.client.put_object(
bucket_name=bucket or self.bucket,
object_name=key,
data=io.BytesIO(data),
length=len(data),
content_type=content_type,
)
return key
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key)
def _safe_filename(name: str) -> str:
"""清洗文件名片段。"""
return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive"
def archive_snapshot(
*,
object_type: str,
object_id: str,
data: bytes,
original_filename: str,
content_type: str,
object_store: ObjectStore,
bucket: str = DEFAULT_ARCHIVE_BUCKET,
request_id: str | None = None,
) -> TransferArchive:
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
content_type: MIME。
object_store: 对象存储替身。
bucket: 目标 bucket。
Returns:
TransferArchive 索引记录。
"""
digest = hashlib.sha256(data).hexdigest()
key = (
f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/"
f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}"
)
object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type)
archive = TransferArchive(
archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}",
object_type=object_type,
object_id=object_id,
storage_provider=ARCHIVE_STORAGE_PROVIDER,
storage_bucket=bucket,
storage_key=key,
original_filename=original_filename,
content_type=content_type,
file_size=len(data),
sha256=digest,
)
db.session.add(archive)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ARCHIVED",
aggregate_type=object_type,
aggregate_id=object_id,
actor_type="worker",
request_id=request_id,
result="success",
after={"storage_key": key, "sha256": digest, "file_size": len(data)},
))
db.session.commit()
return archive
def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool:
"""复核归档 Hash(下载对象重新计算)。
Args:
archive: TransferArchive 索引。
object_store: 对象存储替身。
Returns:
True 一致;False 损坏/篡改。
"""
data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
return hashlib.sha256(data).hexdigest() == archive.sha256
def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes:
"""恢复归档对象字节。"""
return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
@@ -0,0 +1,182 @@
"""在途调拨审计服务。
用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算
before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。
依赖:app.models.TransferAuditEvent、标准库 hashlib/json。
逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash;
event_hash 由事件自身稳定字段复算,不依赖对象内部状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Mapping
import hashlib
import json
from app.models import TransferAuditEvent
# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。
AUDIT_FORBIDDEN_KEY_FRAGMENTS = (
"password", "secret", "token", "ciphertext", "credential",
"api_key", "apikey", "webhook", "authorization", "auth",
)
def is_forbidden_audit_key(key: str) -> bool:
"""判断键名是否命中敏感片段(大小写不敏感)。"""
lowered = str(key or "").lower()
return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS)
def sanitize_snapshot(value: Any) -> Any:
"""递归剔除敏感键,返回可安全持久化的快照副本。
Args:
value: 原始快照(dict/list/标量)。
Returns:
脱敏后的副本。
"""
if isinstance(value, dict):
return {
str(key): sanitize_snapshot(item)
for key, item in value.items()
if not is_forbidden_audit_key(str(key))
}
if isinstance(value, (list, tuple)):
return [sanitize_snapshot(item) for item in value]
return value
def canonical_hash(value: Any) -> str:
"""对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。
Args:
value: 任意 JSON 可序列化值。
Returns:
64 位十六进制 Hash。
"""
payload = json.dumps(
sanitize_snapshot(value),
ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str,
)
return hashlib.sha256(payload.encode("ascii")).hexdigest()
def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]:
"""计算前后快照顶层差异。
Args:
before: 变更前快照。
after: 变更后快照。
Returns:
{"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。
"""
before_keys = set(before)
after_keys = set(after)
return {
"added": {key: after[key] for key in sorted(after_keys - before_keys)},
"removed": {key: before[key] for key in sorted(before_keys - after_keys)},
"changed": {
key: (before[key], after[key])
for key in sorted(before_keys & after_keys)
if before[key] != after[key]
},
}
def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
"""事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。"""
created = event.created_at or datetime.utcnow()
return {
"event_type": event.event_type,
"aggregate_type": event.aggregate_type,
"aggregate_id": event.aggregate_id,
"run_no": event.run_no,
"precheck_no": event.precheck_no,
"invoice_no": event.invoice_no,
"item_id": event.item_id,
"attempt_no": event.attempt_no,
"actor_type": event.actor_type,
"actor_id": event.actor_id,
"actor_role": event.actor_role,
"actor_display": event.actor_display,
"request_id": event.request_id,
"operation_id": event.operation_id,
"source": event.source,
"result": event.result,
"error_code": event.error_code,
"before_hash": event.before_hash,
"after_hash": event.after_hash,
"created_at": created.isoformat(),
}
def compute_event_hash(event: TransferAuditEvent) -> str:
"""由存储字段复算事件 Hash(Hash 校验作业的复算口径)。"""
return canonical_hash(_event_hash_inputs(event))
def build_transfer_audit_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
precheck_no: str | None = None,
invoice_no: str | None = None,
item_id: str | None = None,
attempt_no: str | None = None,
actor_type: str = "system",
actor_id: str | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
before: Any = None,
after: Any = None,
) -> TransferAuditEvent:
"""构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。
Args:
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。
actor_*: 操作者(user/worker/schedule/admin/rpa)。
request_id / operation_id: 关联上下文。
before / after: 前后快照(自动脱敏并计算 Hash)。
Returns:
TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。
"""
before_sanitized = sanitize_snapshot(before if before is not None else {})
after_sanitized = sanitize_snapshot(after if after is not None else {})
created_at = datetime.utcnow()
event = TransferAuditEvent(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=aggregate_id,
run_no=run_no,
precheck_no=precheck_no,
invoice_no=invoice_no,
item_id=item_id,
attempt_no=attempt_no,
actor_type=actor_type,
actor_id=actor_id,
actor_role=actor_role,
actor_display=actor_display,
request_id=request_id,
operation_id=operation_id,
source=source,
result=result,
error_code=error_code,
before_json=before_sanitized,
after_json=after_sanitized,
before_hash=canonical_hash(before_sanitized),
after_hash=canonical_hash(after_sanitized),
created_at=created_at,
)
event.event_hash = compute_event_hash(event)
return event
@@ -0,0 +1,71 @@
"""在途调拨自动排程编排(09:00 自动调拨)。
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from app import db
from app.services.in_transit_transfer.execution_service import execute_precheck
from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
@dataclass
class AutoTransferOutcome:
"""自动调拨阶段结果。"""
run_no: str | None = None
run_status: str | None = None
recovery: RecoveryOutcome = field(default_factory=RecoveryOutcome)
notification_status: str | None = None
errors: list[str] = field(default_factory=list)
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
Args:
business_date: 业务日期。
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
sender / recipients: 企微通知(None 则跳过通知)。
Returns:
AutoTransferOutcome。
"""
outcome = AutoTransferOutcome()
if recover_history:
try:
outcome.recovery = run_daily_recovery(business_date=business_date, deps=deps)
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"recovery_failed: {exc}")
try:
summary = create_precheck(
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
)
executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
outcome.run_no = executed.run_no
outcome.run_status = executed.status
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"auto_transfer_failed: {exc}")
if sender is not None and outcome.run_no:
try:
notice = notify_run_summary(run_no=outcome.run_no, sender=sender, recipients=recipients or [])
outcome.notification_status = notice.get("notification_status")
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"notification_failed: {exc}")
return outcome
@@ -0,0 +1,141 @@
"""在途调拨历史待处理池与老化分级。
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
依赖:models、status。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.status import TransferStatus
AGING_NORMAL = "normal"
AGING_WARN_3D = "warn_3d"
AGING_ESCALATE_5D = "escalate_5d"
AGING_CRITICAL_7D = "critical_7d"
AGING_UNKNOWN = "result_unknown"
AGING_CLOSED = "closed"
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
@dataclass(frozen=True)
class BacklogItemDTO:
"""待处理池单项。"""
item_id: int
source_code: str
invoice_no: str
material_no: str
status: str
reason: str
age_days: int
aging_level: str
last_attempt_at: Optional[str] = None
@dataclass
class BacklogSummaryDTO:
"""待处理池汇总(含老化分级计数)。"""
recoverable_count: int = 0
closed_count: int = 0
unknown_count: int = 0
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
"""按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。"""
if age_days >= critical:
return AGING_CRITICAL_7D
if age_days >= escalate:
return AGING_ESCALATE_5D
if age_days >= warn:
return AGING_WARN_3D
return AGING_NORMAL
def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]:
"""返回明细最近一次 Attempt(无则 None)。"""
return TransferAttempt.query.filter_by(item_id=item.id).order_by(
TransferAttempt.created_at.desc(),
).first()
def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
"""按最近 Attempt 或明细更新时间计算积压天数。"""
latest = _latest_attempt(item)
base = latest.created_at if latest is not None else item.updated_at
return max(0, int((now - base).total_seconds() // 86400))
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
Returns:
BacklogItemDTO 列表。
"""
current = now or datetime.utcnow()
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
]),
)
if source_code:
query = query.filter_by(source_code=source_code)
output: list[BacklogItemDTO] = []
for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all():
age = _item_age_days(item, current)
latest = _latest_attempt(item)
if item.status == TransferStatus.RESULT_UNKNOWN.value:
level = AGING_UNKNOWN
elif item.status == TransferStatus.MANUALLY_CLOSED.value:
level = AGING_CLOSED
else:
level = aging_level_for(age)
output.append(BacklogItemDTO(
item_id=item.id,
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
status=item.status,
reason=item.result_message or item.result_code or "",
age_days=age,
aging_level=level,
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
))
return output
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数与老化分级。"""
items = list_backlog(now=now)
summary = BacklogSummaryDTO()
for item in items:
if item.status == TransferStatus.MANUALLY_CLOSED.value:
summary.closed_count += 1
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
summary.unknown_count += 1
else:
summary.recoverable_count += 1
if item.aging_level == AGING_WARN_3D:
summary.warn_3d += 1
elif item.aging_level == AGING_ESCALATE_5D:
summary.escalate_5d += 1
elif item.aging_level == AGING_CRITICAL_7D:
summary.critical_7d += 1
return summary
@@ -0,0 +1,65 @@
"""在途调拨请求停止(取消剩余任务)。
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
原因必填;取消前后状态进入审计。
依赖:models、status、core.errors。
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""请求停止剩余任务。
Args:
run_no: Run 编号。
reason: 取消原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"run_no": ..., "cancelled_count": ...}。
Raises:
ValidationError: 原因为空。
NotFoundError: Run 不存在。
ConflictError: Run 已终态不可取消。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("reason is required")
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if run.status in {
status_machine.TransferRunStatus.SUCCESS.value,
status_machine.TransferRunStatus.FAILED.value,
status_machine.TransferRunStatus.CANCELLED.value,
}:
raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE")
cancelled = 0
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
cancelled += 1
active = db.session.query(TransferInvoiceItem).filter(
TransferInvoiceItem.run_id == run.id,
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.READY_TO_EXECUTE.value,
]),
).count()
if active == 0:
run.status = status_machine.TransferRunStatus.CANCELLED.value
run.completed_at = run.completed_at or datetime.utcnow()
db.session.commit()
return {"run_no": run.run_no, "cancelled_count": cancelled}
@@ -0,0 +1,100 @@
"""在途调拨 Chat Action Handler。
用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件
(message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。
依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。
逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。
"""
from __future__ import annotations
from typing import Any, Iterator
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.serializers import serialize_precheck_detail
ACTION_TRANSFER_PRECHECK = "transfer.precheck"
ACTION_TRANSFER_EXECUTE = "transfer.execute"
def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEvent:
"""构造结构化消息完成事件。"""
return TurnEvent(event="message.completed", data={
"content": content,
"message_type": message_type,
"payload": payload,
})
@register_action_handler
class TransferPrecheckAction:
"""预检 Action:创建(或恢复)预检并输出预检卡。"""
action_type = ACTION_TRANSFER_PRECHECK
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行只读预检并输出 transfer-precheck 卡片。
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
只读,不写 ERP。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
business_date = str(payload.get("business_date") or business_date_now())
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
)
detail = restore_precheck(summary.precheck_id)
yield _message(
content="调拨预检完成",
message_type="transfer-precheck",
payload={"kind": "precheck", **serialize_precheck_detail(detail)},
)
@register_action_handler
class TransferExecuteAction:
"""执行 Action:确认选择范围并直接生成执行 Run,输出结果卡。"""
action_type = ACTION_TRANSFER_EXECUTE
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 ERP 原子写入。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
invoice_nos = payload.get("invoice_nos")
invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
run_view = get_run(outcome.run_no)
yield _message(
content=f"调拨执行完成:{outcome.run_no}",
message_type="transfer-result",
payload={
"kind": "result",
"run_no": outcome.run_no,
"status": outcome.status,
"run": {
"run_no": outcome.run_no,
"status": outcome.status,
"result": run_view["result"],
},
},
)
@@ -0,0 +1,25 @@
"""在途调拨并发参数与单写者约束。
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
"""同预检最多一个执行 Run。
Args:
run_count: 已存在的执行 Run 数。
Raises:
AssertionError: run_count > 1(一期硬约束)。
"""
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
@@ -0,0 +1,200 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Iterable
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN"
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED = "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED"
TRANSFER_CONFIG_PUBLISH_BLOCKED = "TRANSFER_CONFIG_PUBLISH_BLOCKED"
TRANSFER_SECRET_NOT_EXPOSED = "TRANSFER_SECRET_NOT_EXPOSED"
TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_PERMISSION_DENIED,
TRANSFER_RECEIPT_NOT_MATURED,
TRANSFER_FILE_NOT_READY,
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_ERP_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
TRANSFER_RESULT_UNKNOWN,
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
TRANSFER_CONFIG_PUBLISH_BLOCKED,
TRANSFER_SECRET_NOT_EXPOSED,
TRANSFER_NOTIFICATION_FAILED,
})
def require_known_error_code(code: str) -> None:
"""校验错误码属于一期冻结集合。
Args:
code: 错误码。
Raises:
ValueError: 未知错误码。
"""
if str(code or "").strip() not in KNOWN_TRANSFER_ERROR_CODES:
raise ValueError(f"unknown transfer error code: {code}")
# ---- 预检 DTO -------------------------------------------------------------
@dataclass(frozen=True)
class PrecheckCountsDTO:
"""预检计数。"""
file_invoice_count: int = 0
not_matured_count: int = 0
prechecked_count: int = 0
executable_count: int = 0
blocked_count: int = 0
@dataclass(frozen=True)
class RawLineRefDTO:
"""原始文件行追溯(Sheet/行号/文件版本)。"""
sheet: str
row_no: int
file_version: str
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
source_code: str
material_no: str
material_name: str
specification: str
invoice_no: str
from_warehouse: str
from_quantity: Decimal | None
to_warehouse: str
to_quantity: Decimal
result: str
receipt_date: str | None = None
reason: str = ""
erp_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class PrecheckSummaryDTO:
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
precheck_id: str
status: str
business_date: str
eligible_receipt_date_to: str
expires_at: str
counts: PrecheckCountsDTO
estimated_transfer_quantity: str
estimated_erp_write_count: int
precheck_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@dataclass(frozen=True)
class ErpDocumentLineDTO:
"""ERP 单据内物料明细。"""
material_no: str
material_name: str
specification: str
invoice_no: str
quantity: Decimal
@dataclass(frozen=True)
class ErpDocumentDTO:
"""按 ERP 单号聚合的结果项。"""
document_no: str
from_warehouse: str
to_warehouse: str
material_count: int
total_quantity: Decimal
posting_status: str
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 ERP 单据的异常项(单独展示)。"""
source_code: str
invoice_no: str
material_no: str
reason: str
facts: str
@dataclass(frozen=True)
class RunResultDTO:
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
run_no: str
status: str
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
"""按 ERP 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 erp_document_no 与 result)。
Returns:
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
for item in items:
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.erp_document_no, []).append(item)
documents: list[ErpDocumentDTO] = []
for document_no in sorted(grouped):
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
lines = tuple(
ErpDocumentLineDTO(
material_no=row.material_no,
material_name=row.material_name,
specification=row.specification,
invoice_no=row.invoice_no,
quantity=row.to_quantity,
)
for row in rows
)
documents.append(ErpDocumentDTO(
document_no=document_no,
from_warehouse=rows[0].from_warehouse,
to_warehouse=rows[0].to_warehouse,
material_count=len(rows),
total_quantity=sum((row.to_quantity for row in rows), Decimal("0")),
posting_status="posted",
lines=lines,
))
return tuple(documents)
@@ -0,0 +1,81 @@
"""在途调拨业务日期与成熟度策略。
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
昨天及更早可预检,未来日期阻断)。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
避免各服务各自计算导致口径漂移。
"""
from __future__ import annotations
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 成熟度结果
MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
"""
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
def business_date_now(moment: datetime | None = None) -> date:
"""计算 Asia/Shanghai 业务日期。
Args:
moment: 可选时刻;带时区则转换到上海,naive 按 UTC 兼容处理(与
shipping_notice.business_numbering_service 口径一致)。
Returns:
Asia/Shanghai 口径的日期。
"""
if moment is None:
return datetime.now(SHANGHAI_TZ).date()
if moment.tzinfo is None:
moment = moment.replace(tzinfo=ZoneInfo("UTC"))
return moment.astimezone(SHANGHAI_TZ).date()
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
Returns:
'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或
'future'(receipt_date > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
if receipt == business:
return MATURITY_NOT_MATURED
if receipt > business:
return MATURITY_FUTURE
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str) -> date:
"""返回可进入预检的收料截止日期(业务日期 T - 1 天)。
Args:
business_date: 当前业务日期。
Returns:
T - 1 天。
"""
return parse_date(business_date) - timedelta(days=1)
@@ -0,0 +1,118 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
RouteResolver,
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RouteNotResolvedError(source_code=source_code)
mapping = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).first()
if mapping is None or not mapping.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
to_warehouse=mapping.external_warehouse_code,
)
def _build_erp_adapter() -> CapabilityErpAdapter:
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
"""
return CapabilityErpAdapter()
_override: TransferDeps | None = None
def set_transfer_dependencies(deps: TransferDeps | None) -> None:
"""测试注入点:设置/清除 TransferDeps 覆盖。"""
global _override # noqa: PLW0603
_override = deps
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
erp=_build_erp_adapter(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
@@ -0,0 +1,295 @@
"""在途调拨 ERP 访问统一边界(Adapter)。
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
verify_duplicate / 结果分类。
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Protocol
from app.core.errors import AppError
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
@dataclass(frozen=True)
class InventoryQuery:
"""ERP 账面库存查询结果。"""
found: bool
quantity: Decimal | None = None
document_no: str | None = None
class ErpNotFrozenError(AppError):
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "ERP contract not frozen"):
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ErpQueryTimeoutError(AppError):
"""ERP 查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "ERP query timeout"):
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ErpResultUnknownError(AppError):
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ErpWriteTimeoutError(TimeoutError):
"""ERP 写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""ERP 原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
class ErpTransport(Protocol):
"""ERP 传输层协议(SOAP 或测试替身)。"""
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""按 Invoice 查询账面库存。"""
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""原子建单/审核/过账(Phase 2)。"""
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""核实重复 Invoice 原单是否已审核过账。"""
class SoapErpTransport:
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
Args:
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
"""
def __init__(self, config: dict[str, Any] | None = None) -> None:
self._config = config or {}
def _require_frozen(self, operation: str) -> None:
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
if not str(self._config.get("endpoint") or "").strip():
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
self._require_frozen("query_inventory")
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
self._require_frozen("create_transfer")
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
self._require_frozen("verify_duplicate")
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
class ErpAdapter:
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
self._transport = transport
self._default_org = default_org
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询 ERP 账面库存并分类结果。
Args:
operation_id / run_no / attempt_no / invoice_no / erp_org /
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
Returns:
InventoryQuery。
Raises:
ErpQueryTimeoutError: 查询超时(可重试)。
ErpNotFrozenError: ERP 契约未冻结。
"""
request = {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
try:
response = self._transport.query_inventory(**request)
except ErpNotFrozenError:
raise
except TimeoutError as exc:
raise ErpQueryTimeoutError() from exc
response = response if isinstance(response, dict) else {}
if response.get("found"):
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
return InventoryQuery(found=False)
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
"""组装携带全部强制追踪字段的 ERP 请求。"""
return {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""ERP 原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ErpNotFrozenError: ERP 契约未冻结。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.create_transfer(**request)
except ErpNotFrozenError:
raise
except ErpWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.verify_duplicate(**request)
except ErpNotFrozenError:
raise
except (TimeoutError, ErpWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按 ERP 写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
@@ -0,0 +1,125 @@
"""在途调拨七 Sheet 异常 Excel 导出。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
依赖:openpyxl、models、execution_service。
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
Secret 明文永不写入单元格(仅输出业务字段)。
"""
from __future__ import annotations
import io
from typing import Any
from openpyxl import Workbook
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.core.errors import NotFoundError
EXCEL_SHEET_NAMES = [
"执行汇总",
"数量不一致",
"ERP无库存",
"ERP技术失败",
"ERP结果未知",
"通知失败",
"原始文件追溯",
]
_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def build_exceptions_workbook(run_no: str) -> bytes:
"""生成 Run 的七 Sheet 异常 Excel 字节。
Args:
run_no: Run 编号。
Returns:
xlsx 字节。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).order_by(
TransferInvoiceItem.invoice_no,
).all()
workbook = Workbook()
workbook.remove(workbook.active)
_sheet_summary(workbook, run, items)
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_unknown(workbook, items)
_sheet_notification(workbook, run)
_sheet_raw_trace(workbook, items)
buffer = io.BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""执行汇总 Sheet。"""
sheet = workbook.create_sheet("执行汇总")
sheet.append(["Run", run.run_no])
sheet.append(["Run 状态", run.status])
sheet.append(["通知状态", run.notification_status])
sheet.append([])
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.result_code or item.status, item.erp_document_no or "",
])
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.erp_quantity or "",
item.result_message or item.result_code or item.status,
])
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("ERP结果未知")
sheet.append(["Invoice", "来源", "料号", "说明"])
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
for item in items:
if item.status == "result_unknown" or (item.result_code or "") == "result_unknown":
sheet.append([item.invoice_no, item.source_code, item.material_no, item.result_message or ""])
def _sheet_notification(workbook: Workbook, run: TransferRun) -> None:
"""通知失败 Sheet。"""
sheet = workbook.create_sheet("通知失败")
sheet.append(["Run", "通知状态", "错误码"])
if run.notification_status == "failed":
sheet.append([run.run_no, run.notification_status, run.notification_error_code or ""])
def _sheet_raw_trace(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""原始文件追溯 Sheet(决策 11:Sheet/行号/文件版本)。"""
sheet = workbook.create_sheet("原始文件追溯")
sheet.append(["Invoice", "Sheet", "原始行号", "文件版本", "来源"])
for item in items:
for line in (item.raw_lines_json or []):
sheet.append([
item.invoice_no,
str(line.get("sheet") or ""),
int(line.get("row_no") or 0),
str(line.get("file_version") or ""),
item.source_code,
])
@@ -0,0 +1,399 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ErpDocumentDTO,
PrecheckInvoiceItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_erp_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
RESULT_EXECUTABLE,
RouteNotResolvedError,
TransferDeps,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
PRECHECK_EXPIRED_RESULT = "precheck_expired"
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
@dataclass(frozen=True)
class ExecuteOutcome:
"""一次执行的结果摘要。"""
run_no: str
status: str
result: RunResultDTO
def _item_result_of(item: TransferInvoiceItem) -> str:
"""从持久化状态还原明细结果值(与预检快照口径一致)。"""
if item.result_code:
return item.result_code
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
return RESULT_EXECUTABLE
return item.status
def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"""由存储明细复算预检 Hash(写前快照校验口径)。"""
from app.services.in_transit_transfer.audit import canonical_hash
counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {}
items = [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"erp_quantity": item.erp_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
]
snapshot = {
"scope": sorted(precheck.scope_json.get("source_codes") or []),
"business_date": precheck.business_date,
"file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {},
"counts": {
key: int(counts.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
},
"items": items,
}
return f"sha256:{canonical_hash(snapshot)}"
def _expire(precheck: TransferPrecheck) -> None:
"""将预检置为过期(fail-closed 落位)。"""
precheck.status = "expired"
db.session.flush()
def execute_precheck(
*,
precheck_id: str,
deps: TransferDeps,
selected_invoice_nos: list[str] | None = None,
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""执行一次已确认的预检(手工或自动触发共用)。
Args:
precheck_id: 预检编号。
deps: 注入依赖。
selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。
actor_id / request_id: 审计上下文。
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
ConflictError: 重复执行。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip(),
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
if precheck.confirmed_at is not None:
from app.core.errors import ConflictError
raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED")
if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value:
raise AppError(
code=TRANSFER_CONFIRMATION_REQUIRED,
message="precheck is not confirmed for execution",
http_status=400,
)
if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow():
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired",
http_status=409,
)
if recompute_precheck_hash(precheck) != precheck.precheck_hash:
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED,
message="precheck snapshot changed since confirmation",
http_status=409,
)
executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
if selected_invoice_nos is not None:
selected_set = {str(item).strip() for item in selected_invoice_nos}
available = {item.invoice_no for item in executable}
invalid = selected_set - available
if invalid:
raise ValidationError(
f"invoices not executable: {sorted(invalid)}",
code="TRANSFER.SELECTION_INVALID",
)
selected = [item for item in executable if item.invoice_no in selected_set]
else:
selected = list(executable)
if not selected:
raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED)
run = create_execution_run(
precheck, deps=deps, actor_id=actor_id,
selected_invoice_nos={item.invoice_no for item in selected},
)
for item in selected:
try:
_write_item(item, deps=deps, run_no=run.run_no, request_id=request_id)
except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = ITEM_EXECUTION_ERROR_RESULT
item.result_message = str(exc)
db.session.flush()
db.session.flush()
run_items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
finalize_run(run, run_items)
db.session.commit()
return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run))
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
try:
query = deps.erp.query_inventory(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
except RouteNotResolvedError:
raise
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
return
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
status="running", operation_id=operation_id,
request_snapshot_json={
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
result = deps.erp.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
before_status = item.status
_apply_write_result(item, attempt, result)
_audit_item_write(item, run_no, request_id, operation_id, before_status)
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
"""写前复查失败:fail-closed,不写 ERP。"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result
item.result_message = message
db.session.flush()
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
attempt.response_summary_json = {
"status": result.status,
"document_no": result.document_no,
"verified_posted": result.verified_posted,
"error_code": result.error_code,
}
if result.status == "success":
item.status = status_machine.TransferStatus.SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "duplicate_success":
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "result_unknown":
# 终态:禁止自动重试,等待人工核实 SOP。
item.status = status_machine.TransferStatus.RESULT_UNKNOWN.value
item.result_code = "result_unknown"
attempt.status = "result_unknown"
else:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result.status
item.result_message = result.error_message or result.error_code or ""
attempt.status = "failed"
attempt.error_code = result.error_code
attempt.completed_at = datetime.utcnow()
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_ITEM_EXECUTED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=run_no,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status in {"success", "duplicate_success"} else "failure",
before={"status": before_status},
after={"status": item.status, "erp_document_no": item.erp_document_no},
)
db.session.add(event)
def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = None) -> str:
"""单 Invoice 执行入口(Item Job Handler 使用)。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
Returns:
写入后的 item 状态。
Raises:
NotFoundError / RuntimeError: item 不存在或未关联执行 Run。
"""
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.run_id is None:
raise RuntimeError("item not linked to execution run")
run_no = item.run.run_no if item.run else "RUN-PENDING"
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
db.session.commit()
return item.status
def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
return {
"run_no": run.run_no,
"status": run.status,
"result": serialize_run_result(_build_run_result(run)),
}
def _build_run_result(run: TransferRun) -> RunResultDTO:
"""由 Run 明细构建结果投影。"""
item_dtos: list[PrecheckInvoiceItemDTO] = []
exceptions: list[TransferExceptionDTO] = []
for item in sorted(run.items, key=lambda row: row.invoice_no):
result = _item_result_of(item)
item_dtos.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=result,
reason=item.result_message or "",
erp_document_no=item.erp_document_no,
))
if result not in {"success", "duplicate_success"}:
exceptions.append(TransferExceptionDTO(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
status=run.status,
erp_documents=aggregate_erp_documents(item_dtos),
exceptions=tuple(exceptions),
)
def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
"""结果投影序列化(前端结果页 DTO)。"""
return {
"run_no": result.run_no,
"status": result.status,
"erp_documents": [
{
"document_no": document.document_no,
"from_warehouse": document.from_warehouse,
"to_warehouse": document.to_warehouse,
"material_count": document.material_count,
"total_quantity": str(document.total_quantity),
"posting_status": document.posting_status,
"lines": [
{
"material_no": line.material_no,
"material_name": line.material_name,
"specification": line.specification,
"invoice_no": line.invoice_no,
"quantity": str(line.quantity),
}
for line in document.lines
],
}
for document in result.erp_documents
],
"exceptions": [
{
"source_code": exc.source_code,
"invoice_no": exc.invoice_no,
"material_no": exc.material_no,
"reason": exc.reason,
"facts": exc.facts,
}
for exc in result.exceptions
],
}
@@ -0,0 +1,179 @@
"""在途调拨收料文件字段/结构校验。
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Any, Iterable, Mapping
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.date_policy import parse_date
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
@dataclass(frozen=True)
class ParsedReceiptRow:
"""单行已校验收料记录。"""
source_code: str
sheet: str
row_no: int
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
class ReceiptFileSchemaError(AppError):
"""收料文件结构/字段校验失败(整行阻断)。"""
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
super().__init__(
code=TRANSFER_FILE_SCHEMA_INVALID,
message=message,
http_status=422,
details={"rows": rows or []},
)
def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
"""累积式抛出首个行级错误(携带行号与原因)。"""
rows.append({"row_no": row_no, "reason": reason})
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 通用异动原始行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "doc_no",
"material_no": "material_code",
"receipt_quantity": "quantity",
"receipt_date": "movement_date",
},
)
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""校验并解析收料文件行。
Args:
source_code: 任务来源实例(用于校验行内来源身份一致性)。
rows: 原始文件行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "invoice_no",
"material_no": "material_no",
"receipt_quantity": "receipt_quantity",
"receipt_date": "receipt_date",
},
)
def _parse_rows(
*,
source_code: str,
rows: Iterable[Mapping[str, Any]],
projection: Mapping[str, str],
) -> list[ParsedReceiptRow]:
"""按字段名投影校验并解析原始行。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 原始文件行 dict。
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
invoice_key = str(projection.get("invoice_no") or "invoice_no")
material_key = str(projection.get("material_no") or "material_no")
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
date_key = str(projection.get("receipt_date") or "receipt_date")
errors: list[dict[str, Any]] = []
parsed: list[ParsedReceiptRow] = []
for raw in rows:
row = raw if isinstance(raw, Mapping) else {}
row_no = row.get("row_no")
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
continue
if not invoice_no:
_fail(errors, row_no=row_no, reason="missing_invoice_no")
continue
if not material_no:
_fail(errors, row_no=row_no, reason="missing_material_no")
continue
row_source = str(row.get("source_code") or "").strip()
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
try:
receipt_date = parse_date(receipt_date_raw)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
except QuantityValidationError as exc:
_fail(errors, row_no=row_no, reason=str(exc))
continue
parsed.append(ParsedReceiptRow(
source_code=str(source_code),
sheet=sheet,
row_no=int(row_no),
invoice_no=invoice_no,
material_no=material_no,
material_name=str(row.get("material_name") or "").strip(),
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
return parsed
@@ -0,0 +1,96 @@
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
任何触发失败 fail-closed 进入 failed,绝不误报 file_ready。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Protocol
STAGE_FILE_READY = "file_ready"
STAGE_WAITING_RPA = "waiting_rpa_callback"
STAGE_FAILED = "failed"
@dataclass(frozen=True)
class ReadyReceiptFile:
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
source_code: str
business_date: str
file_no: str
file_version: str
checksum: str
rows: tuple[dict[str, Any], ...] = ()
@dataclass(frozen=True)
class FilePreparationResult:
"""来源级文件准备结果。"""
stage: str
file: ReadyReceiptFile | None = None
error_code: str | None = None
error_message: str | None = None
class ReceiptFileRepository(Protocol):
"""收料 ready 文件仓库协议。"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
class RpaTrigger(Protocol):
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
def ensure_receipt_file_ready(
*,
source_code: str,
business_date: str,
repository: ReceiptFileRepository,
rpa_trigger: RpaTrigger,
active_source_job_key: str | None = None,
) -> FilePreparationResult:
"""确保来源当日 ready 文件可用。
Args:
source_code: 来源实例编码。
business_date: 业务日期(YYYY-MM-DD)。
repository: ready 文件仓库。
rpa_trigger: RPA 触发器。
active_source_job_key: 活动 Source Job 键;非空时绑定已有任务不重复触发。
Returns:
FilePreparationResult(file_ready / waiting_rpa_callback / failed)。
"""
ready = repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is not None:
return FilePreparationResult(stage=STAGE_FILE_READY, file=ready)
if active_source_job_key is not None:
# 已有活动抓取任务:绑定等待,不重复触发。
return FilePreparationResult(stage=STAGE_WAITING_RPA)
outcome = rpa_trigger.trigger(
source_code=source_code,
business_date=business_date,
reason="precheck_missing_ready_file",
)
outcome = outcome if isinstance(outcome, dict) else {}
if outcome.get("ok"):
return FilePreparationResult(stage=STAGE_WAITING_RPA)
return FilePreparationResult(
stage=STAGE_FAILED,
error_code=str(outcome.get("error_code") or "RPA_TRIGGER_FAILED"),
error_message=str(outcome.get("error_message") or "rpa trigger failed"),
)
@@ -0,0 +1,80 @@
"""services/in_transit_transfer/gateway_adapter.py
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
(query_inventory 是首个配置绑定消费者)。
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
class CapabilityErpAdapter:
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
Args:
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
"""
def __init__(self, gateway: Any | None = None) -> None:
self._gateway = gateway
def _gateway_or_default(self):
if self._gateway is not None:
return self._gateway
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询外部系统库存(经连接器框架)。
Args/Raises:
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
来源专属绑定待 P2/P3。
"""
result = self._gateway_or_default().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"invoice_no": invoice_no,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ErpQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
data = result.data or {}
found = bool(data.get("found"))
qty = data.get("quantity")
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
@@ -0,0 +1,91 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Iterable
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
@dataclass(frozen=True)
class AggregatedInvoice:
"""单 Invoice 汇总结果(含原始行追溯)。"""
source_code: str
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
class InvoiceConflictError(AppError):
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
super().__init__(
code=TRANSFER_INVOICE_CONFLICT,
message=message,
http_status=422,
details={"invoice_no": invoice_no, "conflict": conflict},
)
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
for row in group
)
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
))
return invoices
@@ -0,0 +1,66 @@
"""在途调拨人工关闭服务。
用途:将异常项标记为 manually_closed(原因必填、永久排除、历史保留)。
依赖:models、status、audit、contracts。
逻辑:result_unknown / success / duplicate_success / manually_closed 禁止关闭。
"""
from __future__ import annotations
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工关闭一个异常 Invoice。
Args:
item_id: TransferInvoiceItem.id。
reason: 关闭原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": "manually_closed"}。
Raises:
ValidationError: 原因缺失或状态不可关闭。
NotFoundError: item 不存在。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status in {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
}:
raise ValidationError(f"item status {item.status} is not closeable", code="TRANSFER.MANUAL_CLOSE_NOT_ALLOWED")
before_status = item.status
item.status = status_machine.TransferStatus.MANUALLY_CLOSED.value
item.result_code = "manually_closed"
item.result_message = reason_value
item.manually_closed_reason = reason_value
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_MANUALLY_CLOSED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
actor_type="user",
actor_id=str(actor_id) if actor_id is not None else None,
request_id=request_id,
result="success",
before={"status": before_status},
after={"status": item.status, "reason": reason_value},
))
db.session.commit()
return {"item_id": item.id, "status": item.status}
@@ -0,0 +1,56 @@
"""在途调拨运营指标。
用途:从数据库现状投影成功率、失败类型、待处理老化与通知失败等指标,
供运营看板与告警使用。
依赖:models、backlog_service。
逻辑:指标只读,不触发任何外部调用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.backlog_service import backlog_summary
from app.services.in_transit_transfer.status import TransferNotificationStatus
def collect_metrics(*, now: datetime | None = None) -> dict[str, Any]:
"""采集调拨域指标。
Args:
now: 判定时刻(老化计算用)。
Returns:
{"runs": {...}, "items": {...}, "backlog": {...}}。
"""
runs_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferRun.status).all():
runs_by_status[str(status)] = runs_by_status.get(str(status), 0) + 1
notification_failed_runs = TransferRun.query.filter_by(
notification_status=TransferNotificationStatus.FAILED.value,
).count()
items_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferInvoiceItem.status).all():
items_by_status[str(status)] = items_by_status.get(str(status), 0) + 1
backlog = backlog_summary(now=now)
return {
"runs": {
**runs_by_status,
"notification_failed_runs": notification_failed_runs,
},
"items": items_by_status,
"backlog": {
"recoverable": backlog.recoverable_count,
"closed": backlog.closed_count,
"unknown": backlog.unknown_count,
"aging": {
"warn_3d": backlog.warn_3d,
"escalate_5d": backlog.escalate_5d,
"critical_7d": backlog.critical_7d,
},
},
}
@@ -0,0 +1,75 @@
"""在途调拨通用异动/移动表领域字段契约。
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
依赖:标准库 dataclasses / enum。
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
class MovementFieldValueType(StrEnum):
"""领域字段值类型(校验与展示共用)。"""
TEXT = "text"
DECIMAL = "decimal"
DATE = "date"
@dataclass(frozen=True)
class MovementField:
"""单个定死异动字段契约。
Args:
code: 稳定字段名(运行时契约)。
label: 业务中文名。
value_type: 值类型(text / decimal / date)。
is_identity: 是否参与幂等/匹配键。
required: 是否必填(缺省阻断)。
"""
code: str
label: str
value_type: MovementFieldValueType
is_identity: bool = False
required: bool = False
# 定死的 10 个通用异动字段(领域契约,不配置化)。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
MovementField("in_out_flag", "进出库别", MovementFieldValueType.TEXT),
MovementField("material_code", "料号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("material_name", "品名", MovementFieldValueType.TEXT),
MovementField("warehouse_code", "仓库", MovementFieldValueType.TEXT),
MovementField("storage_code", "储位", MovementFieldValueType.TEXT),
MovementField("lot_no", "批号", MovementFieldValueType.TEXT),
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
)
def movement_match_key() -> str:
"""调拨幂等/汇总键:单号 doc_no。"""
return "doc_no"
def movement_quantity_field() -> str:
"""严格数量匹配字段:数量 quantity。"""
return "quantity"
def movement_identity_fields() -> set[str]:
"""参与幂等/匹配判定的字段集(doc_no / material_code / movement_date)。"""
return {field.code for field in MOVEMENT_FIELDS if field.is_identity}
def movement_field_codes() -> set[str]:
"""全部定死字段名集合。"""
return {field.code for field in MOVEMENT_FIELDS}
@@ -0,0 +1,125 @@
"""在途调拨真实异动(收料/出货)文件仓库。
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
def __init__(self) -> None:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
return None
data = self._storage.get_bytes(report.storage_key)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
)
return ReadyReceiptFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
rows=tuple(rows),
)
def _extract_movement_rows(
data: bytes,
*,
field_mapping: Mapping[str, str],
sheet_name: str | None = None,
header_row_index: int | None = None,
) -> list[dict[str, Any]]:
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
if sheet_name and sheet_name in wb.sheetnames:
ws = wb[sheet_name]
else:
ws = wb.active
raw_rows: list[list[Any]] = [list(row) for row in ws.iter_rows(values_only=True)]
finally:
wb.close()
if not raw_rows:
return []
header_idx: int | None = None
if header_row_index is not None:
idx = int(header_row_index) - 1
if 0 <= idx < len(raw_rows):
header_idx = idx
if header_idx is None:
header_idx = find_inventory_header_row_index(raw_rows)
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
return output
@@ -0,0 +1,84 @@
"""在途调拨企业微信汇总通知。
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
依赖:models、audit、typing.Protocol。
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
"""
from __future__ import annotations
from typing import Any, Protocol
from app import db
from app.core.errors import NotFoundError
from app.models import TransferRun
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.status import TransferNotificationStatus
class WeComSender(Protocol):
"""企业微信汇总通知协议(测试注入 FakeWeCom)。"""
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""发送一次汇总通知。"""
def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None,
excel_path: str | None = None) -> dict[str, Any]:
"""为 Run 发送一条汇总通知(幂等)。
Args:
run_no: Run 编号。
sender: 企微发送器。
recipients: 接收人列表(缺省空)。
excel_path: 异常 Excel 附件路径(可空)。
Returns:
{"run_no", "notification_status", "delivered"};空数据返回 skipped。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if not run.items:
# 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"}
if run.notification_status == TransferNotificationStatus.SUCCESS.value:
# 已成功投递:幂等跳过,保证每个 Run 恰好一条。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False}
summary = {
"run_no": run.run_no,
"status": run.status,
"business_date": run.business_date,
"counts": dict(run.counts_json or {}),
"result_summary": dict(run.result_summary_json or {}),
}
outcome = sender.send_summary(
run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path,
)
outcome = outcome if isinstance(outcome, dict) else {}
failed = str(outcome.get("status") or "success") != "success"
run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value
if failed:
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
run.notification_error_message = str(outcome.get("error_message") or "")
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_NOTIFICATION",
aggregate_type="transfer_run",
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type="worker",
result="failure" if failed else "success",
before={"status": run.status, "notification_status": "pending"},
after={"status": run.status, "notification_status": run.notification_status},
))
db.session.commit()
return {
"run_no": run.run_no,
"notification_status": run.notification_status,
"delivered": True,
}
@@ -0,0 +1,83 @@
"""在途调拨执行编排(Run 生命周期辅助)。
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
按明细终态收尾 Run(success / partial_failed)。
依赖:models、status、precheck_service.TransferDeps。
逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from app import db
from app.core.errors import ConflictError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED"
def create_execution_run(
precheck: TransferPrecheck,
*,
deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展
actor_id: int | None = None,
selected_invoice_nos: set[str] | None = None,
) -> TransferRun:
"""为已就绪预检创建执行 Run 并关联选中的可执行明细。
Args:
precheck: 已预检(ready_to_execute)对象。
deps: 依赖集合(预留)。
actor_id: 确认操作者。
selected_invoice_nos: 选择范围(缺省关联全部可执行项)。
Returns:
状态为 executing 的 TransferRun。
Raises:
ConflictError: 预检已确认(重复执行)。
"""
if precheck.confirmed_at is not None:
raise ConflictError(
"precheck already executed", code=EXECUTION_CONFLICT_CODE,
)
run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}"
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=precheck.business_date,
status=status_machine.TransferRunStatus.EXECUTING.value,
source_codes_json=list(precheck.scope_json.get("source_codes") or []),
counts_json=dict(precheck.counts_json or {}),
)
db.session.add(run)
db.session.flush()
precheck.run_id = run.id
precheck.status = status_machine.TransferRunStatus.EXECUTING.value
precheck.confirmed_at = datetime.utcnow()
precheck.confirmed_by = actor_id
for item in precheck.items:
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None:
continue
if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos:
continue
item.run_id = run.id
item.status = status_machine.TransferStatus.EXECUTING.value
item.attempt_no += 1
db.session.flush()
return run
def finalize_run(run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""按明细终态汇总 Run 状态(全部 success/duplicate_success → success,否则 partial_failed)。"""
statuses = {str(item.status) for item in items}
terminal_ok = {status_machine.TransferStatus.SUCCESS.value, status_machine.TransferStatus.DUPLICATE_SUCCESS.value}
if statuses and statuses <= terminal_ok:
run.status = status_machine.TransferRunStatus.SUCCESS.value
else:
run.status = status_machine.TransferRunStatus.PARTIAL_FAILED.value
run.completed_at = datetime.utcnow()
@@ -0,0 +1,578 @@
"""在途调拨预检服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
"""
from __future__ import annotations
import uuid
from dataclasses import asdict, dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Protocol
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import canonical_hash
from app.services.in_transit_transfer.contracts import (
PrecheckCountsDTO,
PrecheckInvoiceItemDTO,
PrecheckSummaryDTO,
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
ReadyReceiptFile,
ReceiptFileRepository,
RpaTrigger,
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
# 明细结果值(对应 Invoice 项状态)
RESULT_EXECUTABLE = "executable"
RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
@dataclass(frozen=True)
class RouteMapping:
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
erp_org: str
from_warehouse: str
to_warehouse: str
class RouteNotResolvedError(AppError):
"""来源实例缺少路由归属映射(fail-closed)。"""
def __init__(self, *, source_code: str):
super().__init__(
code=ROUTE_NOT_RESOLVED_CODE,
message=f"route not resolved for source {source_code}",
http_status=422,
details={"source_code": source_code},
)
class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
class SourceProgressDTO:
"""来源实例级进度(决策 18:来源隔离展示)。"""
source_code: str
stage: str
file_no: str | None = None
file_version: str | None = None
checksum: str | None = None
error_code: str | None = None
error_message: str | None = None
@dataclass(frozen=True)
class PrecheckRunResult:
"""一次预检运行的完整结果。"""
summary: PrecheckSummaryDTO
items: tuple[PrecheckInvoiceItemDTO, ...]
sources: tuple[SourceProgressDTO, ...]
@dataclass(frozen=True)
class TransferDeps:
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
erp: Any
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
if any(source.stage not in {"file_ready"} for source in sources):
return "file_pending"
if counts.executable_count > 0:
return "ready_to_execute"
return "success"
def run_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
business_date: 业务日期 T(YYYY-MM-DD)。
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(创建 Run 前可为占位)。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空。
"""
if not source_codes:
raise ValidationError("source_codes is required")
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
items: list[PrecheckInvoiceItemDTO] = []
file_snapshot: dict[str, Any] = {}
for source_code in source_codes:
source_stage: SourceProgressDTO
try:
prepared = ensure_receipt_file_ready(
source_code=source_code,
business_date=business_date,
repository=deps.file_repository,
rpa_trigger=deps.rpa_trigger,
active_source_job_key=active_source_job_key,
)
if prepared.stage != "file_ready" or prepared.file is None:
sources.append(SourceProgressDTO(
source_code=source_code,
stage=prepared.stage,
error_code=prepared.error_code,
error_message=prepared.error_message,
))
continue
ready_file = prepared.file
file_snapshot[source_code] = {
"file_no": ready_file.file_no,
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
business_date=business_date,
ready_file=ready_file,
deps=deps,
run_no=run_no,
)
items.extend(source_items)
sources.append(SourceProgressDTO(
source_code=source_code,
stage="file_ready",
file_no=ready_file.file_no,
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except RouteNotResolvedError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
error_message=str(exc),
))
counts = PrecheckCountsDTO(
file_invoice_count=sum(
1 for item in items
),
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
)
estimated_quantity = sum(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
"file_snapshot": file_snapshot,
"counts": {
"file_invoice_count": counts.file_invoice_count,
"not_matured_count": counts.not_matured_count,
"prechecked_count": counts.prechecked_count,
"executable_count": counts.executable_count,
"blocked_count": counts.blocked_count,
},
"items": [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"result": item.result,
}
for item in items
],
}
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
sources_tuple = tuple(sources)
summary = PrecheckSummaryDTO(
precheck_id="", # 落库时回填
status=_summary_status(sources_tuple, counts),
business_date=business_date,
eligible_receipt_date_to=str(
(date.fromisoformat(business_date) - timedelta(days=1))
),
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_erp_write_count=counts.executable_count,
precheck_hash=precheck_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
def _precheck_invoices(
*,
invoices: list,
source_code: str,
business_date: str,
ready_file: ReadyReceiptFile,
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
for invoice in invoices:
maturity = maturity_status(invoice.receipt_date, business_date)
raw = tuple(
RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version)
for line in invoice.raw_lines
)
receipt_date_iso = invoice.receipt_date.isoformat()
if maturity == MATURITY_NOT_MATURED:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
raw_lines=raw,
))
continue
if maturity == MATURITY_FUTURE:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
raw_lines=raw,
))
continue
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=run_no,
attempt_no=1,
invoice_no=invoice.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=invoice.receipt_quantity,
)
except ErpQueryTimeoutError:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
raw_lines=raw,
))
return output
def _item_status(result: str) -> str:
"""明细结果 → Invoice 项状态。"""
mapping = {
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
}
return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value)
def _generate_no(prefix: str, business_date: str) -> str:
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
compact = str(business_date).replace("-", "")
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
def create_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
Args:
source_codes / business_date / deps: 同 run_precheck。
Returns:
预检摘要(precheck_id 已回填)。
"""
run_no = _generate_no("RUN", business_date)
result = run_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
run_no=run_no,
)
now = datetime.utcnow()
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=business_date,
status="prechecking",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
)
db.session.add(run)
db.session.flush()
# 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。
# 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。
from app.services.in_transit_transfer.source_job_service import create_source_job
_valid_job_statuses = {
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
}
for job_source in result.sources:
create_source_job(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
)
precheck_no = _generate_no("TPC", business_date)
precheck = TransferPrecheck(
precheck_no=precheck_no,
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
"file_version": stage.file_version,
"checksum": stage.checksum,
}
for stage in result.sources
if stage.file_no
},
mapping_version="v0",
strategy_version="v0",
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.flush()
for item in result.items:
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
))
db.session.commit()
summary = PrecheckSummaryDTO(
precheck_id=precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
)
return summary
def restore_precheck(precheck_id: str) -> dict[str, Any]:
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
Args:
precheck_id: 预检编号(TPC-...)。
Returns:
{"summary": {...}, "items": [...], "sources": [...]}。
Raises:
NotFoundError: 预检不存在。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip()
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
counts = PrecheckCountsDTO(**{
key: int(precheck.counts_json.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
})
summary = PrecheckSummaryDTO(
precheck_id=precheck.precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=str(
date.fromisoformat(precheck.business_date) - timedelta(days=1)
),
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=counts,
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
precheck_hash=precheck.precheck_hash,
)
items = []
for item in sorted(precheck.items, key=lambda row: row.invoice_no):
items.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
raw_lines=tuple(
RawLineRefDTO(
sheet=line.get("sheet", ""),
row_no=int(line.get("row_no", 0)),
file_version=line.get("file_version", ""),
)
for line in (item.raw_lines_json or [])
),
))
sources = [
SourceProgressDTO(
source_code=job.source_code,
stage=job.status,
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
SourceProgressDTO(source_code=code, stage="file_ready")
for code in (precheck.scope_json.get("source_codes") or [])
]
return {
"summary": summary,
"items": items,
"sources": sources,
}
@@ -0,0 +1,61 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
# 匹配结果
MATCH_EXECUTABLE = "executable"
MATCH_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
class QuantityValidationError(ValueError):
"""收料数量非法(0、负数、非数字)。"""
def validate_receipt_quantity(value: Any) -> Decimal:
"""校验并归一化收料数量。
Args:
value: 数字或数字字符串。
Returns:
归一化后的 Decimal。
Raises:
QuantityValidationError: 非数字、0 或负数。
"""
try:
quantity = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
if quantity <= 0:
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
return quantity
def strict_quantities_equal(left: Any, right: Any) -> bool:
"""Decimal 精确相等比较(1.0 == 1.00)。"""
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
erp_quantity: ERP 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if erp_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, erp_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -0,0 +1,57 @@
"""在途调拨收料回调桥。
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import TransferSourceJob
_FILE_READY = 'file_ready'
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def advance_source_job_from_receipt_callback(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
"""按来源推进最新等待回调的调拨来源任务。
Args:
source_code: 回调所属来源实例。
file_no: 收料文件号(success 时)。
file_sha256: 收料文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
"""
job = (
TransferSourceJob.query
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
.order_by(TransferSourceJob.id.desc())
.first()
)
if job is None:
return None
if callback_ok and file_no:
job.status = _FILE_READY
job.file_no = file_no
job.file_sha256 = file_sha256
job.error_code = None
job.error_message = None
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
job.error_message = error_message or 'receipt rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
@@ -0,0 +1,101 @@
"""在途调拨真实收料 RPA 触发服务。
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
import uuid
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'warehouse_id': warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def trigger_receipt_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
@@ -0,0 +1,87 @@
"""在途调拨 Worker 崩溃/陈旧执行恢复(区别于 recovery_service 的每日历史复核)。
用途:回收租约过期的 executing 项(重新写前复查 + 幂等写入,不重复建单),
并将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
依赖:execution_service._write_item、orchestrator.finalize_run、status。
逻辑:恢复依赖 Invoice 幂等(重复返回原单号 duplicate_success);
result_unknown 绝不自动重试。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.execution_service import _write_item
from app.services.in_transit_transfer.orchestrator import finalize_run
from app.services.in_transit_transfer.precheck_service import TransferDeps
STALE_EXECUTION_THRESHOLD_SECONDS = 3600
_TERMINAL_ITEM_STATUSES = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
}
def recover_stale_execution_items(*, deps: TransferDeps, now: datetime | None = None,
request_id: str | None = None) -> dict:
"""回收租约过期的执行中明细。
Args:
deps: 注入依赖。
now: 判定时刻。
request_id: 审计上下文。
Returns:
{"recovered": n, "skipped_result_unknown": n, "failed": n}。
"""
current = now or datetime.utcnow()
threshold = current - timedelta(seconds=STALE_EXECUTION_THRESHOLD_SECONDS)
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status == status_machine.TransferStatus.EXECUTING.value,
TransferInvoiceItem.updated_at <= threshold,
).all()
recovered = skipped_unknown = failed = 0
for item in items:
if (item.result_code or "") == "result_unknown" or item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
skipped_unknown += 1
continue
run_no = item.run.run_no if item.run else "RUN-PENDING"
try:
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
recovered += 1
except Exception: # noqa: BLE001 —— 单项恢复失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "recovery_failed"
failed += 1
db.session.flush()
db.session.commit()
return {"recovered": recovered, "skipped_result_unknown": skipped_unknown, "failed": failed}
def finalize_stale_runs(*, now: datetime | None = None) -> list[int]:
"""将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
Args:
now: 判定时刻(保留参数)。
Returns:
已收尾的 Run id 列表。
"""
finalized: list[int] = []
runs = TransferRun.query.filter_by(
status=status_machine.TransferRunStatus.EXECUTING.value,
).all()
for run in runs:
items = list(run.items)
if items and all(item.status in _TERMINAL_ITEM_STATUSES for item in items):
finalize_run(run, items)
finalized.append(run.id)
db.session.flush()
db.session.commit()
return finalized
@@ -0,0 +1,66 @@
"""在途调拨每日历史恢复(自动复核待处理池)。
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
"""
from __future__ import annotations
from dataclasses import dataclass
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
from app.services.in_transit_transfer.retry_service import _recheck_item
@dataclass
class RecoveryOutcome:
"""每日恢复结果汇总。"""
recovered_count: int = 0
still_blocked_count: int = 0
skipped_result_unknown: int = 0
skipped_manually_closed: int = 0
attempts_created: int = 0
def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOutcome:
"""对可恢复异常执行每日自动复核。
Args:
business_date: 业务日期(仅用于审计上下文)。
deps: 注入依赖。
Returns:
RecoveryOutcome。
"""
outcome = RecoveryOutcome()
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
]),
).all()
for item in items:
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
# 只读隔离:不查询、不写入、不创建 Attempt。
outcome.skipped_result_unknown += 1
continue
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
# 永久排除。
outcome.skipped_manually_closed += 1
continue
before_attempt = item.attempt_no
new_status = _recheck_item(item, deps=deps, request_id=None)
if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
outcome.recovered_count += 1
else:
outcome.still_blocked_count += 1
if item.attempt_no > before_attempt:
outcome.attempts_created += 1
db.session.commit()
return outcome
@@ -0,0 +1,120 @@
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from decimal import Decimal
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
from app.services.in_transit_transfer.quantity import classify_quantity_match
RETRY_KIND_ERP_RECHECK = "erp_recheck"
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
Returns:
重检后的 item 状态。
"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no + 1,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
attempt.status = "failed"
else:
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
item.result_code = None
item.result_message = None
item.erp_quantity = str(query.quantity)
attempt.status = "success"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value else "failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no},
))
db.session.flush()
return item.status
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工重试异常项。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": ..., "attempt_no": ...}。
Raises:
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。
NotFoundError: item 不存在。
"""
kind_value = str(kind or "").strip()
if kind_value == RETRY_KIND_RPA_REFETCH:
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
if kind_value != RETRY_KIND_ERP_RECHECK:
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
@@ -0,0 +1,77 @@
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
依赖:contracts、execution_service。
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
"""
from __future__ import annotations
from typing import Any
from app.services.in_transit_transfer.execution_service import serialize_run_result
def serialize_summary(summary) -> dict[str, Any]:
"""预检摘要序列化。"""
return {
"precheck_id": summary.precheck_id,
"status": summary.status,
"business_date": summary.business_date,
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
"expires_at": summary.expires_at,
"counts": {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"prechecked_count": summary.counts.prechecked_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
},
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
"estimated_erp_write_count": summary.estimated_erp_write_count,
"precheck_hash": summary.precheck_hash,
}
def serialize_item(item) -> dict[str, Any]:
"""明细项序列化(决策 6 十列字段)。"""
return {
"source_code": item.source_code,
"material_no": item.material_no,
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"receipt_date": item.receipt_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"to_warehouse": item.to_warehouse,
"to_quantity": str(item.to_quantity),
"result": item.result,
"reason": item.reason,
"raw_lines": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
def serialize_source(source) -> dict[str, Any]:
"""来源进度序列化。"""
return {
"source_code": source.source_code,
"stage": source.stage,
"file_no": source.file_no,
"file_version": source.file_version,
"checksum": source.checksum,
"error_code": source.error_code,
"error_message": source.error_message,
}
def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]:
"""预检恢复详情(summary + items + sources)。"""
return {
"summary": serialize_summary(detail["summary"]),
"items": [serialize_item(item) for item in detail["items"]],
"sources": [serialize_source(source) for source in detail["sources"]],
}
@@ -0,0 +1,63 @@
"""在途调拨来源收料文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;否则 → none。
"""
from __future__ import annotations
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is not None:
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
}
active_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -0,0 +1,70 @@
"""在途调拨来源级状态服务(唯一推进入口)。
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
依赖:models(TransferSourceJob)、status_machine。
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferSourceJob
SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
Args:
run_id: 所属 TransferRun.id。
source_code: 来源实例编码。
status: 初始状态。
Returns:
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
"""
existing = (
TransferSourceJob.query.filter_by(run_id=run_id, source_code=source_code).order_by(TransferSourceJob.id.desc()).first()
)
if existing is not None:
return existing
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
db.session.add(job)
db.session.flush()
return job
def advance_source_job(*, job: TransferSourceJob, status: str, **fields: Any) -> TransferSourceJob:
"""推进单条来源 job 状态并写入来源级事实字段。
Args:
job: 目标 TransferSourceJob。
status: 目标状态(须在 SOURCE_JOB_STATUSES 内,模型 CheckConstraint 兜底)。
fields: 其余来源级字段(file_no/file_sha256/error_code/error_message/lease_until 等),
可选 finished_at 被重置为当前时间。
Returns:
更新后的 job。
"""
job.status = status
for key, value in fields.items():
if hasattr(job, key):
setattr(job, key, value)
if status in ('success', 'partial_failed', 'failed', 'cancelled'):
job.finished_at = datetime.utcnow()
if status == 'pending':
job.started_at = datetime.utcnow()
db.session.flush()
return job
def source_jobs_for_run(run_id: int) -> list[TransferSourceJob]:
"""读取某次 run 的全部来源级 job(供 restore/投影)。"""
return TransferSourceJob.query.filter_by(run_id=run_id).order_by(TransferSourceJob.source_code).all()
@@ -0,0 +1,217 @@
"""在途调拨状态机与转换门禁。
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
(TransferRunStatus)与通知状态(TransferNotificationStatus),
并强制所有状态转换走服务端门禁。
依赖:app.core.errors.AppError。
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态;
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
"""
from __future__ import annotations
from enum import StrEnum
from typing import Mapping
from app.core.errors import AppError
INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
class TransferStatus(StrEnum):
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
FILE_PENDING = "file_pending"
FILE_READY = "file_ready"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
DUPLICATE_SUCCESS = "duplicate_success"
BLOCKED_RECOVERABLE = "blocked_recoverable"
NOT_MATURED = "not_matured"
RESULT_UNKNOWN = "result_unknown"
MANUALLY_CLOSED = "manually_closed"
CANCELLED = "cancelled"
NOTIFICATION_FAILED = "notification_failed"
class TransferRunStatus(StrEnum):
"""Run 级生命周期;ERP 结果与通知结果分离。"""
QUEUED = "queued"
PREPARING_FILES = "preparing_files"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
PARTIAL_FAILED = "partial_failed"
FAILED = "failed"
CANCELLED = "cancelled"
class TransferNotificationStatus(StrEnum):
"""通知投递状态;failed 即提示词中 notification_failed 的语义。"""
PENDING = "pending"
SUCCESS = "success"
FAILED = "failed"
# 无出边终态:这些状态不得再触发任何自动或手工迁移。
TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.NOTIFICATION_FAILED.value,
})
# Invoice 项转换白名单:key=当前状态,value=允许的目标状态集合。
ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.FILE_PENDING.value: frozenset({
TransferStatus.FILE_READY.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.FILE_READY.value: frozenset({
TransferStatus.PRECHECKING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.PRECHECKING.value: frozenset({
TransferStatus.READY_TO_EXECUTE.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.READY_TO_EXECUTE.value: frozenset({
TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检
TransferStatus.EXECUTING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.EXECUTING.value: frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.NOT_MATURED.value: frozenset(),
TransferStatus.SUCCESS.value: frozenset(),
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
TransferStatus.RESULT_UNKNOWN.value: frozenset(),
TransferStatus.MANUALLY_CLOSED.value: frozenset(),
TransferStatus.CANCELLED.value: frozenset(),
TransferStatus.NOTIFICATION_FAILED.value: frozenset(),
}
# Run 级转换白名单。
RUN_TRANSITIONS: dict[str, frozenset[str]] = {
TransferRunStatus.QUEUED.value: frozenset({
TransferRunStatus.PREPARING_FILES.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PREPARING_FILES.value: frozenset({
TransferRunStatus.PRECHECKING.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PRECHECKING.value: frozenset({
TransferRunStatus.READY_TO_EXECUTE.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.READY_TO_EXECUTE.value: frozenset({
TransferRunStatus.EXECUTING.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.EXECUTING.value: frozenset({
TransferRunStatus.SUCCESS.value,
TransferRunStatus.PARTIAL_FAILED.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.SUCCESS.value: frozenset(),
TransferRunStatus.PARTIAL_FAILED.value: frozenset(),
TransferRunStatus.FAILED.value: frozenset(),
TransferRunStatus.CANCELLED.value: frozenset(),
}
class TransferStateError(AppError):
"""非法状态转换领域错误。"""
def __init__(
self,
message: str = "Invalid state transition",
*,
current: str | None = None,
target: str | None = None,
):
details: dict[str, str] = {}
if current is not None:
details["current"] = current
if target is not None:
details["target"] = target
super().__init__(
code=INVALID_STATE_TRANSITION_CODE,
message=message,
http_status=409,
details=details,
)
def assert_transition_allowed(
current: str,
target: str,
*,
transitions: Mapping[str, frozenset[str]] = ITEM_TRANSITIONS,
) -> None:
"""服务端状态转换门禁。
Args:
current: 当前状态。
target: 目标状态。
transitions: 转换白名单(默认 Invoice 项表)。
Raises:
TransferStateError: 当前状态未知或目标不在允许集合内。
"""
current_value = str(current or "").strip()
target_value = str(target or "").strip()
allowed = transitions.get(current_value)
if allowed is None:
raise TransferStateError("unknown current status", current=current_value)
if target_value not in allowed:
raise TransferStateError(
"status transition not allowed",
current=current_value,
target=target_value,
)
def apply_notification_failure(run_status: str) -> str:
"""通知失败不改变 ERP 结果。
Args:
run_status: Run 的 ERP 业务终态。
Returns:
原 run_status(保持不变)。
Raises:
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
"""
status = str(run_status or "").strip()
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
raise TransferStateError(
"notification failure only allowed after ERP terminal status",
current=status,
)
return status
@@ -0,0 +1,61 @@
"""在途调拨策略硬门禁。
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
强制默认 10 分钟确认有效期。
依赖:app.core.errors.AppError、standard decimal。
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
阻止发布/执行(fail-closed)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from app.core.errors import AppError
STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION"
DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟
@dataclass(frozen=True)
class TransferStrategyPolicy:
"""调拨策略冻结快照;三项禁令默认关闭。"""
allow_partial: bool = False
quantity_tolerance: Decimal = Decimal("0")
allow_erp_auto_retry: bool = False
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
class StrategyViolationError(AppError):
"""策略触碰一期禁令。"""
def __init__(self, message: str, *, reason: str):
super().__init__(
code=STRATEGY_VIOLATION_CODE,
message=message,
http_status=409,
details={"reason": reason},
)
def validate_strategy(strategy: TransferStrategyPolicy) -> None:
"""校验策略是否违反一期硬门禁。
Args:
strategy: 待校验策略。
Raises:
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
"""
if strategy.allow_partial:
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
if strategy.quantity_tolerance != Decimal("0"):
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
if strategy.allow_erp_auto_retry:
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
def default_strategy() -> TransferStrategyPolicy:
"""返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。"""
return TransferStrategyPolicy()
Loaded 100 of 732 files, more files were not shown because too many files have changed in this diff. Show more