Merge branch 'dev' into runny0914
This commit is contained in:
commit
594d9c22b5
267 files changed
+19053
-3489
No files matched your search
@@ -146,6 +146,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||
|
||||
@@ -158,6 +158,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inven
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
|
||||
@@ -238,6 +238,7 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2
|
||||
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
||||
|
||||
|
||||
@@ -175,6 +175,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
|
||||
@@ -16,6 +16,7 @@ import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.permission_roles # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
|
||||
@@ -22,21 +22,11 @@ def dashboard_summary():
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -28,6 +28,13 @@ def create_department():
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
api/admin/permission_roles.py
|
||||
|
||||
用途:管理端权限组列表、编辑、成员预览与确认调整。
|
||||
依赖:admin.blueprint、permission_roles.service。
|
||||
逻辑:/permission-roles* 路由;成员调整必须先 preview 再 apply。
|
||||
"""
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.permission_roles import service as role_service
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_roles():
|
||||
"""列出全部权限组。"""
|
||||
return jsonify(role_service.list_roles())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_catalog():
|
||||
"""角色编辑可选应用与应用内能力。"""
|
||||
return jsonify(role_service.grantable_catalog())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/picker-users', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_picker_users():
|
||||
"""选人弹窗候选人(排除管理员)。"""
|
||||
return jsonify(role_service.list_picker_people())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_permission_role():
|
||||
"""新建权限组。"""
|
||||
data = request.get_json() or {}
|
||||
payload = role_service.create_role(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_permission_role(code: str):
|
||||
"""权限组详情。"""
|
||||
return jsonify(role_service.get_role_detail(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_permission_role(code: str):
|
||||
"""保存权限包并同步该组用户授权。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.update_role(code, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_permission_role(code: str):
|
||||
"""删除空的非内置权限组。"""
|
||||
return jsonify(role_service.delete_role(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members/preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_permission_role_members(code: str):
|
||||
"""确认前预览将改入/移出的人及来源角色。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.preview_role_members(code, data.get('selected_ids')))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members', methods=['POST'])
|
||||
@require_admin
|
||||
def apply_permission_role_members(code: str):
|
||||
"""确认后写回成员。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.apply_role_members(code, data.get('selected_ids')))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
用途:管理后台应用权限批量更新 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
逻辑:/permissions/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -28,22 +28,3 @@ def update_user_permissions(id: int):
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
"""聊天使用分析报表(统计范围:start_date/end_date 自定义日期优先,否则 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
@@ -34,6 +34,8 @@ def usage_report():
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -43,7 +45,7 @@ def usage_report():
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
Query: start_date, end_date(自定义日期优先), range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
@@ -56,6 +58,8 @@ def applications_report():
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
@@ -67,6 +71,22 @@ def applications_report():
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/overview', methods=['GET'])
|
||||
@require_admin
|
||||
def ops_overview_report():
|
||||
"""
|
||||
运营总览报表:对话量 / 活跃用户 / 活跃应用 / 趋势环比 / Top 与低使用应用 / 未处理反馈。
|
||||
Query: start_date, end_date(自定义日期优先),否则 range(7d/30d/90d/180d/365d)。
|
||||
"""
|
||||
return jsonify(
|
||||
report_service.build_ops_overview_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
@@ -86,3 +106,31 @@ def list_general_feedbacks_report():
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/chat-log-tops', methods=['GET'])
|
||||
@require_admin
|
||||
def chat_log_tops():
|
||||
"""聊天日志 Top 提问/回答内容(直接按 ChatLog 明细统计,复用 FAQ 问句归一化)。"""
|
||||
return jsonify(report_service.build_chat_log_top_content(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback-summary', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_summary():
|
||||
"""用户反馈概览:待处理 / 本月已关闭 / 最多反馈应用(三张概览卡)。"""
|
||||
return jsonify(report_service.build_feedback_summary(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/issue-analysis', methods=['GET'])
|
||||
@require_admin
|
||||
def issue_analysis():
|
||||
"""问题分析:高频问题簇 KPI + 优先处理问题(复用聊天日志风险规则)。"""
|
||||
return jsonify(report_service.build_issue_analysis_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/close', methods=['POST'])
|
||||
@require_admin
|
||||
def close_general_feedback(feedback_id: int):
|
||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
鐢ㄩ€旓細绠$悊鍚庡彴鐢ㄦ埛 CRUD API锛堣杽璺敱灞傦級銆?
|
||||
渚濊禆锛歛dmin.blueprint銆乻ervices/admin/user_service銆乧ore.auth.jwt銆?
|
||||
閫昏緫锛?users* 璺敱銆?
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -20,7 +20,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
"""Admin user operation."""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
@@ -28,7 +28,7 @@ def list_users():
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
@@ -37,22 +37,30 @@ def create_user():
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch', methods=['PUT'])
|
||||
@require_admin
|
||||
def batch_update_users():
|
||||
"""批量更新用户部门 / 角色 / 状态。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.batch_update_users(data.get('user_ids', []), data.get('data') or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
"""Admin user operation."""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
@@ -62,21 +70,7 @@ def batch_delete_users():
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
"""Admin user operation."""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -37,7 +37,7 @@ def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = N
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
|
||||
@@ -7,8 +7,8 @@ backend/app/api/contract_payment/__init__.py
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -111,7 +111,7 @@ def _require_contract_payment_access():
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
if user.is_platform_admin() or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
@@ -124,7 +124,7 @@ def _require_contract_payment_admin():
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
会改写外部系统或触发企微,因此仅平台管理员可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
@@ -135,7 +135,7 @@ def _require_contract_payment_admin():
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
|
||||
@@ -65,12 +65,12 @@ def _require_user():
|
||||
|
||||
|
||||
def require_transfer_permission(f):
|
||||
"""装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
"""装饰器:平台管理员放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
user = _require_user()
|
||||
if user.role == "admin":
|
||||
if user.is_platform_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:
|
||||
@@ -322,15 +322,18 @@ def retrigger_document_api(run_no: str, doc_no: str):
|
||||
@in_transit_transfer_bp.route("/documents", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_documents_api():
|
||||
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
|
||||
"""已执行单分页查询(首页「执行看板」区块数据源;只读,不写审计)。
|
||||
|
||||
Query:
|
||||
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表,
|
||||
按收料日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换);
|
||||
page(默认 1);page_size(默认 20,上限 100)。
|
||||
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
|
||||
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
|
||||
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
|
||||
列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨
|
||||
明细/待处理池/结果卡统一口径,跨数据源不再乱序;执行落库时间仅作
|
||||
同序兜底),cancelled 不展示(无产生路径)。
|
||||
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
|
||||
"""
|
||||
from app import db
|
||||
@@ -383,19 +386,28 @@ def list_documents_api():
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
|
||||
}
|
||||
|
||||
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
|
||||
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
|
||||
# [STEP 3] 列表查询:status_group / 时间窗仅作用列表;cancelled 恒不展示。
|
||||
# [2026-09-29 口径] 时间窗按收料日期过滤(receipt_date 为 ISO 日期字符串,
|
||||
# 字典序即时间序);排序与可调拨明细/结果卡统一:收料日期→数据源→库位升序,
|
||||
# created_at/id 兜底稳定分页(跨数据源不再按落库序乱序)。
|
||||
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
|
||||
if status_group:
|
||||
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
|
||||
if date_from:
|
||||
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
|
||||
query = query.filter(TransferDocument.receipt_date >= date_from.isoformat())
|
||||
if date_to:
|
||||
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
|
||||
query = query.filter(TransferDocument.created_at < window_end)
|
||||
window_end = (date_to + timedelta(days=1)).isoformat()
|
||||
query = query.filter(TransferDocument.receipt_date < window_end)
|
||||
total = query.count()
|
||||
docs = (
|
||||
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
|
||||
query.order_by(
|
||||
TransferDocument.receipt_date.asc(),
|
||||
TransferDocument.source_code.asc(),
|
||||
TransferDocument.from_warehouse.asc(),
|
||||
TransferDocument.to_warehouse.asc(),
|
||||
TransferDocument.created_at.asc(),
|
||||
TransferDocument.id.asc(),
|
||||
)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
@@ -507,9 +519,9 @@ def retry_document_api(doc_no: str):
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
|
||||
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
|
||||
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
|
||||
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
|
||||
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
行为:单内 blocked 行按组织批量重查(一次外部查询,行级 Attempt/隔离不变)
|
||||
→ 全部 ready 则自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);
|
||||
任一行仍阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
"""
|
||||
from app.services.in_transit_transfer.retry_service import retry_document
|
||||
|
||||
@@ -525,7 +537,7 @@ def retry_document_api(doc_no: str):
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离,按组织一次外部查询)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
@@ -698,7 +710,7 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
每来源附收料文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
@@ -725,13 +737,41 @@ def transfer_sources_api():
|
||||
def retry_source_rpa_api(source_code: str):
|
||||
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
|
||||
|
||||
响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。
|
||||
【AI 触发时机】来源收料文件不可用需要恢复时调用:解析失败(parse_failed)先
|
||||
本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。
|
||||
|
||||
解析失败优先本地重解析(解析失败分层 2026-09-29):当日文件可用但解析失败时,
|
||||
先走 sync_and_commit_for_callback 重解析归档文件——成功且投影回 ready →
|
||||
200 {"source_code", "ok": true, "file_status": "ready", "reparsed": true}
|
||||
(不触发 RPA、不返回 202/fetching);仍失败 → 同结构 ok=false
|
||||
(file_status=parse_failed)。其余状态沿用原路径:重新触发一次收料 RPA,
|
||||
成功 202+fetching;配置缺失时 fail-closed(ok=False)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
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()
|
||||
|
||||
# [STEP 1] 解析失败分层:文件可用但解析失败 → 先本地重解析归档文件,不触发 RPA。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
if status.get("file_status") == "parse_failed" and status.get("file_sha256"):
|
||||
synced = sync_and_commit_for_callback(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
now=datetime.utcnow(),
|
||||
)
|
||||
# 重解析后再取投影:以真实落库事实(而非 sync 返回值)决定 ok。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
ready = bool(synced) and status.get("file_status") == "ready"
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": ready,
|
||||
"file_status": status["file_status"],
|
||||
"reparsed": True,
|
||||
})
|
||||
|
||||
# [STEP 2] 其余状态沿用原路径:重新触发一次收料 RPA 抓取(202 + fetching)。
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
|
||||
@@ -55,9 +55,9 @@ def _require_ledger_admin():
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
if user.has_feature_permission('maintenance.ledger_write'):
|
||||
return user
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
@@ -18,7 +20,10 @@ from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_work
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
|
||||
Query:
|
||||
scope: inventory(默认)或 receipt。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory'
|
||||
return ok(serialize_rpa_worker_status(scope=scope))
|
||||
@@ -22,6 +22,7 @@ from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, Shi
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
@@ -123,6 +124,26 @@ def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/receipt-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_receipt_raw_zip(run_id: int):
|
||||
"""
|
||||
下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。
|
||||
|
||||
核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。
|
||||
"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_receipt_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
|
||||
@require_admin
|
||||
def resend_receipt_report_file(file_id: int):
|
||||
|
||||
@@ -435,7 +435,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
**user.client_auth_fields(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
|
||||
@@ -185,7 +185,7 @@ def home():
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
@@ -213,7 +213,7 @@ def home():
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -297,7 +297,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -348,7 +348,7 @@ def get_agent_details(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
@@ -199,7 +199,7 @@ def workspace_shipping_my_todos():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -224,7 +224,7 @@ def workspace_shipping_my_todos_count():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import count_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
@@ -249,7 +249,7 @@ def workspace_shipping_done_lines():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import list_done_notice_lines
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -276,7 +276,7 @@ def workspace_shipping_done_lines_export():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
stream, filename = build_done_lines_xlsx(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
@@ -302,7 +302,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
|
||||
def _can_dispose_task(user, task) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
return bool(user.is_platform_admin()) or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
@@ -345,7 +345,7 @@ def _batch_dispose(action: str):
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
@@ -542,7 +542,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
@@ -562,7 +562,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
def workspace_shipping_task_odm_options(task_no: str):
|
||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -576,7 +576,7 @@ def workspace_shipping_task_odm_options(task_no: str):
|
||||
def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -601,7 +601,7 @@ def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
@@ -633,7 +633,7 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
list_freight_notice_groups_for_task,
|
||||
@@ -1604,7 +1604,7 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
@@ -1639,7 +1639,7 @@ def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
@@ -1676,7 +1676,7 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_case_snapshot import (
|
||||
build_order_review_case_snapshot,
|
||||
@@ -1724,7 +1724,7 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
@@ -1762,7 +1762,7 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
source_content_hash: string(可选,请求快照用于参数一致性)
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
payload = request.get_json(silent=True) if request.is_json else None
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
@@ -1821,7 +1821,7 @@ def workspace_audit_shipping_order_review_version_history(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -1867,7 +1867,7 @@ def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -2135,7 +2135,7 @@ def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
@@ -2176,7 +2176,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
decide_review_line_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2277,7 +2277,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
close_remaining_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = close_remaining_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2690,7 +2690,7 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||||
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
|
||||
|
||||
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
|
||||
@@ -2700,7 +2700,7 @@ def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import request_field_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='request_llm_suggestion')
|
||||
@@ -2725,7 +2725,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
|
||||
|
||||
@@ -135,7 +135,7 @@ def workspace_post_process_gate_action(execution_no: str, gate_code: str):
|
||||
action_code=parsed['action_code'],
|
||||
expected_gate_version=parsed['expected_gate_version'],
|
||||
idempotency_key=parsed['idempotency_key'],
|
||||
actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user',
|
||||
actor_type='admin' if user.is_platform_admin() else 'user',
|
||||
actor_id=int(user.id),
|
||||
payload=parsed['payload'],
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,7 +42,7 @@ def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;平台管理员不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
@@ -58,18 +58,18 @@ def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
核心逻辑:is_platform_admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
已认证且具备立账凭证 Agent 授权(或平台管理员)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
if user.is_platform_admin() or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
@@ -81,7 +81,7 @@ def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 is_platform_admin。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
@@ -91,7 +91,7 @@ def _require_admin():
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
@@ -181,7 +181,7 @@ def workspace_voucher_notifications():
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
核心逻辑:仅 is_platform_admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
@@ -191,7 +191,7 @@ def workspace_voucher_notify_config_get():
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
核心逻辑:仅 is_platform_admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
|
||||
@@ -291,10 +291,17 @@ class Config:
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
||||
)
|
||||
# 行库存查得时刻(inventory_checked_at)的 stale 徽标判定窗口(纯展示阈值)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS', '86400') or '86400'
|
||||
)
|
||||
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')
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
|
||||
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2'
|
||||
)
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
||||
)
|
||||
@@ -465,6 +472,9 @@ class Config:
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
@@ -763,6 +773,8 @@ class TestingConfig(Config):
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
# 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600
|
||||
# 库存查得时刻 stale 阈值钉 24h(stale 用例按 86400s 书写)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = 86400
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
|
||||
@@ -47,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → 平台管理员放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -66,7 +66,7 @@ def require_agent_permission(f):
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
@@ -77,8 +77,8 @@ def require_agent_permission(f):
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
装饰器:限制仅平台管理员可访问。
|
||||
核心逻辑:解析用户 → 校验 is_platform_admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
@@ -88,7 +88,7 @@ def require_admin(f):
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/models/__init__.py
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
@@ -242,6 +243,8 @@ from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'permission_role_agents',
|
||||
'PermissionRole',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
|
||||
@@ -130,4 +130,8 @@ class GeneralFeedback(Base):
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
# 处理状态:pending=待处理,closed=已关闭(数据分析卡片用;默认待处理)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending', nullable=False, index=True)
|
||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -69,7 +69,8 @@ TRANSFER_DOCUMENT_STATUSES = (
|
||||
)
|
||||
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||||
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(test_document_model.py 锁定)。
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py
|
||||
# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。
|
||||
UNRESOLVED_DOC_STATUSES = (
|
||||
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||||
)
|
||||
@@ -262,6 +263,10 @@ class TransferInvoiceItem(Base):
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||||
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
||||
# 仅匹配评估/重查/写前复查在真实取数时写入;置空库存时同步置空)。NULL=无库存数据。
|
||||
inventory_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
models/permission_role.py
|
||||
|
||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
permission_role_agents = db.Table(
|
||||
'permission_role_agents',
|
||||
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||
)
|
||||
|
||||
|
||||
class PermissionRole(Base):
|
||||
"""权限组:可用应用入口 + 应用内能力。"""
|
||||
|
||||
__tablename__ = 'permission_roles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_permission_roles_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_platform_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
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,
|
||||
)
|
||||
|
||||
agents: Mapped[List['Agent']] = relationship(
|
||||
'Agent',
|
||||
secondary=permission_role_agents,
|
||||
)
|
||||
@@ -40,7 +40,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
|
||||
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -116,6 +116,10 @@ class ShippingReceiptReportFile(Base):
|
||||
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)
|
||||
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
|
||||
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
+42
-16
@@ -2,8 +2,9 @@
|
||||
backend/app/models/user.py
|
||||
|
||||
用途:用户账户、首页偏好、登录审计相关模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;admin/user API 主要读写本模块。
|
||||
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -59,7 +60,7 @@ class User(Base):
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
role: Mapped[str] = mapped_column(String(64), default='user')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
@@ -85,27 +86,41 @@ class User(Base):
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
"""返回当前角色自带的功能权限默认值。"""
|
||||
"""
|
||||
返回未配置权限组时的功能权限默认值。
|
||||
|
||||
核心逻辑:只认 is_platform_admin;不再用 hr / maintenance_manager 角色名暗示能力。
|
||||
"""
|
||||
admin = self.is_platform_admin()
|
||||
return {
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
|
||||
'shipping_notice.audit_sensitive_read': self.role == 'admin',
|
||||
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
'training_hr_manage': admin,
|
||||
'shipping_notice_force_create': admin,
|
||||
'shipping_notice.audit_sensitive_read': admin,
|
||||
'shipping_notice.xfa_split_rule_edit': admin,
|
||||
'shipping_notice.xfa_split_rule_preview': admin,
|
||||
'shipping_notice.xfa_split_rule_publish': admin,
|
||||
'maintenance.ledger_write': admin,
|
||||
}
|
||||
|
||||
def is_platform_admin(self) -> bool:
|
||||
"""当前用户是否属于平台管理权限组。"""
|
||||
from app.services.permission_roles.service import user_is_platform_admin
|
||||
|
||||
return user_is_platform_admin(self)
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
"""
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
||||
输出约束:仅返回布尔型权限键。
|
||||
"""
|
||||
from app.services.permission_roles.service import effective_feature_permissions
|
||||
|
||||
packaged = effective_feature_permissions(self)
|
||||
if packaged is not None:
|
||||
return packaged
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
|
||||
result: dict[str, bool] = {}
|
||||
@@ -121,7 +136,7 @@ class User(Base):
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
核心逻辑:只持久化与默认值不同的权限。未种子权限组时默认仅平台管理员全开;其余角色靠 JSON 覆盖或权限组能力键。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -143,6 +158,17 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def client_auth_fields(self) -> dict:
|
||||
"""登录态/首页共用的角色与功能权限字段。"""
|
||||
from app.services.permission_roles.service import list_role_name_map
|
||||
|
||||
names = list_role_name_map()
|
||||
return {
|
||||
'is_platform_admin': self.is_platform_admin(),
|
||||
'role_name': names.get(self.role) or self.role,
|
||||
'feature_permissions': self.get_feature_permissions(),
|
||||
}
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization、permission_roles。
|
||||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||||
权限组启用后 update_agent_permissions 拒绝按人改授权。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,7 +16,13 @@ import requests
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models import (
|
||||
Agent, AgentDirectoryMember, ChatLog, ChatSession, ChatToolRun,
|
||||
ContractReview, FaqHotCandidate, Feedback, GeneralFeedback,
|
||||
PermissionRequest, QuickQuestion, ScheduleTask, User,
|
||||
UserDefaultAgent, UserFavoriteAgent, user_agent_permissions,
|
||||
)
|
||||
from sqlalchemy import delete, select, update
|
||||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
@@ -112,11 +119,40 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
"""
|
||||
删除 Agent 及其数据库引用,避免 chat_logs 外键导致管理端删除失败。
|
||||
|
||||
[STEP 1] 清理权限、目录、收藏、默认入口及业务直接引用。
|
||||
[STEP 2] 先清理 chat_log 子表,再删除会话日志。
|
||||
[STEP 3] 最后删除 Agent,整段操作使用当前事务保证原子性。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
if not agent:
|
||||
return
|
||||
chat_log_ids = select(ChatLog.id).where(ChatLog.agent_id == agent_id)
|
||||
db.session.execute(delete(user_agent_permissions).where(user_agent_permissions.c.agent_id == agent_id))
|
||||
db.session.execute(delete(AgentDirectoryMember).where(
|
||||
(AgentDirectoryMember.directory_agent_id == agent_id)
|
||||
| (AgentDirectoryMember.member_agent_id == agent_id)
|
||||
))
|
||||
db.session.execute(delete(UserFavoriteAgent).where(UserFavoriteAgent.agent_id == agent_id))
|
||||
db.session.execute(delete(UserDefaultAgent).where(UserDefaultAgent.agent_id == agent_id))
|
||||
db.session.execute(update(User).where(User.default_agent_id == agent_id).values(default_agent_id=None))
|
||||
db.session.execute(update(ScheduleTask).where(ScheduleTask.dify_agent_id == agent_id).values(dify_agent_id=None))
|
||||
db.session.execute(delete(PermissionRequest).where(PermissionRequest.agent_id == agent_id))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.agent_id == agent_id))
|
||||
db.session.execute(delete(QuickQuestion).where(QuickQuestion.agent_id == agent_id))
|
||||
db.session.execute(delete(FaqHotCandidate).where(FaqHotCandidate.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatSession).where(ChatSession.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatToolRun).where(
|
||||
(ChatToolRun.agent_id == agent_id) | ChatToolRun.chat_log_id.in_(chat_log_ids)
|
||||
))
|
||||
db.session.execute(delete(Feedback).where(Feedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(GeneralFeedback).where(GeneralFeedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ChatLog).where(ChatLog.agent_id == agent_id))
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||||
@@ -170,68 +206,65 @@ def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
"""
|
||||
Test Dify endpoint reachability without executing the configured application flow.
|
||||
|
||||
The test calls Dify's read-only ``/v1/parameters`` endpoint so a business
|
||||
Chatflow/Workflow never receives synthetic text such as ``OK`` that could be
|
||||
passed into a database or other external tool.
|
||||
"""
|
||||
if not agent.dify_api_key:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Key\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing api_base_url.',
|
||||
'analysis': '测试失败:未配置 API Base URL。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Base URL\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
dify_app_type = 'chatflow'
|
||||
if dify_app_type == 'workflow':
|
||||
request_url = DifyService._build_workflow_url(base_url)
|
||||
payload = {
|
||||
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||||
|
||||
# [STEP 1] Read-only endpoint: never run a business Chatflow/Workflow in an admin connectivity test.
|
||||
request_url = DifyService._build_parameters_url(base_url)
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
response = requests.get(request_url, headers=headers, timeout=(5, 15))
|
||||
raw_text = (response.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
passed = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
if response.ok:
|
||||
passed = True
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
try:
|
||||
data = resp.json()
|
||||
if dify_app_type == 'workflow':
|
||||
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
|
||||
else:
|
||||
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
passed = True
|
||||
analysis = (
|
||||
'测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
if dify_app_type == 'workflow'
|
||||
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
)
|
||||
if passed and (not agent.is_active):
|
||||
analysis = '\u6d4b\u8bd5\u901a\u8fc7\uff1aDify \u53c2\u6570\u63a5\u53e3\u53ef\u8bbf\u95ee\u4e14 API Key \u8ba4\u8bc1\u901a\u8fc7\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict):
|
||||
output_info = str(body)[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
passed = False
|
||||
analysis = f'\u6d4b\u8bd5\u5931\u8d25\uff1aHTTP {response.status_code}\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict) and body.get('message'):
|
||||
output_info = str(body['message'])[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if passed and not agent.is_active:
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
@@ -240,7 +273,7 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': resp.status_code,
|
||||
'http_status': response.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
@@ -249,12 +282,11 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u8bf7\u6c42\u5f02\u5e38\uff08\u7f51\u7edc\u3001\u8d85\u65f6\u6216\u8ba4\u8bc1\u95ee\u9898\uff09\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
|
||||
passed = 200 <= resp.status_code < 300
|
||||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||||
@@ -291,7 +323,13 @@ def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, p
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||||
"""
|
||||
将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
from app.models import Agent, ChatLog, Feedback, User
|
||||
|
||||
|
||||
def compute_dashboard_summary() -> dict:
|
||||
@@ -32,29 +32,12 @@ def compute_dashboard_summary() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def compute_dashboard_badges() -> dict:
|
||||
"""
|
||||
聚合侧栏角标所需的待办数量。
|
||||
Returns:
|
||||
pending_approvals、pending_requests。
|
||||
"""
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
||||
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
}
|
||||
|
||||
|
||||
def compute_legacy_dashboard_stats() -> dict:
|
||||
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
|
||||
summary = compute_dashboard_summary()
|
||||
badges = compute_dashboard_badges()
|
||||
return {
|
||||
'total_users': summary['user_count'],
|
||||
'active_agents': summary['agent_count'],
|
||||
'total_conversations': summary['total_conversations'],
|
||||
'avg_score': summary['avg_score'],
|
||||
'pending_approvals': badges['pending_approvals'],
|
||||
'pending_requests': badges['pending_requests'],
|
||||
}
|
||||
@@ -19,7 +19,6 @@ from app.models import (
|
||||
ChatLog,
|
||||
Department,
|
||||
Feedback,
|
||||
PermissionRequest,
|
||||
QuickQuestion,
|
||||
User,
|
||||
UserDefaultAgent,
|
||||
@@ -33,7 +32,6 @@ ADMIN_TABLE_MODEL_MAP = {
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
@@ -52,6 +50,35 @@ def _serialize_model_row(item) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
def _apply_generic_table_filters(query, model, query_params: dict[str, str]):
|
||||
"""通用表筛选:created_at 时间范围(created_from/created_to)+ 各列 ILIKE/等值过滤。"""
|
||||
reserved = {'created_from', 'created_to'}
|
||||
# 时间范围(支持有 created_at 列的通用表,如 feedbacks 回答评价)
|
||||
created_from = (query_params.get('created_from') or '').strip()
|
||||
created_to = (query_params.get('created_to') or '').strip()
|
||||
if created_from and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_from, end_of_day=False)
|
||||
if dt:
|
||||
query = query.filter(model.created_at >= dt)
|
||||
if created_to and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_to, end_of_day=True)
|
||||
if dt:
|
||||
query = query.filter(model.created_at <= dt)
|
||||
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if hasattr(model, key):
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
"""
|
||||
返回管理报表表数据(最多 100 行)。
|
||||
@@ -62,28 +89,20 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
query = db.session.query(model)
|
||||
for key, value in query_params.items():
|
||||
if hasattr(model, key) and value:
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
items = query.limit(100).all()
|
||||
return [_serialize_model_row(item) for item in items]
|
||||
|
||||
|
||||
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
|
||||
"""返回表行数;chat_logs 使用报表筛选。"""
|
||||
"""返回表行数(应用当前筛选);chat_logs 使用报表筛选。"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.count_chat_logs_report(query_params)
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
total = db.session.query(func.count(model.id)).scalar()
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
total = query.count()
|
||||
return {'table': table, 'total': int(total or 0)}
|
||||
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
from app.models import Department, User
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
@@ -27,8 +29,43 @@ def serialize_department(dept: Department) -> dict:
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||||
return [serialize_department(d) for d in depts]
|
||||
rows = (
|
||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||
.outerjoin(User, User.department == Department.name)
|
||||
.group_by(Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
.all()
|
||||
)
|
||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
||||
|
||||
|
||||
def list_department_members(dept_id: int) -> dict:
|
||||
"""
|
||||
查询指定部门的员工名单。
|
||||
|
||||
[STEP 1] 通过部门主键读取部门名称。
|
||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||
return {
|
||||
'department': serialize_department(dept),
|
||||
'count': len(users),
|
||||
'members': [
|
||||
{
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
}
|
||||
for user in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
|
||||
依赖:models、wecom_notify.send_wecom_event_message。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
|
||||
依赖:models.PermissionRequest、integrations.wecom.notify.send_wecom_event_message、permission_roles.service。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。权限组启用后直接改应用会被拒绝。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,7 +19,15 @@ _BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
def serialize_permission_request(req: PermissionRequest) -> dict:
|
||||
"""PermissionRequest ORM → 管理端列表 JSON。"""
|
||||
"""
|
||||
把权限申请记录转成管理端列表 JSON。
|
||||
|
||||
核心逻辑:只输出申请主键、用户、应用、理由、状态和创建时间。
|
||||
Args:
|
||||
req: 已落库的 PermissionRequest。
|
||||
Returns:
|
||||
可供列表接口直接返回的字典。
|
||||
"""
|
||||
return {
|
||||
'id': req.id,
|
||||
'user_id': req.user_id,
|
||||
@@ -68,11 +76,11 @@ def _notify_batch_permission_update(user: User, agents: list[Agent], action: str
|
||||
def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新多用户的 Agent 权限(add / remove / set)。
|
||||
Returns:
|
||||
{ status, updated_count }。
|
||||
Raises:
|
||||
ValidationError: 未选择用户。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
action = data.get('action', 'add')
|
||||
@@ -95,11 +103,11 @@ def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
|
||||
Returns:
|
||||
{ status }。
|
||||
Raises:
|
||||
NotFoundError: 用户不存在。
|
||||
权限组启用后禁止按人改应用。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('Not found')
|
||||
@@ -123,9 +131,14 @@ def list_permission_requests() -> list[dict]:
|
||||
def approve_permission_request(request_id: int) -> dict:
|
||||
"""
|
||||
批准权限申请:更新状态并将 Agent 加入用户权限。
|
||||
权限组启用后禁止按人加应用,须改角色包或调整角色成员。
|
||||
Raises:
|
||||
NotFoundError: 申请不存在。
|
||||
ValidationError: 已启用角色包时禁止直接授权。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
req = db.session.get(PermissionRequest, request_id)
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,6 @@ from app.models import (
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
@@ -295,7 +294,11 @@ def _validate_movement_profile_binding(profile_id: Any) -> int | None:
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填。
|
||||
|
||||
DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认;
|
||||
不作为排程是否产出执行单元的门禁(一源一单元)。
|
||||
"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
@@ -309,14 +312,7 @@ def _validate_receipt_report_config(
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
|
||||
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
|
||||
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
|
||||
if len(warehouse_conditions) != 1 or not any(warehouse_values):
|
||||
raise ValidationError(
|
||||
'DBS receipt report requires exactly one Warehouse query condition with values',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
# Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
@@ -385,9 +381,7 @@ def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None:
|
||||
"""校验停用站点可直接采用的已发布方案与当前发货模板字段契约。"""
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before changing parsing profile', code='SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED')
|
||||
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
@@ -418,7 +412,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个停用库存站点原子绑定已发布解析方案并写入追加式审计。
|
||||
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
@@ -642,115 +636,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool:
|
||||
"""判断已确认的货代仓库是否已有精确映射或库存源默认映射。"""
|
||||
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
|
||||
warehouse = str(warehouse_id or '').strip().upper()
|
||||
if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None:
|
||||
return True
|
||||
return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None
|
||||
|
||||
|
||||
def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""复核测试连接证据并生成行级解析/调拨映射准备状态,不将后两者作为启用条件。"""
|
||||
missing: list[str] = []
|
||||
details: dict[str, Any] = {'sample_warehouses': []}
|
||||
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['completed', 'completed_empty']),
|
||||
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
|
||||
if (
|
||||
not confirmed_test
|
||||
or source.rpa_profile is None
|
||||
or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version
|
||||
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
|
||||
):
|
||||
return ['configuration_test'], details
|
||||
if confirmed_test.status == 'completed_empty':
|
||||
# 无库存时只能确认连接与查询成功;行级解析和调拨映射留待首个非空文件或实际调拨前验证。
|
||||
details['data_validation'] = 'pending_first_non_empty_export'
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'deferred_until_transfer'
|
||||
return missing, details
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
|
||||
profile = source.parsing_profile
|
||||
if analysis is None or profile is None:
|
||||
return ['configuration_test'], details
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
selected = next((item for item in candidates if isinstance(item, dict)
|
||||
and item.get('sheet_name') == definition.get('sheet_name')
|
||||
and item.get('header_row_index') == definition.get('header_row_index')), None)
|
||||
headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()]
|
||||
duplicate_headers = {
|
||||
str(item.get('header') or '').strip()
|
||||
for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and item.get('duplicate')
|
||||
}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
runtime_mapping, catalog = runtime_field_mapping(mapping)
|
||||
usages = usage_field_ids()
|
||||
mapped_ids = set(runtime_mapping)
|
||||
match_fields = mapped_ids & usages.get('match_identity', set())
|
||||
quantity_fields = mapped_ids & usages.get('inventory_quantity', set())
|
||||
required_fields = match_fields | quantity_fields
|
||||
if (
|
||||
not selected
|
||||
or not match_fields
|
||||
or len(quantity_fields) != 1
|
||||
or not required_fields <= set(runtime_mapping)
|
||||
or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields)
|
||||
or any(str(value or '').strip() in duplicate_headers for value in mapping.values())
|
||||
or not int((selected or {}).get('sample_row_count') or 0)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column_by_header = {
|
||||
str(item.get('header') or '').strip(): item
|
||||
for item in (selected or {}).get('columns', []) if isinstance(item, dict)
|
||||
}
|
||||
quantity_codes = quantity_fields
|
||||
quantity_column = next((
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in quantity_codes
|
||||
), {})
|
||||
identifier_columns = [
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in match_fields
|
||||
]
|
||||
if (
|
||||
quantity_column.get('inferred_type') != 'number'
|
||||
or any(not item.get('sample_values') for item in identifier_columns)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
if source.warehouse_resolution_mode == 'fixed':
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if _enabled_external_mapping_exists(source, source.fixed_warehouse_id) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
|
||||
if len(warehouse_codes) != 1:
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '')
|
||||
if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers:
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column = next((item for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {})
|
||||
sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()})
|
||||
details['sample_warehouses'] = sample_warehouses
|
||||
details['warehouse_identification'] = 'ready_for_transfer' if sample_warehouses else 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if sample_warehouses and all(
|
||||
_enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses
|
||||
) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
|
||||
|
||||
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
@@ -770,35 +655,11 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if run is None:
|
||||
return {'state': 'not_started'}
|
||||
profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None
|
||||
if (
|
||||
run.source_config_version != source.config_version
|
||||
or run.rpa_profile_config_version != profile_version
|
||||
):
|
||||
return {
|
||||
'state': 'stale', 'run_no': run.run_no, 'status': run.status,
|
||||
'source_config_version': run.source_config_version,
|
||||
'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
}
|
||||
if run.status == 'failed':
|
||||
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
if run.status == 'completed_empty':
|
||||
return {'state': 'empty', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
|
||||
|
||||
def _activation_check(
|
||||
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
|
||||
blocking: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造单项上线门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
return {
|
||||
'code': code,
|
||||
'status': status or ('passed' if passed else 'pending'),
|
||||
@@ -809,16 +670,15 @@ def _activation_check(
|
||||
|
||||
|
||||
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。"""
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing = set(validation_missing)
|
||||
test_evidence = _latest_test_run_evidence(source)
|
||||
test_complete = 'configuration_test' not in missing
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_valid = template_ready and 'template_validation' not in missing
|
||||
checks = [
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_activation_check(
|
||||
'rpa_profile', passed=profile_ready, action='configure_connection',
|
||||
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
|
||||
@@ -832,40 +692,14 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
|
||||
evidence={'template_id': source.excel_template_id, 'published': template_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'template_validation', passed=not template_ready or template_valid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid,
|
||||
),
|
||||
_activation_check(
|
||||
'configuration_test', passed=test_complete,
|
||||
action='run_configuration_test', evidence=test_evidence,
|
||||
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed', 'empty'} else None,
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_validation', passed=test_complete and not validation_details.get('parsing_validation'),
|
||||
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if validation_details.get('parsing_validation') else None, blocking=False,
|
||||
'template_validation', passed=not template_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
if source.warehouse_resolution_mode == 'inventory_match':
|
||||
checks.append(_activation_check(
|
||||
'warehouse_identification', passed=validation_details.get('warehouse_identification') == 'ready_for_transfer',
|
||||
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if validation_details.get('warehouse_identification') else None, blocking=False,
|
||||
))
|
||||
checks.append(_activation_check(
|
||||
'warehouse_mapping', passed=validation_details.get('warehouse_mapping') == 'ready_for_transfer', action='configure_warehouse_mapping',
|
||||
evidence={
|
||||
'mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'sample_warehouses': validation_details['sample_warehouses'],
|
||||
},
|
||||
status='pending' if validation_details.get('warehouse_mapping') else None, blocking=False,
|
||||
))
|
||||
return checks
|
||||
|
||||
|
||||
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""返回库存站点正式运行的结构化门禁结果。
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
Args:
|
||||
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
|
||||
@@ -883,25 +717,8 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A
|
||||
}
|
||||
|
||||
|
||||
def activate_source_if_ready(source: ShippingInventorySource, *, actor_id: int | None) -> bool:
|
||||
"""在测试回调后自动启用已满足全部正式运行条件的停用站点。
|
||||
|
||||
Args:
|
||||
source: 已完成当前版本测试的库存站点;调用方负责统一提交事务。
|
||||
actor_id: 发起测试的管理员标识,仅用于更新审计字段。
|
||||
|
||||
Returns:
|
||||
当本次将站点改为启用时返回 ``True``;条件未齐或已启用时返回 ``False``。
|
||||
"""
|
||||
if source.enabled or not get_source_activation_status(source)['ready']:
|
||||
return False
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
return True
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
|
||||
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
@@ -919,7 +736,7 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。"""
|
||||
"""停用库存站点,保留其解析方案和历史运行审计。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。
|
||||
逻辑:由 api/admin/users.py 调用。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +17,7 @@ from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.auth import casdoor_service
|
||||
from app.services.permission_roles import service as role_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
|
||||
|
||||
@@ -68,13 +69,16 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User) -> dict:
|
||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': names.get(user.role) or user.role,
|
||||
'is_platform_admin': user.is_platform_admin(),
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
@@ -137,7 +141,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
order_by = resolve_users_order_by(query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
names = role_service.list_role_name_map()
|
||||
return [serialize_admin_user(u, names) for u in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
@@ -162,8 +167,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
names = role_service.list_role_name_map()
|
||||
return {
|
||||
'items': [serialize_admin_user(u) for u in users],
|
||||
'items': [serialize_admin_user(u, names) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
@@ -194,21 +200,28 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
role_code = role_service.assert_role_assignable(
|
||||
data.get('role') or role_service.default_role_code(),
|
||||
allow_admin=True,
|
||||
)
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
department=empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
role=role_code,
|
||||
status=data.get('status', 'active'),
|
||||
real_name=empty_to_none(data.get('real_name')),
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
if not role_service.roles_configured():
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
if role_service.roles_configured():
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
elif data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
casdoor_service.sync_create_user(
|
||||
@@ -268,13 +281,21 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key == 'role':
|
||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if role_service.roles_configured():
|
||||
if 'role' in data:
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
else:
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if new_password and user.check_password(new_password):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_UNCHANGED',
|
||||
@@ -283,7 +304,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
)
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
if 'agent_ids' in data and not role_service.roles_configured():
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
@@ -301,6 +322,30 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新用户部门 / 角色 / 状态。改角色时同步权限包。
|
||||
"""
|
||||
if not user_ids:
|
||||
raise ValidationError('No users selected')
|
||||
payload = data if isinstance(data, dict) else {}
|
||||
next_role = None
|
||||
if payload.get('role'):
|
||||
next_role = role_service.assert_role_assignable(payload.get('role'), allow_admin=True)
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
for user in users:
|
||||
if 'department' in payload and payload.get('department') != '':
|
||||
user.department = empty_to_none(payload.get('department'))
|
||||
if 'status' in payload and payload.get('status') != '':
|
||||
user.status = payload.get('status')
|
||||
if next_role:
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
def cleanup_rejected_users() -> dict:
|
||||
rejected_ids = [row[0] for row in db.session.query(User.id).filter_by(status='rejected').all()]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
|
||||
@@ -48,7 +48,7 @@ class LoginResult:
|
||||
'username': self.user.username,
|
||||
'role': self.user.role,
|
||||
'default_agent_id': self.user.default_agent_id,
|
||||
'feature_permissions': self.user.get_feature_permissions(),
|
||||
**self.user.client_auth_fields(),
|
||||
'source': 'casdoor',
|
||||
'access_token': self.access_token,
|
||||
'refresh_token': self.refresh_token,
|
||||
|
||||
@@ -91,7 +91,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
普通知识问答、普通员工提问或其他 Agent 一律不命中。
|
||||
|
||||
Args:
|
||||
user: 当前聊天用户代理对象;需至少包含 role。
|
||||
user: 当前聊天用户;须能 has_feature_permission('training_hr_manage')。
|
||||
agent: 当前 Agent 代理对象;需能识别是否为员工培训 Agent。
|
||||
query: 用户原始问题。
|
||||
|
||||
@@ -100,7 +100,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
"""
|
||||
if not is_training_chat_agent(agent):
|
||||
return False
|
||||
if str(getattr(user, 'role', '') or '').strip() not in {'admin', 'hr'}:
|
||||
if not bool(getattr(user, 'has_feature_permission', None) and user.has_feature_permission('training_hr_manage')):
|
||||
return False
|
||||
return (
|
||||
_matches_any(query, _TRAINING_TOTAL_PATTERNS)
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
"""合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。"""
|
||||
"""
|
||||
services/contract_payment/schedule_seed.py
|
||||
|
||||
用途:合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:幂等创建;owner 优先平台管理员,否则任意用户。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
@@ -24,7 +31,7 @@ def ensure_default_contract_payment_schedules(*, commit: bool = True):
|
||||
Returns:
|
||||
新建的 ScheduleTask 列表;无用户时返回空列表。
|
||||
"""
|
||||
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user()
|
||||
if owner is None:
|
||||
return []
|
||||
created = []
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/file_assets/cleanup_schedule.py
|
||||
|
||||
用途:确保 platform Job file-asset-cleanup 存在默认 ScheduleTask(迁移补种 + 启动/建用户补建)。
|
||||
依赖:models.ScheduleTask/User、schedule.timezone_util.compute_next_run_at、SQLAlchemy Session 事件。
|
||||
依赖:models.ScheduleTask/User、permission_roles.service.first_schedule_owner_user、schedule.timezone_util、SQLAlchemy Session 事件。
|
||||
逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。
|
||||
"""
|
||||
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -60,14 +61,7 @@ def ensure_default_file_asset_cleanup_schedule(
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed file-asset-cleanup schedule: no users yet")
|
||||
return None
|
||||
|
||||
@@ -36,14 +36,17 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||
"""执行一次自动调拨排程。
|
||||
|
||||
核心逻辑:可选恢复 → 自动匹配 → 若 executable_count>0 则执行并写 run_no;
|
||||
空数据日(匹配后无可执行行)直接返回,不执行、不通知、不记 error(C5)。
|
||||
|
||||
Args:
|
||||
business_date: 业务日期。
|
||||
deps: 注入依赖。
|
||||
source_codes: 来源实例列表(缺省全部启用来源)。
|
||||
recover_history: 是否执行历史恢复。
|
||||
sender / recipients: 企微通知(None 则跳过通知)。
|
||||
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
||||
Returns:
|
||||
AutoTransferOutcome。
|
||||
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
|
||||
"""
|
||||
outcome = AutoTransferOutcome()
|
||||
if recover_history:
|
||||
@@ -57,10 +60,12 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
)
|
||||
# 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
|
||||
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役);
|
||||
# 无可执行行时门禁抛错,
|
||||
# 与旧流程一致记入 errors 不阻断通知阶段。
|
||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||
if summary.counts.executable_count == 0:
|
||||
return outcome
|
||||
# [STEP 3] 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
|
||||
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)。
|
||||
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
|
||||
outcome.run_no = executed.run_no
|
||||
outcome.run_status = executed.status
|
||||
|
||||
@@ -13,6 +13,9 @@ from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
|
||||
@@ -73,24 +76,35 @@ def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical
|
||||
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 _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
||||
"""批量取每行最近一次 Attempt 时间(单条 GROUP BY 聚合)。
|
||||
|
||||
【为什么批量】待处理池历史行持续累积,旧实现逐行 `_latest_attempt` 子查询
|
||||
在列表接口放大为 2N+1 条 SQL(age 判定一次、DTO 组装各一次),是
|
||||
backlog / backlog/summary 接口 4s+ 响应的根因(2026-09-29 修复);
|
||||
分组聚合后整池仅 1 条。
|
||||
|
||||
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))
|
||||
Args:
|
||||
item_ids: 池内明细 id 列表(空列表直接返回空表,不发查询)。
|
||||
Returns:
|
||||
{item_id: 最近 Attempt 的 created_at};无 Attempt 的行不在表中。
|
||||
"""
|
||||
if not item_ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at))
|
||||
.filter(TransferAttempt.item_id.in_(item_ids))
|
||||
.group_by(TransferAttempt.item_id)
|
||||
.all()
|
||||
)
|
||||
return {item_id: latest for item_id, latest in rows}
|
||||
|
||||
|
||||
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
|
||||
|
||||
排序:收料日期 → Invoice → 创建时间(业务稳定键,与重查/恢复等操作无关)。
|
||||
排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
|
||||
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
|
||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||
以此排序会让正在处理的行在列表中跳位。
|
||||
|
||||
@@ -110,15 +124,19 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
)
|
||||
if source_code:
|
||||
query = query.filter_by(source_code=source_code)
|
||||
output: list[BacklogItemDTO] = []
|
||||
for item in query.order_by(
|
||||
pool_rows = query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
).all():
|
||||
age = _item_age_days(item, current)
|
||||
latest = _latest_attempt(item)
|
||||
).all()
|
||||
latest_map = _latest_attempt_times([row.id for row in pool_rows])
|
||||
output: list[BacklogItemDTO] = []
|
||||
for item in pool_rows:
|
||||
latest = latest_map.get(item.id)
|
||||
base = latest if latest is not None else item.updated_at
|
||||
age = max(0, int((current - base).total_seconds() // 86400))
|
||||
if item.status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
level = AGING_UNKNOWN
|
||||
elif item.status == TransferStatus.MANUALLY_CLOSED.value:
|
||||
@@ -134,7 +152,7 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
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,
|
||||
last_attempt_at=latest.isoformat() if latest is not None else None,
|
||||
receipt_date=item.receipt_date,
|
||||
material_name=item.material_name,
|
||||
from_warehouse=item.from_warehouse,
|
||||
|
||||
@@ -74,7 +74,7 @@ class MatchingCountsDTO:
|
||||
# 文件已落地、尚未查 ERP 库存的待查行(status='matching' +
|
||||
# result_code='pending_stock_check',evidence_sync 落地态)。
|
||||
pending_stock_check_count: int = 0
|
||||
# blocked_file_removed 行数(文件新版本中消失,已出清,不进默认视图/明细)。
|
||||
# blocked_file_removed 行数(历史残留:存续语义上线前误标;不进默认视图/明细,修复脚本恢复后归零)。
|
||||
invalid_count: int = 0
|
||||
|
||||
|
||||
@@ -162,13 +162,16 @@ class ExternalDocumentDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferExceptionDTO:
|
||||
"""未生成 外部系统 单据的异常项(单独展示)。"""
|
||||
"""未生成 外部系统 单据的异常项(单独展示;仅收未建单被阻断的行)。"""
|
||||
|
||||
source_code: str
|
||||
invoice_no: str
|
||||
material_no: str
|
||||
reason: str
|
||||
facts: str
|
||||
# 行级人话原因(= 行 result_message,2026-09-29 契约扩充):前端展示优先于
|
||||
# reason 状态码标签(分组阻断时携带阻断单号等可行动信息),空则标签兜底。
|
||||
message: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""在途调拨业务日期与成熟度策略。
|
||||
|
||||
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
|
||||
昨天及更早可匹配,未来日期阻断)。
|
||||
依赖:标准库 zoneinfo / datetime。
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用,
|
||||
避免各服务各自计算导致口径漂移。
|
||||
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
|
||||
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
|
||||
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
|
||||
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
|
||||
复用,避免各服务各自计算导致口径漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,15 +20,29 @@ MATURITY_ELIGIBLE = "eligible"
|
||||
MATURITY_NOT_MATURED = "not_matured"
|
||||
MATURITY_FUTURE = "future"
|
||||
|
||||
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
|
||||
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
|
||||
DEFAULT_MATURITY_LAG_DAYS = 2
|
||||
|
||||
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
|
||||
_US_DATE_FORMATS = (
|
||||
"%m/%d/%Y %H:%M:%S",
|
||||
"%m/%d/%Y %H:%M",
|
||||
"%m/%d/%Y",
|
||||
)
|
||||
|
||||
|
||||
def parse_date(value: date | datetime | str) -> date:
|
||||
"""将 date/datetime 或日期字符串归一化为 date。
|
||||
|
||||
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
|
||||
均失败则 ValueError(fail-closed)。
|
||||
|
||||
Args:
|
||||
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
|
||||
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
|
||||
value: date/datetime 对象,或日期字符串(ISO 如 '2026-08-26 17:38:38';
|
||||
美式如 '08/13/2026 13:08:00')。
|
||||
Returns:
|
||||
归一化后的 date。
|
||||
归一化后的 date(忽略时分秒)。
|
||||
Raises:
|
||||
ValueError: 字符串不是可识别的日期/日期时间。
|
||||
"""
|
||||
@@ -42,8 +57,15 @@ def parse_date(value: date | datetime | str) -> date:
|
||||
pass
|
||||
try:
|
||||
return datetime.fromisoformat(text).date()
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid date value: {value!r}") from exc
|
||||
except ValueError:
|
||||
pass
|
||||
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
|
||||
for fmt in _US_DATE_FORMATS:
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(f"Invalid date value: {value!r}")
|
||||
|
||||
|
||||
def business_date_now(moment: datetime | None = None) -> date:
|
||||
@@ -85,31 +107,51 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
"""按 D+1 规则判定收料日期成熟度。
|
||||
def maturity_lag_days() -> int:
|
||||
"""读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。
|
||||
|
||||
Returns:
|
||||
成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值,
|
||||
保持策略函数可纯调用。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app
|
||||
return int(current_app.config.get(
|
||||
"IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS)
|
||||
except RuntimeError: # 无 app 上下文
|
||||
return DEFAULT_MATURITY_LAG_DAYS
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str,
|
||||
lag_days: int | None = None) -> str:
|
||||
"""按 T+lag 规则判定收料日期成熟度(默认 lag=2)。
|
||||
|
||||
Args:
|
||||
receipt_date: 收料日期。
|
||||
business_date: 当前业务日期 T。
|
||||
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
|
||||
Returns:
|
||||
'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或
|
||||
'future'(receipt_date > T,结构化阻断)。
|
||||
'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或
|
||||
'future'(receipt > T,结构化阻断)。
|
||||
"""
|
||||
receipt = parse_date(receipt_date)
|
||||
business = parse_date(business_date)
|
||||
if receipt == business:
|
||||
return MATURITY_NOT_MATURED
|
||||
lag = maturity_lag_days() if lag_days is None else int(lag_days)
|
||||
if receipt > business:
|
||||
return MATURITY_FUTURE
|
||||
if receipt > business - timedelta(days=lag):
|
||||
return MATURITY_NOT_MATURED
|
||||
return MATURITY_ELIGIBLE
|
||||
|
||||
|
||||
def eligible_receipt_date_to(business_date: date | str) -> date:
|
||||
"""返回可进入匹配的收料截止日期(业务日期 T - 1 天)。
|
||||
def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date:
|
||||
"""返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期。
|
||||
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
|
||||
Returns:
|
||||
T - 1 天。
|
||||
T - lag 天。
|
||||
"""
|
||||
return parse_date(business_date) - timedelta(days=1)
|
||||
lag = maturity_lag_days() if lag_days is None else int(lag_days)
|
||||
return parse_date(business_date) - timedelta(days=lag)
|
||||
@@ -29,6 +29,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
)
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
DEFAULT_INVENTORY_STALE_TTL_SECONDS,
|
||||
default_strategy,
|
||||
)
|
||||
|
||||
@@ -107,6 +108,18 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
_override = deps
|
||||
|
||||
|
||||
def _ttl_from_config(key: str, default: int) -> int:
|
||||
"""读取整型 TTL 配置(无应用上下文/非法值回落代码默认,下限 1 秒)。"""
|
||||
try:
|
||||
raw = current_app.config.get(key, default)
|
||||
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
|
||||
raw = default
|
||||
try:
|
||||
return max(1, int(raw))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _strategy_from_config():
|
||||
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
|
||||
|
||||
@@ -115,19 +128,18 @@ def _strategy_from_config():
|
||||
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
|
||||
|
||||
Returns:
|
||||
TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。
|
||||
TransferStrategyPolicy(confirm_ttl_seconds / inventory_stale_ttl_seconds
|
||||
=max(1, 配置值),禁令项沿用默认)。
|
||||
"""
|
||||
try:
|
||||
raw = current_app.config.get(
|
||||
return replace(
|
||||
default_strategy(),
|
||||
confirm_ttl_seconds=_ttl_from_config(
|
||||
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
)
|
||||
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
|
||||
raw = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
try:
|
||||
ttl = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
ttl = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl))
|
||||
),
|
||||
inventory_stale_ttl_seconds=_ttl_from_config(
|
||||
"IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS", DEFAULT_INVENTORY_STALE_TTL_SECONDS,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
|
||||
@@ -3,16 +3,22 @@
|
||||
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
|
||||
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
|
||||
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
|
||||
matching_service(_item_evaluated_sha 复用)/ models / audit。
|
||||
逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/
|
||||
contracts / models / audit。
|
||||
逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
|
||||
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
|
||||
查的,作废);消失标记行复现 → 无论证据变化与否无条件恢复待查(防复现行卡死
|
||||
隐藏);文件里消失 → blocked_file_removed 且换戳到最新 sha(保证对齐入口
|
||||
row_shas 收敛直通)。全程零外部调用(不查 ERP、不触发 RPA);终态行绝不触碰,
|
||||
终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件
|
||||
恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳
|
||||
到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行
|
||||
复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行
|
||||
绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
|
||||
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败
|
||||
标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback
|
||||
(保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID /
|
||||
ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,14 +30,20 @@ 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.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
|
||||
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError, parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_FILE_REMOVED,
|
||||
RouteNotResolvedError,
|
||||
_item_evaluated_sha,
|
||||
_latest_usable_report_file,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
clear_receipt_parse_failure,
|
||||
record_receipt_parse_failure,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
filter_invoices_for_type,
|
||||
@@ -61,20 +73,25 @@ class SyncOutcome:
|
||||
inserted: int = 0 # 文件有、本地无 → 插入待查行
|
||||
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
|
||||
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
|
||||
removed: int = 0 # 文件里消失 → blocked_file_removed
|
||||
absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28)
|
||||
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
|
||||
|
||||
|
||||
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
|
||||
|
||||
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
|
||||
(parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该
|
||||
文件已成功解析;无标记时为 no-op。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
deps: TransferDeps(只用 file_repository 与 route_resolver)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
|
||||
Returns:
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支
|
||||
不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
|
||||
"""
|
||||
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
|
||||
if ready is None:
|
||||
@@ -112,7 +129,7 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
).all()
|
||||
}
|
||||
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0}
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0}
|
||||
incoming_keys: set[tuple] = set()
|
||||
|
||||
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
|
||||
@@ -166,10 +183,10 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
))
|
||||
counters["inserted"] += 1
|
||||
continue
|
||||
# [Important② 复现行] 消失标记行(blocked_file_removed)重新出现在最新
|
||||
# 文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)已
|
||||
# 失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。
|
||||
# [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现
|
||||
# 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)
|
||||
# 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。
|
||||
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
|
||||
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
|
||||
# 据此收敛直通)。
|
||||
@@ -195,27 +212,32 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
row.result_code = SYNC_RESULT_PENDING
|
||||
row.result_message = None
|
||||
row.external_quantity = None # 旧库存对旧数量,作废待重查
|
||||
# [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前
|
||||
# external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。
|
||||
row.inventory_checked_at = None
|
||||
counters["reset_pending"] += 1
|
||||
else:
|
||||
counters["refreshed"] += 1
|
||||
# refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at
|
||||
#(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。
|
||||
row.updated_at = now
|
||||
|
||||
# [STEP 4] 文件里消失的非终态行 → blocked_file_removed(终态行不在 by_key,绝不触碰)。
|
||||
# [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA
|
||||
# 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message,
|
||||
# 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas
|
||||
# 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。
|
||||
# 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实
|
||||
# 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key,
|
||||
# 绝不触碰。
|
||||
for key, row in by_key.items():
|
||||
if key in incoming_keys:
|
||||
continue
|
||||
# [版本戳] 消失标记行同样换戳到最新文件 sha(保留原 sheet/row_no 行定位,
|
||||
# 只更新版本号与 sha):否则行版本戳停在旧文件,align 判据 row_shas 永不
|
||||
# 收敛为 {latest_sha},每次兜底都会空转重解析。
|
||||
row.raw_lines_json = [
|
||||
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
|
||||
for line in (row.raw_lines_json or [])
|
||||
]
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_FILE_REMOVED
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
row.updated_at = now
|
||||
counters["removed"] += 1
|
||||
counters["absent_kept"] += 1
|
||||
|
||||
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
|
||||
db.session.flush()
|
||||
@@ -229,10 +251,18 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
after={
|
||||
"file_sha256": outcome.file_sha256,
|
||||
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
|
||||
"reset_pending": outcome.reset_pending, "removed": outcome.removed,
|
||||
"reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept,
|
||||
"skipped": outcome.skipped,
|
||||
},
|
||||
))
|
||||
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
|
||||
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与
|
||||
# source_file_status 一致(_latest_usable_report_file);只 flush 不 commit,
|
||||
# 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake
|
||||
# 仓库测试场景/文件已清理)时为 no-op。
|
||||
report = _latest_usable_report_file(source_code)
|
||||
if report is not None and report.parse_failed_at is not None:
|
||||
clear_receipt_parse_failure(report=report)
|
||||
return outcome
|
||||
|
||||
|
||||
@@ -296,13 +326,16 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
|
||||
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
|
||||
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
|
||||
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
|
||||
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料单元行上的 source_code)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at)。
|
||||
Returns:
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志;
|
||||
schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
@@ -315,9 +348,9 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s",
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s",
|
||||
source_code, outcome.inserted, outcome.refreshed,
|
||||
outcome.reset_pending, outcome.removed, outcome.skipped)
|
||||
outcome.reset_pending, outcome.absent_kept, outcome.skipped)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
|
||||
@@ -325,6 +358,30 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
# [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径;
|
||||
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
|
||||
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
|
||||
# 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败
|
||||
# 事实),桥隔离语义保持,仍返回 False。
|
||||
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
|
||||
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
|
||||
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
|
||||
# B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。
|
||||
try:
|
||||
code = getattr(exc, "code", None) or ""
|
||||
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError):
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
report = _latest_usable_report_file(source_code)
|
||||
if report is not None:
|
||||
record_receipt_parse_failure(
|
||||
report=report,
|
||||
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
|
||||
error_message=str(detail)[:2000],
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志,仍返回 False
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -634,6 +634,9 @@ def _recheck_stock_for_document(
|
||||
material_no=item.material_no,
|
||||
warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no),
|
||||
)
|
||||
# [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的
|
||||
# external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。
|
||||
item.inventory_checked_at = datetime.utcnow()
|
||||
if row is None:
|
||||
# 查无账面:原位刷新最新事实(账面按 0 留痕)并移出本单。
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
@@ -1248,7 +1251,8 @@ def get_run(run_no: str) -> dict[str, Any]:
|
||||
"""按 run_no 恢复 Run 结果(result 单号聚合/异常 + orders 调拨单清单投影)。
|
||||
|
||||
orders 为 D9 融合卡数据源(调拨单清单=进度=结果),结构与行集口径见
|
||||
serialize_run_orders;result.exceptions 既有口径不变。
|
||||
serialize_run_orders;result.exceptions 仅收未建单阻断行(2026-09-29 收窄,
|
||||
已建单失败/未知行的原因与动作由 orders 卡片承载,不再重复进异常区)。
|
||||
"""
|
||||
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
@@ -1285,12 +1289,22 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
# T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。
|
||||
unit=str(item.unit or ""),
|
||||
))
|
||||
if result not in {"success", "duplicate_success"}:
|
||||
# [2026-09-29 口径收窄] exceptions 仅收「未落入任何调拨单」的阻断行
|
||||
# (如分组单冲突 group_order_unresolved):已建单的失败/未知行由 orders
|
||||
# 卡片展示行级原因与动作;关闭单脱离回 ready 的行(result=executable)
|
||||
# 回到待执行池,同样不算异常。Excel 异常下载(excel_export)仍走全量
|
||||
# 行集,审计口径不受本投影收窄影响。
|
||||
if (
|
||||
item.document_id is None
|
||||
and result not in {"success", "duplicate_success", RESULT_EXECUTABLE}
|
||||
):
|
||||
exceptions.append(TransferExceptionDTO(
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
reason=result,
|
||||
# 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。
|
||||
message=str(item.result_message or "").strip(),
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
))
|
||||
return RunResultDTO(
|
||||
@@ -1333,6 +1347,8 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
"invoice_no": exc.invoice_no,
|
||||
"material_no": exc.material_no,
|
||||
"reason": exc.reason,
|
||||
# 行级人话原因(2026-09-29):前端优先展示,状态码标签兜底。
|
||||
"message": exc.message,
|
||||
"facts": exc.facts,
|
||||
}
|
||||
for exc in result.exceptions
|
||||
@@ -1347,7 +1363,9 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
|
||||
(D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。
|
||||
|
||||
核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢),
|
||||
created_at/id 升序稳定排序;[STEP 2] 每单行集取自单挂接行(document_id →
|
||||
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 →
|
||||
拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现
|
||||
日期乱序);[STEP 2] 每单行集取自单挂接行(document_id →
|
||||
items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与
|
||||
_build_order_lines 同键同序)聚合:数量 Decimal 相加取 6 位小数字符串
|
||||
(D14 快照口径),unit/material_name 取组内首个非空原值。
|
||||
@@ -1358,16 +1376,24 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
|
||||
Returns:
|
||||
orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充):
|
||||
[{doc_no, receipt_date, from_warehouse, to_warehouse, status,
|
||||
erp_document_no, error_message, lines: [{material_no, material_name,
|
||||
lot_no, quantity(6 位小数字符串), unit, reason}]}]。
|
||||
erp_document_no, error_message, lines: [{invoice_no, material_no,
|
||||
material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。
|
||||
行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决):
|
||||
键恒出现——失败/未知行 = 组内首个非空行级 result_message,成功行/无原因为
|
||||
None(前端按「reason ?? 单 error_message」展示);ERP 写入行(
|
||||
_build_order_lines)不携带该键,投影层专属。
|
||||
"""
|
||||
# [2026-09-29 排序对齐] 仅投影层展示序,建单/执行顺序(组键序)不变。
|
||||
docs = (
|
||||
TransferDocument.query.filter_by(run_id=run.id)
|
||||
.order_by(TransferDocument.created_at.asc(), TransferDocument.id.asc())
|
||||
.order_by(
|
||||
TransferDocument.receipt_date.asc(),
|
||||
TransferDocument.source_code.asc(),
|
||||
TransferDocument.from_warehouse.asc(),
|
||||
TransferDocument.to_warehouse.asc(),
|
||||
TransferDocument.created_at.asc(),
|
||||
TransferDocument.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
# [Task 17 重构] 行聚合与 reason 契约统一收敛到 serializers.serialize_order
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨匹配服务。
|
||||
|
||||
用途:编排「证据兜底对齐 → 圈行 → D+1 成熟过滤 → 路由分组批量查 外部系统 库存 →
|
||||
用途:编排「证据兜底对齐 → 圈行 → T+lag 成熟过滤(默认 T+2)→ 路由分组批量查 外部系统 库存 →
|
||||
严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。
|
||||
依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/
|
||||
source_file_status / capability_client / date_policy / quantity / contracts /
|
||||
@@ -10,13 +10,18 @@
|
||||
匹配只读 DB 行并写库存侧字段(status/result_code/result_message/
|
||||
external_quantity/from_warehouse/to_warehouse/unit/updated_at),
|
||||
raw_lines 版本戳归 evidence_sync 所有,匹配不碰。来源实例独立处理,
|
||||
任一来源失败不阻断其他来源;当天收料不查询 外部系统;匹配 Hash 由冻结
|
||||
任一来源失败不阻断其他来源;【失败分层 2026-09-29】路由不可解析只落
|
||||
行级 blocked_route_not_resolved(来源保持 file_ready 不整源抬升),
|
||||
align 的 schema 类解析失败把失败事实落到来源可用文件(parse_failed
|
||||
三列,record_receipt_parse_failure),投影转 parse_failed 阻止下游当
|
||||
ready 使用;当天收料不查询 外部系统;匹配 Hash 由冻结
|
||||
快照复算;create_matching 只落 Run + SourceJob + Matching 留痕(行落位
|
||||
已由 run_matching 完成,行归属 matching_id 保持首次创建值不迁移);
|
||||
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
|
||||
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合,
|
||||
blocked_file_removed 行不进明细与常规 counts(只进 invalid_count);
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合;
|
||||
历史残留 blocked_file_removed(2026-09-28 起不再新产生)仅过滤进
|
||||
invalid_count,不进明细与常规 counts;
|
||||
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
|
||||
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
|
||||
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库
|
||||
@@ -35,10 +40,11 @@ from sqlalchemy import func, false, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.models import ShippingReceiptReportFile, TransferInvoiceItem, TransferMatching, 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 (
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
MatchingCountsDTO,
|
||||
MatchingItemDTO,
|
||||
MatchingSummaryDTO,
|
||||
@@ -60,7 +66,11 @@ from app.services.in_transit_transfer.file_preparation import (
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
record_receipt_parse_failure,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
@@ -83,14 +93,15 @@ RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。
|
||||
# 历史残留结果码(2026-09-28 前按"文件新版本缺失该行"自动标记;存续语义上线后不再新产生,仅作历史数据防御识别)。
|
||||
RESULT_FILE_REMOVED = "blocked_file_removed"
|
||||
# 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即
|
||||
# ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库
|
||||
# 已落列(可解释、可重查);blocked_ 前缀计入 blocked_count(既有 blocked_* 契约)。
|
||||
RESULT_MISSING_UNIT = "blocked_missing_unit"
|
||||
# 路由不可解析(2026-09-25 行级化):行落 blocked 可解释、可重查(路由配置修复后
|
||||
# 重跑匹配/重查即恢复);同时来源级 stage 仍标 failed(fail-closed 语义保留)。
|
||||
# 路由不可解析(2026-09-25 行级化;【2026-09-29 失败分层】取消来源级整源抬升):
|
||||
# 行落 blocked 可解释、可重查(路由配置修复后重跑匹配/重查即恢复);来源级
|
||||
# stage 保持 file_ready(有可用文件时),失败事实只落在行上。
|
||||
RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved"
|
||||
|
||||
# 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径):
|
||||
@@ -176,6 +187,36 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun
|
||||
return "success"
|
||||
|
||||
|
||||
def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None:
|
||||
"""返回某来源当前「可用」(当天抓取且未清理未过期)的收料归档文件,最新优先。
|
||||
|
||||
【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用
|
||||
文件上(parse_failed 三列)、或同步成功后清除其标记时调用——查询口径与
|
||||
source_file_status.resolve_source_file_status 的可用文件判定一致
|
||||
(receipt_file_gate.usable_receipt_file_condition),防止两处口径漂移。
|
||||
|
||||
核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run
|
||||
关联 ShippingReceiptRpaUnitRun.source_code)+ 可用门禁过滤;[STEP 2] 按
|
||||
created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料执行单元行上的 source_code)。
|
||||
Returns:
|
||||
最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/
|
||||
已清理)返回 None。
|
||||
"""
|
||||
return (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def run_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
@@ -192,7 +233,10 @@ def run_matching(
|
||||
【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥,
|
||||
主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组
|
||||
批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取
|
||||
并按准备结果标来源阶段。落库写入不在此 commit(随调用方事务:create_matching
|
||||
并按准备结果标来源阶段。【失败分层 2026-09-29】路由不可解析只落行级
|
||||
blocked_route_not_resolved(来源有可用文件时 stage 保持 file_ready,不再整源
|
||||
抬升 failed);align 的 schema 类解析失败额外把失败事实落到来源可用文件
|
||||
(parse_failed 三列)。落库写入不在此 commit(随调用方事务:create_matching
|
||||
末尾统一提交 / 异步 Job handler 回写后提交)。
|
||||
|
||||
Args:
|
||||
@@ -212,7 +256,7 @@ def run_matching(
|
||||
raise ValidationError("source_codes is required")
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出成熟规则(业务日期-lag,默认 T-2),起始不得晚于截止。
|
||||
range_from = parse_date(receipt_date_from) if receipt_date_from else None
|
||||
range_to = parse_date(receipt_date_to) if receipt_date_to else None
|
||||
if range_from and range_to and range_from > range_to:
|
||||
@@ -221,7 +265,7 @@ def run_matching(
|
||||
)
|
||||
if range_to and range_to > eligible_receipt_date_to(business_date):
|
||||
raise ValidationError(
|
||||
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
"receipt date range end exceeds receipt maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -250,6 +294,19 @@ def run_matching(
|
||||
for source_code in source_codes:
|
||||
if source_code in align_errors:
|
||||
error_code, error_message = align_errors[source_code]
|
||||
# [解析失败分层 2026-09-29] 仅 schema 类解析失败把失败事实落到该来源
|
||||
# 当前可用文件(parse_failed 三列,只 flush;随 create_matching 主事务
|
||||
# 统一提交)——来源状态投影随之转 parse_failed,阻止下游把坏文件当
|
||||
# ready 使用。TRANSFER.SOURCE_MATCH_ERROR 是通用匹配层错误(网络/依赖
|
||||
# 异常等),不代表文件解析失败,不落文件标记。
|
||||
if error_code == TRANSFER_FILE_SCHEMA_INVALID:
|
||||
report = _latest_usable_report_file(source_code)
|
||||
if report is not None:
|
||||
record_receipt_parse_failure(
|
||||
report=report,
|
||||
error_code=error_code,
|
||||
error_message=error_message[:2000],
|
||||
)
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=error_code, error_message=error_message,
|
||||
@@ -299,25 +356,15 @@ def run_matching(
|
||||
))
|
||||
pipeline_codes.append(source_code)
|
||||
|
||||
items, pending_stock_check_count, route_failed_sources = _matching_rows(
|
||||
# [失败分层 2026-09-29] _matching_rows 不再回传路由失败来源集合:路由不可
|
||||
# 解析只落行级 blocked_route_not_resolved(行可解释、可重查),来源级 stage
|
||||
# 保持 file_ready(有可用文件时),不再整源抬升 failed——顶栏匹配状态由行
|
||||
# blocked_count 呈现,来源错误码不再被路由问题污染。
|
||||
items, pending_stock_check_count = _matching_rows(
|
||||
source_codes=pipeline_codes, business_date=business_date, deps=deps,
|
||||
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
|
||||
file_snapshot=file_snapshot, now=now,
|
||||
)
|
||||
# [来源级 fail-closed] 路由不可解析的来源整源标 failed(行级已落
|
||||
# blocked_route_not_resolved,二者同源不同层:行可解释可重查,来源状态
|
||||
# 提示配置缺漏需人工处理)。
|
||||
for failed_code in route_failed_sources:
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=stage.source_code, stage="failed",
|
||||
file_no=stage.file_no, file_version=stage.file_version,
|
||||
checksum=stage.checksum,
|
||||
error_code=ROUTE_NOT_RESOLVED_CODE,
|
||||
error_message=f"route not resolved for source {stage.source_code}",
|
||||
) if stage.source_code == failed_code else stage
|
||||
for stage in sources
|
||||
]
|
||||
|
||||
# [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts,
|
||||
# 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。
|
||||
@@ -401,13 +448,15 @@ def _matching_rows(
|
||||
receipt_date_to: str | None,
|
||||
file_snapshot: dict[str, Any],
|
||||
now: datetime,
|
||||
) -> tuple[list[MatchingItemDTO], int, set[str]]:
|
||||
) -> tuple[list[MatchingItemDTO], int]:
|
||||
"""对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。
|
||||
|
||||
【2026-09-25】替代旧 _matching_invoices(按文件 Invoice 内存匹配):行已在
|
||||
DB(evidence_sync 落地),本函数只写库存侧字段(status/result_code/
|
||||
result_message/external_quantity/from_warehouse/to_warehouse/unit/
|
||||
updated_at);raw_lines 版本戳归 evidence_sync 所有,匹配不碰。
|
||||
【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_resolved,
|
||||
不再回传失败来源集合(run_matching 不再整源抬升 failed)。
|
||||
|
||||
Args:
|
||||
source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。
|
||||
@@ -417,9 +466,8 @@ def _matching_rows(
|
||||
file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。
|
||||
now: 落位时间(updated_at 新鲜度基准)。
|
||||
Returns:
|
||||
(items DTO 列表, pending_count, route_failed_sources)——pending_count=
|
||||
落位前的待查行数(counts 桶);route_failed_sources=路由不可解析的来源
|
||||
集合(run_matching 据此整源标 failed)。
|
||||
(items DTO 列表, pending_count)——pending_count=落位前的待查行数
|
||||
(counts 桶)。
|
||||
"""
|
||||
# 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
@@ -427,7 +475,7 @@ def _matching_rows(
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code.in_(source_codes),
|
||||
TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES),
|
||||
# 失效行(文件新版本消失)不参与匹配,也不进明细(invalid_count 单独计数)。
|
||||
# 失效行(历史残留 blocked_file_removed 行防御过滤)不参与匹配,也不进明细(invalid_count 单独计数)。
|
||||
or_(TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
)
|
||||
@@ -435,14 +483,19 @@ def _matching_rows(
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from))
|
||||
if receipt_date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to))
|
||||
# [统一排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与可调拨
|
||||
# 明细队列/待处理池同口径的业务稳定键(2026-09-29 统一),行不因重查/恢复跳位。
|
||||
scope_rows_all = query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc(),
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
).all()
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行
|
||||
# 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。
|
||||
pending_count = 0
|
||||
route_failed_sources: set[str] = set()
|
||||
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
|
||||
output: list[MatchingItemDTO] = []
|
||||
for row in scope_rows_all:
|
||||
@@ -454,10 +507,10 @@ def _matching_rows(
|
||||
if maturity == MATURITY_NOT_MATURED:
|
||||
row.status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
row.result_code = RESULT_NOT_MATURED
|
||||
row.result_message = "receipt not matured until next business day"
|
||||
row.result_message = f"receipt not matured before {eligible_receipt_date_to(business_date).isoformat()}"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
continue
|
||||
if maturity == MATURITY_FUTURE:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
@@ -465,7 +518,7 @@ def _matching_rows(
|
||||
row.result_message = "future receipt date"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
continue
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
@@ -473,15 +526,16 @@ def _matching_rows(
|
||||
warehouse_code=row.receipt_warehouse_code or "",
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
# [2026-09-25 行级化] 路由不可解析:行落 blocked(可解释、可重查),
|
||||
# 来源级 stage 由调用方标 failed;不炸整批(原「来源级中断」语义)。
|
||||
# [2026-09-25 行级化 / 2026-09-29 失败分层] 路由不可解析:行落
|
||||
# blocked(可解释、可重查);来源级 stage 保持 file_ready 不整源
|
||||
# 抬升(失败事实只在行上,匹配卡顶栏由 blocked_count 呈现);
|
||||
# 不炸整批(原「来源级中断」语义)。
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_ROUTE_NOT_RESOLVED
|
||||
row.result_message = f"route not resolved for source {row.source_code}"
|
||||
row.updated_at = now
|
||||
route_failed_sources.add(row.source_code)
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
continue
|
||||
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
|
||||
matured.append((row, route))
|
||||
@@ -512,7 +566,7 @@ def _matching_rows(
|
||||
row.result_message = "external query timeout"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
@@ -524,7 +578,7 @@ def _matching_rows(
|
||||
row.result_message = f"external query failed: {detail}"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
continue
|
||||
for row, route in entries:
|
||||
stock_row = stock.lookup_row(
|
||||
@@ -538,6 +592,8 @@ def _matching_rows(
|
||||
row.result_code = RESULT_INVENTORY_NOT_FOUND
|
||||
row.result_message = "external inventory not found"
|
||||
row.external_quantity = "0"
|
||||
# [库存查得时刻] 查无记录也是一次真实取数(按 0 落痕)。
|
||||
row.inventory_checked_at = now
|
||||
row.unit = ""
|
||||
else:
|
||||
stock_unit = (stock_row.stock_unit or "").strip()
|
||||
@@ -549,10 +605,12 @@ def _matching_rows(
|
||||
row.result_code = RESULT_MISSING_UNIT
|
||||
row.result_message = "external inventory unit is missing"
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.inventory_checked_at = now
|
||||
row.unit = ""
|
||||
else:
|
||||
match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity)
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.inventory_checked_at = now
|
||||
row.unit = stock_unit
|
||||
if match == RESULT_EXECUTABLE:
|
||||
row.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
@@ -564,8 +622,8 @@ def _matching_rows(
|
||||
row.result_message = "strict quantity mismatch"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
return output, pending_count, route_failed_sources
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
return output, pending_count
|
||||
|
||||
|
||||
def _generate_no(prefix: str, business_date: str) -> str:
|
||||
@@ -577,9 +635,10 @@ def _generate_no(prefix: str, business_date: str) -> str:
|
||||
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
"""读取行的文件版本戳(评估该行时所用的收料文件 checksum)。
|
||||
|
||||
用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items
|
||||
执行门禁②)据此判断"行的评估版本是否仍是最新文件版本"。
|
||||
两个消费方对 None(未知版本)口径不同:
|
||||
用途:文件对账(restore 展示 / execute_items 执行门禁②)据此判断
|
||||
"行的评估版本是否仍是最新文件版本"。2026-09-28 起不再用于
|
||||
消失行标记(blocked_file_removed 仅历史残留防御,匹配侧只过滤/
|
||||
invalid_count)。两个消费方对 None(未知版本)口径不同:
|
||||
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
|
||||
- execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
|
||||
@@ -610,9 +669,10 @@ def create_matching(
|
||||
|
||||
【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 +
|
||||
库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录
|
||||
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」
|
||||
——消失行标记(blocked_file_removed)归 evidence_sync;行归属 matching_id
|
||||
保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
|
||||
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」。
|
||||
【2026-09-28】evidence_sync 对缺席行改为存续只换戳,不再新产生
|
||||
blocked_file_removed(该码仅历史残留防御;匹配侧过滤/invalid_count);
|
||||
行归属 matching_id 保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -722,14 +782,14 @@ def restore_matching(
|
||||
|
||||
匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与
|
||||
匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行
|
||||
实时聚合;blocked_file_removed 行不进明细与常规 counts(只计入
|
||||
counts.invalid_count,2026-09-25);estimated_* 与 expires_at /
|
||||
实时聚合;历史残留 blocked_file_removed(2026-09-28 起不再新产生)不进
|
||||
明细与常规 counts(只计入 counts.invalid_count);estimated_* 与 expires_at /
|
||||
matching_hash 沿用匹配记录留痕展示。
|
||||
|
||||
Args:
|
||||
matching_id: 匹配编号(MTG-...)。
|
||||
deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore
|
||||
只读 strategy.confirm_ttl_seconds,不产生外部调用)。
|
||||
只读 strategy.inventory_stale_ttl_seconds,不产生外部调用)。
|
||||
now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。
|
||||
Returns:
|
||||
{"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰
|
||||
@@ -742,7 +802,7 @@ def restore_matching(
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds)
|
||||
|
||||
matching = db.session.query(TransferMatching).filter_by(
|
||||
matching_no=str(matching_id).strip()
|
||||
@@ -752,13 +812,22 @@ def restore_matching(
|
||||
|
||||
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
|
||||
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
|
||||
# [统一排序] 与可调拨明细队列/待处理池同口径(2026-09-29 统一),
|
||||
# 同一批行在匹配卡/可调拨明细/待处理池三处视图顺序一致。
|
||||
rows_all = (
|
||||
scope_item_query(matching)
|
||||
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
|
||||
.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
# [失效行分层]【2026-09-25】blocked_file_removed 行已出清:不进明细与常规
|
||||
# counts(与 _matching_rows 圈行口径一致),只计入 invalid_count。
|
||||
# [失效行分层]【2026-09-28】历史残留 blocked_file_removed(存续语义上线后
|
||||
# 不再新产生)防御过滤:不进明细与常规 counts(与 _matching_rows 圈行
|
||||
# 口径一致),只计入 invalid_count。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
|
||||
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
|
||||
@@ -874,7 +943,7 @@ def _item_dto(
|
||||
item: TransferInvoiceItem,
|
||||
latest: dict,
|
||||
moment: datetime,
|
||||
ttl_seconds: int,
|
||||
inventory_stale_ttl_seconds: int,
|
||||
) -> MatchingItemDTO:
|
||||
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
||||
|
||||
@@ -882,13 +951,13 @@ def _item_dto(
|
||||
item: 明细行。
|
||||
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
|
||||
moment: 新鲜度判定基准时间。
|
||||
ttl_seconds: 行级 stale 展示阈值(strategy.confirm_ttl_seconds;仅驱动
|
||||
stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
|
||||
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
||||
"""
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
updated_at = item.updated_at
|
||||
inventory_checked_at = item.inventory_checked_at
|
||||
return MatchingItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
@@ -919,15 +988,19 @@ def _item_dto(
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
# [行装饰] 行级新鲜度与文件对账(均纯展示,不阻断执行):
|
||||
# [行装饰] 库存时效与文件对账(均纯展示,不阻断执行):
|
||||
# [2026-09-25 TTL 退役] stale 仅是「库存数据已过期,请重查」展示徽标
|
||||
# (原 TTL 执行门禁已删除,防错由文件版本对账 + worker 写前库存复查
|
||||
# 承担):stale=距上次评估超过展示阈值(confirm_ttl_seconds);
|
||||
# 承担)。[2026-09-29 时钟换源] stale/checked_at 挂 inventory_checked_at
|
||||
# (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟
|
||||
# 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过
|
||||
# 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定;
|
||||
# file_current=行评估版本戳仍是该来源当前可用文件 sha
|
||||
# (无版本戳或无可用文件均视为不一致 → False)。
|
||||
item_id=item.id,
|
||||
checked_at=updated_at.isoformat() if updated_at else None,
|
||||
stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds,
|
||||
checked_at=inventory_checked_at.isoformat() if inventory_checked_at else None,
|
||||
stale=bool(inventory_checked_at)
|
||||
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
|
||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||
)
|
||||
|
||||
@@ -950,16 +1023,18 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds)
|
||||
|
||||
# [稳定排序] 收料日期(空值最后)→ Invoice → 创建时间:与重查/恢复等操作
|
||||
# 无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位。
|
||||
# [稳定排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复
|
||||
# 等操作无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位;
|
||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
|
||||
@@ -8,11 +8,13 @@
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。
|
||||
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
|
||||
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from io import BytesIO
|
||||
from typing import Any, Mapping
|
||||
|
||||
@@ -20,6 +22,20 @@ from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
|
||||
_HEADER_WS_RE = re.compile(r"\s+")
|
||||
|
||||
|
||||
def _normalize_header_label(value: Any) -> str:
|
||||
"""归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。
|
||||
|
||||
Args:
|
||||
value: 原始表头单元格或 field_mapping 别名。
|
||||
Returns:
|
||||
归一化后的字符串;空输入返回空串。
|
||||
"""
|
||||
return _HEADER_WS_RE.sub(" ", str(value or "").strip())
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
|
||||
@@ -89,9 +105,16 @@ def _extract_movement_rows(
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
|
||||
|
||||
核心逻辑:定位表头行 → 别名/表头归一化后建反查表 → 逐数据行映射领域字段 + 溯源。
|
||||
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
|
||||
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
|
||||
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
|
||||
|
||||
Args:
|
||||
data: xlsx 原始字节。
|
||||
field_mapping: 领域字段 → 表头别名(来自站点绑定的 movement profile)。
|
||||
sheet_name: 工作表名;空则取 active。
|
||||
header_row_index: 1-based 表头行;空则自动探测。
|
||||
"""
|
||||
from openpyxl import load_workbook
|
||||
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
|
||||
@@ -114,14 +137,17 @@ def _extract_movement_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]
|
||||
|
||||
# [STEP] 别名与表头均经 _normalize_header_label,抗 SSRS 单元格内换行。
|
||||
header_to_code: dict[str, list[str]] = {}
|
||||
for code, alias in field_mapping.items():
|
||||
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
|
||||
# 反查必须是 一别名→多字段,不得互相覆盖。
|
||||
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
|
||||
key = _normalize_header_label(alias)
|
||||
if not key:
|
||||
continue
|
||||
header_to_code.setdefault(key, []).append(str(code).strip())
|
||||
headers = [_normalize_header_label(c) for c in raw_rows[header_idx]]
|
||||
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
|
||||
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
|
||||
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
|
||||
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
|
||||
@@ -136,6 +162,7 @@ def _extract_movement_rows(
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
|
||||
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
|
||||
|
||||
headers / header_to_code 的键须已由 _normalize_header_label 归一化。
|
||||
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
|
||||
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
|
||||
"""
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
||||
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
|
||||
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
|
||||
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
|
||||
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
|
||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,9 +23,11 @@ RouteTriggerWriter = Callable[..., str | None]
|
||||
def _build_trigger_unit(
|
||||
*, source_code: str, business_date: str, reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
|
||||
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
|
||||
|
||||
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
@@ -35,22 +38,22 @@ def _build_trigger_unit(
|
||||
profile = source.rpa_profile
|
||||
if profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
|
||||
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
|
||||
query_parameters = [
|
||||
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
|
||||
]
|
||||
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': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'query_parameters_json': query_parameters,
|
||||
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return {
|
||||
'inventory_source_id': source.id,
|
||||
'callback_id': f'receipt:{uuid.uuid4().hex}',
|
||||
'source_code': source.source_code,
|
||||
'connector_type': source.connector_type,
|
||||
'warehouse_id': warehouse_id,
|
||||
'warehouse_id': None,
|
||||
'rpa_profile_id': profile.id,
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
'login_url': profile.login_url,
|
||||
@@ -60,13 +63,31 @@ def _build_trigger_unit(
|
||||
'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 []),
|
||||
'query_parameters_json': list(query_parameters),
|
||||
'config_snapshot': snapshot,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
}
|
||||
|
||||
|
||||
def list_receipt_capable_source_codes() -> list[str]:
|
||||
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
|
||||
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
rows = db.session.query(ShippingInventorySource.source_code).join(
|
||||
ShippingReceiptReportConfig,
|
||||
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
|
||||
return [str(code) for (code,) in rows]
|
||||
|
||||
|
||||
def trigger_receipt_rpa(
|
||||
*,
|
||||
source_code: str,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
依赖:models、retry_service._recheck_items_batch、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变;
|
||||
库存查询与人工重查共用按组织批量核心(一组一次外部调用,2026-09-29)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,7 +15,7 @@ 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.matching_service import TransferDeps
|
||||
from app.services.in_transit_transfer.retry_service import _recheck_item
|
||||
from app.services.in_transit_transfer.retry_service import _recheck_items_batch
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -45,6 +46,7 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
]),
|
||||
).all()
|
||||
eligible: list[TransferInvoiceItem] = []
|
||||
for item in items:
|
||||
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
# 只读隔离:不查询、不写入、不创建 Attempt。
|
||||
@@ -54,13 +56,19 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut
|
||||
# 永久排除。
|
||||
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
|
||||
eligible.append(item)
|
||||
# [按组织批量查询] 恢复与人工重查共用批量核心:每组织一次外部调用,行级
|
||||
# Attempt/审计/新鲜度语义与人工重查完全一致;路由解析失败行未建 Attempt、
|
||||
# 保持阻断原状(计入 still_blocked)。
|
||||
statuses, _row_errors = _recheck_items_batch(eligible, deps=deps, request_id=None)
|
||||
for item in eligible:
|
||||
if item.id in statuses:
|
||||
outcome.attempts_created += 1
|
||||
if statuses[item.id] == status_machine.TransferStatus.READY_TO_EXECUTE.value:
|
||||
outcome.recovered_count += 1
|
||||
else:
|
||||
outcome.still_blocked_count += 1
|
||||
else:
|
||||
outcome.still_blocked_count += 1
|
||||
if item.attempt_no > before_attempt:
|
||||
outcome.attempts_created += 1
|
||||
db.session.commit()
|
||||
return outcome
|
||||
@@ -7,9 +7,14 @@
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
|
||||
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
|
||||
库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经
|
||||
_recheck_items_batch——路由解析按 external_org 分组,一组一次
|
||||
capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt /
|
||||
审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用,
|
||||
禁止回退逐行单查(N 行 N 次调用会打崩外部系统);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
|
||||
单行入口由 retry_item 的 result_code 兜底拒绝(拒绝逻辑单点闭环,消失证据
|
||||
不可用旧库存翻回可执行);
|
||||
单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失
|
||||
证据不可用旧库存翻回可执行);
|
||||
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
|
||||
"""
|
||||
@@ -36,6 +41,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXECUTABLE,
|
||||
RESULT_FILE_REMOVED,
|
||||
RESULT_MISSING_UNIT,
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
scope_item_query,
|
||||
)
|
||||
@@ -56,86 +62,98 @@ _RETRYABLE_STATUSES = {
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
|
||||
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
|
||||
def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
|
||||
"""单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
Returns:
|
||||
重检后的 item 状态。
|
||||
通过门禁的行(本函数不触碰任何字段)。
|
||||
Raises:
|
||||
NotFoundError: item 不存在。
|
||||
ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行
|
||||
不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失,
|
||||
重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 /
|
||||
等重新同步恢复该行)。
|
||||
"""
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
# [口径] 重查按当前路由配置发查询,行上仓库字段同步刷新为本次解析值——
|
||||
# 查询与后续执行写路径必须用同一仓库值:行上旧值可能来自更早配置(路由
|
||||
# 已漂移),也可能为空(如 blocked_missing_unit 行在路由解析前被阻断)。
|
||||
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
|
||||
item.from_warehouse = route.from_warehouse
|
||||
item.to_warehouse = route.to_warehouse
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
item.attempt_no += 1
|
||||
before_status = item.status
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
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 _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
|
||||
# 谓词排除失效行,但按 id 直取(requery_items_by_ids)与单行入口绕过该谓词
|
||||
# ——拒绝逻辑只落在此单点,三条入口同时闭环。
|
||||
if item.result_code == RESULT_FILE_REMOVED:
|
||||
raise ValidationError(
|
||||
"removed rows cannot be requeried; close manually or wait for re-sync",
|
||||
code="TRANSFER.RETRY_NOT_ALLOWED",
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt,
|
||||
before_status: str, detail: str,
|
||||
operation_id: str, request_id: str | None) -> str:
|
||||
"""行级降级收口:外部查询故障 → blocked_external_query_failed + 原因。
|
||||
|
||||
与单行历史语义一致:网关/绑定故障不向调用方抛基础设施异常(避免全局错误
|
||||
弹窗);本次失败也是一次真实评估,行级 TTL 照常续期。
|
||||
|
||||
Args:
|
||||
item: 重查行(Attempt 已创建并 flush)。
|
||||
attempt: 该行本次 external_query Attempt(running 态)。
|
||||
before_status: 重查前状态(审计 before)。
|
||||
detail: 外部异常摘要(落 result_message 与审计)。
|
||||
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
|
||||
Returns:
|
||||
降级后的行状态。
|
||||
"""
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_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="failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
|
||||
))
|
||||
db.session.flush()
|
||||
# [降级] 与 matching 逐单语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)],
|
||||
)
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)
|
||||
stock_qty = stock_row.quantity if stock_row is not None else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
logger.warning(
|
||||
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
|
||||
item.invoice_no, item.id, item.attempt_no, detail,
|
||||
)
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_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="failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
|
||||
))
|
||||
db.session.flush()
|
||||
return item.status
|
||||
return item.status
|
||||
|
||||
|
||||
def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt,
|
||||
before_status: str, receipt_qty: Decimal, stock_row,
|
||||
operation_id: str, request_id: str | None) -> str:
|
||||
"""行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。
|
||||
|
||||
Args:
|
||||
item: 重查行(Attempt 已创建并 flush)。
|
||||
attempt: 该行本次 external_query Attempt(running 态)。
|
||||
before_status: 重查前状态(审计 before)。
|
||||
receipt_qty: 行收料数量(严格相等判定的基准)。
|
||||
stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。
|
||||
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
|
||||
Returns:
|
||||
重查后的行状态。
|
||||
"""
|
||||
stock_qty = stock_row.quantity if stock_row is not None else None
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
@@ -162,8 +180,12 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
item.unit = (stock_row.stock_unit or "").strip()
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
# [库存查得时刻] 重查是真实取数:三个分支(查无按 0/单位缺失/正常)落定的
|
||||
# external_quantity 都以本次取数为准,同步刷新其取数时间戳——stale 徽标
|
||||
# 判定时钟(2026-09-29 起挂本字段,不再依赖 updated_at,见 _item_dto)。
|
||||
item.inventory_checked_at = datetime.utcnow()
|
||||
# [行级新鲜度续期] 重查显式刷新 updated_at(行新鲜度口径),不依赖
|
||||
# attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
@@ -184,9 +206,133 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
return item.status
|
||||
|
||||
|
||||
def _recheck_items_batch(
|
||||
items: list[TransferInvoiceItem], *, deps: TransferDeps, request_id: str | None = None,
|
||||
) -> tuple[dict[int, str], dict[int, Exception]]:
|
||||
"""按组织批量重查核心:一组(external_org)一次 capabilities.query_stock。
|
||||
|
||||
【AI 触发时机】:全部重查/恢复/单据重试入口(retry_item / requery_items /
|
||||
requery_items_by_ids / retry_document / run_daily_recovery)圈定行集并过完
|
||||
资格门禁后统一调用;本函数不再校验状态与 file_removed。
|
||||
|
||||
【为什么按组织批量】重查面向整批行(可调拨清单「重查选中」可达数百行),
|
||||
逐行单查会把 N 行放大成 N 次外部调用,外部系统不可承受;外部访问按
|
||||
(料号, 仓库, 批号) 元组天然支持批量,执行链写前复查已按组织批量——本函数
|
||||
与其同形态。行级粒度保留:评估/Attempt/审计/新鲜度续期仍逐行落库,
|
||||
单行路由解析失败只跳过该行。
|
||||
|
||||
Args:
|
||||
items: 已过资格门禁的可重查行。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
request_id: 审计上下文。
|
||||
Returns:
|
||||
(statuses, row_errors):
|
||||
statuses = {item_id: 重查后状态}(进入查询的行,含降级为 blocked 的行);
|
||||
row_errors = {item_id: 原始异常}(路由/数量前置解析失败行:未发起查询、
|
||||
行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛
|
||||
保持历史 fail-closed 行为)。
|
||||
"""
|
||||
# [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位
|
||||
# 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须
|
||||
# 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如
|
||||
# blocked_missing_unit 行在路由解析前被阻断)。
|
||||
resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = []
|
||||
row_errors: dict[int, Exception] = {}
|
||||
for item in items:
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
|
||||
row_errors[item.id] = exc
|
||||
logger.warning(
|
||||
"transfer recheck row skipped (pre-resolve failed): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
continue
|
||||
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
|
||||
item.from_warehouse = route.from_warehouse
|
||||
item.to_warehouse = route.to_warehouse
|
||||
resolved.append((item, route, receipt_qty))
|
||||
|
||||
# [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享
|
||||
# 一次批量查询,N 行 = 每组织 1 次外部调用。
|
||||
groups: dict[str, list[tuple[TransferInvoiceItem, RouteMapping, Decimal]]] = {}
|
||||
for entry in resolved:
|
||||
groups.setdefault(str(entry[1].external_org or "").strip(), []).append(entry)
|
||||
|
||||
statuses: dict[int, str] = {}
|
||||
# [STEP 3] 每组织:行级 Attempt(running)→ 一次批量查询 → 行级收口(评估或
|
||||
# 降级)→ 组粒度提交(一组落库即一组持久,后续组故障不回滚已落组)。组内
|
||||
# Attempt 共享查询 operation_id,与 IntegrationCall 调用审计可互查。
|
||||
for external_org, entries in groups.items():
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
attempts: dict[int, TransferAttempt] = {}
|
||||
before_statuses: dict[int, str] = {}
|
||||
for item, route, receipt_qty in entries:
|
||||
item.attempt_no += 1
|
||||
before_statuses[item.id] = item.status
|
||||
attempts[item.id] = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "external_org": external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempts[item.id])
|
||||
db.session.flush()
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
) for item, route, _receipt_qty in entries],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为
|
||||
# blocked_external_query_failed + 原因(逐行查询时同样会全部失败,
|
||||
# 语义一致只是不再慢速放大),不中断批次、不向调用方抛异常。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
logger.warning(
|
||||
"transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s",
|
||||
external_org, len(entries), detail,
|
||||
)
|
||||
for item, route, receipt_qty in entries:
|
||||
statuses[item.id] = _degrade_recheck_row(
|
||||
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
|
||||
detail=detail, operation_id=operation_id, request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
continue
|
||||
for item, route, receipt_qty in entries:
|
||||
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)
|
||||
statuses[item.id] = _apply_recheck_outcome(
|
||||
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
|
||||
receipt_qty=receipt_qty, stock_row=stock_row,
|
||||
operation_id=operation_id, request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return statuses, row_errors
|
||||
|
||||
|
||||
def _row_error_text(exc: Exception) -> str:
|
||||
"""行级异常 → 用户可见错误文本(AppError 取 message,其余取 str/类名)。"""
|
||||
return str(getattr(exc, "message", "") or "").strip() or str(exc).strip() or exc.__class__.__name__
|
||||
|
||||
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""人工重试异常项。
|
||||
"""人工重试异常项(单行入口:资格门禁 + 按组织批量核心的单行特例)。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
@@ -197,37 +343,20 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
Raises:
|
||||
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读 /
|
||||
file_removed 行不可重查(消失证据不可恢复:证据行的源单已从最新
|
||||
收料文件中消失,重查只会用外部系统旧库存把行翻回可执行,唯一出口
|
||||
= 人工关闭 / 等重新同步恢复)。
|
||||
file_removed 行不可重查(资格门禁,见 _gate_retryable_item)。
|
||||
NotFoundError: item 不存在。
|
||||
Exception: 路由/数量前置解析失败原样上抛(fail-closed,保持单行历史行为)。
|
||||
"""
|
||||
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_EXTERNAL_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 _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
|
||||
# 谓词排除失效行,但按 id 直取(requery_items_by_ids 循环)与单行入口都绕过
|
||||
# 该谓词——拒绝逻辑只落在此单点,三条入口同时闭环。为什么拒绝:消失证据
|
||||
# 不可恢复,重查会用外部系统旧库存把行翻回可执行(虚假放行),唯一出口
|
||||
# = 人工关闭 / 等重新同步恢复该行。
|
||||
if item.result_code == RESULT_FILE_REMOVED:
|
||||
raise ValidationError(
|
||||
"removed rows cannot be requeried; close manually or wait for re-sync",
|
||||
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}
|
||||
item = _gate_retryable_item(item_id)
|
||||
statuses, row_errors = _recheck_items_batch([item], deps=deps, request_id=request_id)
|
||||
if item.id in row_errors:
|
||||
raise row_errors[item.id]
|
||||
return {"item_id": item.id, "status": statuses[item.id], "attempt_no": item.attempt_no}
|
||||
|
||||
|
||||
def requery_items_by_ids(
|
||||
@@ -237,8 +366,8 @@ def requery_items_by_ids(
|
||||
"""按明细 id 批量重查外部系统库存(待处理池批量「重查」入口)。
|
||||
|
||||
与 requery_items(匹配号定位)的差异:待处理池的行可能分散在多份历史
|
||||
匹配,只能按 id 直取。单行失败(状态不允许/不存在/异常)不影响其余行,
|
||||
隔离语义与 requery_items 一致。
|
||||
匹配,只能按 id 直取。单行门禁失败(状态不允许/不存在/file_removed)不
|
||||
影响其余行;库存查询按组织批量(每组织一次外部调用)。
|
||||
|
||||
Args:
|
||||
item_ids: TransferInvoiceItem.id 列表(非空)。
|
||||
@@ -263,29 +392,28 @@ def requery_items_by_ids(
|
||||
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
results: list[dict] = []
|
||||
results_by_id: dict[int, dict] = {}
|
||||
eligible: list[TransferInvoiceItem] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
retry_item(item_id=item_id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
results.append({"item_id": item_id, "invoice_no": item.invoice_no if item else "",
|
||||
"ok": True, "status": item.status if item else ""})
|
||||
eligible.append(_gate_retryable_item(item_id))
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
|
||||
logger.warning(
|
||||
"transfer batch requery row crashed (skipped): item=%s error=%s",
|
||||
item_id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"total": len(ids), "results": results}
|
||||
results_by_id[item_id] = {"item_id": item_id, "invoice_no": "",
|
||||
"ok": False, "error": exc.message}
|
||||
statuses, row_errors = _recheck_items_batch(eligible, deps=deps, request_id=request_id)
|
||||
for item in eligible:
|
||||
if item.id in row_errors:
|
||||
results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no,
|
||||
"ok": False, "error": _row_error_text(row_errors[item.id])}
|
||||
else:
|
||||
results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no,
|
||||
"ok": True, "status": statuses[item.id]}
|
||||
return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]}
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行逐单重查并刷新。
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。
|
||||
|
||||
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
|
||||
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
|
||||
@@ -299,7 +427,7 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
|
||||
单行门禁/路由失败不影响其余行(来源级隔离同款语义)。
|
||||
"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
@@ -333,25 +461,17 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
|
||||
items = query.order_by(TransferInvoiceItem.id).all()
|
||||
|
||||
# [按组织批量查询] 圈定行集一次性交批量核心:每组织一次外部调用;
|
||||
# 行级结果按输入行序(id 序)回报。
|
||||
statuses, row_errors = _recheck_items_batch(items, deps=deps, request_id=request_id)
|
||||
results: list[dict] = []
|
||||
for item in items:
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
if item.id in row_errors:
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": True, "status": item.status})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
"ok": False, "error": _row_error_text(row_errors[item.id])})
|
||||
else:
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
|
||||
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
|
||||
logger.warning(
|
||||
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
"ok": True, "status": statuses[item.id]})
|
||||
return {"matching_no": matching_no, "total": len(items), "results": results}
|
||||
|
||||
|
||||
@@ -359,7 +479,7 @@ def retry_document(
|
||||
*, doc_no: str, deps: TransferDeps,
|
||||
actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 逐行重查 → 全 ready 自动重跑。
|
||||
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 按组织批量重查 → 全 ready 自动重跑。
|
||||
|
||||
【AI 触发时机】:用户在失败调拨单上点「重试」——替代旧的单据级重查(其按
|
||||
可执行池关联行,对 blocked 行必报"未能关联");本函数按单圈行(单是行权威
|
||||
@@ -367,10 +487,11 @@ def retry_document(
|
||||
|
||||
核心逻辑:[STEP 1] 状态门禁——仅 failed 族(business/technical_failed)可重试;
|
||||
result_unknown 唯一出口=重新触发(D11),pending/executing 在飞拒绝,终态拒绝。
|
||||
[STEP 2] 单内 blocked 行逐行重查(复用 retry_item:单行隔离、file_removed 拒绝、
|
||||
每行落 Attempt);ready 行原样保留。 [STEP 3] 全部行 ready → 自动建新 Run 重跑
|
||||
(prepare_execution:门禁②文件对账 + D7①分支②复用原单号,写前复查兜底);
|
||||
任一行仍阻断 → 不重跑(单是原子单位,缺行不跑),阻断明细原样返回由池子兜底。
|
||||
[STEP 2] 单内 blocked 行批量重查(按组织一次外部查询;file_removed 行不可
|
||||
重查、保持阻断——消失证据不可恢复,拒绝语义同资格门禁);ready 行原样保留。
|
||||
[STEP 3] 全部行 ready → 自动建新 Run 重跑(prepare_execution:门禁②文件对账
|
||||
+ D7①分支②复用原单号,写前复查兜底);任一行仍阻断 → 不重跑(单是原子单位,
|
||||
缺行不跑),阻断明细原样返回由池子兜底。
|
||||
|
||||
Args:
|
||||
doc_no: TransferDocument.doc_no。
|
||||
@@ -404,16 +525,15 @@ def retry_document(
|
||||
"document has no attached items", code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 2] 单内 blocked 行逐行重查(行级隔离,单行失败不炸整单)。
|
||||
for item in items:
|
||||
if item.status != status_machine.TransferStatus.BLOCKED_RECOVERABLE.value:
|
||||
continue
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
except (ValidationError, NotFoundError):
|
||||
# file_removed 等拒绝语义:行保持阻断,原因随结果返回。
|
||||
continue
|
||||
# [STEP 2] 单内 blocked 行批量重查(按组织一次外部查询,行级隔离语义不变;
|
||||
# file_removed 行直接排除——消失证据不可恢复,保持阻断原样)。
|
||||
eligible = [
|
||||
item for item in items
|
||||
if item.status == status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
and item.result_code != RESULT_FILE_REMOVED
|
||||
]
|
||||
if eligible:
|
||||
_recheck_items_batch(eligible, deps=deps, request_id=request_id)
|
||||
|
||||
for item in items:
|
||||
db.session.expire(item)
|
||||
|
||||
@@ -124,7 +124,8 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
|
||||
核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量
|
||||
Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个
|
||||
非空原值;[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
|
||||
非空原值,行级 invoice_no 随 ERP 写入行同款口径透传(2026-09-29 契约扩充);
|
||||
[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
|
||||
首个非空行级 result_message,成功行/无原因为 None(前端按
|
||||
「reason ?? 单 error_message」展示)。
|
||||
|
||||
@@ -170,6 +171,9 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
"error_message": doc.error_message,
|
||||
"lines": [
|
||||
{
|
||||
# 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||
"invoice_no": line["invoice_no"],
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
@@ -217,10 +221,14 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"invoice_no": item.invoice_no,
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||
# deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。
|
||||
"lot_no": item.lot_no or "",
|
||||
"quantity": item.receipt_quantity,
|
||||
"unit": item.unit or "",
|
||||
}
|
||||
for item in sorted(items, key=lambda row: row.id)
|
||||
# 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同
|
||||
# (组键含两者),按 invoice_no 升序、id 兜底稳定排序。
|
||||
for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id))
|
||||
],
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
"""在途调拨来源收料文件状态投影服务。
|
||||
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
|
||||
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
|
||||
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
|
||||
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
|
||||
有进行中单元 → fetching;最新单元为失败终态 → failed;
|
||||
文件仍在但已失效 → expired;否则 → none。
|
||||
record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列
|
||||
(写入与清除均只 flush 不 commit,事务归属调用方)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
@@ -30,7 +37,9 @@ 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', 'expired', 'none'}。
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
|
||||
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
||||
仍带 file_no/file_sha256 便于诊断与前端提示。
|
||||
"""
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
@@ -43,6 +52,15 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
.first()
|
||||
)
|
||||
if report is not None:
|
||||
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
|
||||
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
|
||||
if report.parse_failed_at is not None:
|
||||
return {
|
||||
'file_status': 'parse_failed',
|
||||
'has_ready_file': False,
|
||||
'file_no': report.original_filename or str(report.id),
|
||||
'file_sha256': report.sha256,
|
||||
}
|
||||
return {
|
||||
'file_status': 'ready',
|
||||
'has_ready_file': True,
|
||||
@@ -83,3 +101,55 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
|
||||
def record_receipt_parse_failure(
|
||||
*,
|
||||
report: ShippingReceiptReportFile,
|
||||
error_code: str,
|
||||
error_message: str,
|
||||
now: datetime | None = None,
|
||||
) -> None:
|
||||
"""标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
|
||||
|
||||
【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
|
||||
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
|
||||
改调 clear_receipt_parse_failure。
|
||||
|
||||
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
|
||||
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
|
||||
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
|
||||
|
||||
Args:
|
||||
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
|
||||
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
|
||||
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
|
||||
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
|
||||
Returns:
|
||||
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
|
||||
"""
|
||||
report.parse_failed_at = now or datetime.utcnow()
|
||||
report.parse_error_code = (error_code or '')[:64]
|
||||
report.parse_error_message = (error_message or '')[:2000]
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None:
|
||||
"""清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
|
||||
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
|
||||
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
|
||||
|
||||
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
|
||||
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
|
||||
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
|
||||
|
||||
Args:
|
||||
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
|
||||
Returns:
|
||||
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
|
||||
"""
|
||||
report.parse_failed_at = None
|
||||
report.parse_error_code = None
|
||||
report.parse_error_message = None
|
||||
db.session.flush()
|
||||
@@ -1,8 +1,10 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试;
|
||||
confirm_ttl_seconds 为纯展示阈值(默认 10 分钟 stale 徽标判定窗口,
|
||||
不再作为执行门禁——2026-09-25 退役)。
|
||||
confirm_ttl_seconds 与 inventory_stale_ttl_seconds 均为纯展示阈值
|
||||
(stale 徽标判定窗口,不再作为执行门禁——2026-09-25 退役);
|
||||
2026-09-29 起 stale 时钟换源:挂 inventory_checked_at(库存查得
|
||||
时刻),阈值默认 24 小时——证据同步换戳不续期该时钟。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
阻止发布/执行(fail-closed)。
|
||||
@@ -17,6 +19,7 @@ from app.core.errors import AppError
|
||||
|
||||
STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION"
|
||||
DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟
|
||||
DEFAULT_INVENTORY_STALE_TTL_SECONDS = 86400 # 24 小时
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -30,6 +33,10 @@ class TransferStrategyPolicy:
|
||||
# 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前
|
||||
# 库存复查承担(见 execution_service)。
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
# 纯展示阈值:stale 徽标判定窗口,时钟=inventory_checked_at(库存查得
|
||||
# 时刻,仅匹配评估/重查/写前复查写入;2026-09-29 起替换原 updated_at
|
||||
# 时钟——后者被证据同步换戳每日续期,徽标对老行永不触发)。
|
||||
inventory_stale_ttl_seconds: int = DEFAULT_INVENTORY_STALE_TTL_SECONDS
|
||||
|
||||
|
||||
class StrategyViolationError(AppError):
|
||||
@@ -61,5 +68,6 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
"""返回一期默认策略(全部禁令关闭,stale 展示阈值 600 秒)。"""
|
||||
"""返回一期默认策略(全部禁令关闭;stale 展示阈值:行新鲜度 600 秒 /
|
||||
库存查得时刻 24 小时)。"""
|
||||
return TransferStrategyPolicy()
|
||||
@@ -0,0 +1,97 @@
|
||||
"""在途调拨企微汇总通知的真实通道适配(notification.WeComSender 协议实现)。
|
||||
|
||||
用途:把自动调拨 Run 汇总经企微 textcard 发给通知人,替代排程 handler 的
|
||||
sender=None 占位;通知失败只落 run.notification_status,不影响 ERP 结果。
|
||||
依赖:integrations.wecom.notify.send_wecom_event_message(事件门禁+审计)、models.User。
|
||||
逻辑:逐收件人解析 wecom_userid 后发送;复用 schedule_completed 事件开关(与排程
|
||||
通用通知同一启停入口,不新增 WECOM_NOTIFY_EVENTS 事件名);至少一人送达即
|
||||
success,无可用收件人或全部失败为 failed,由 notify_run_summary 统一落库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
# 复用排程完成事件开关:运维通过 WECOM_NOTIFY_EVENTS 的 schedule_completed
|
||||
# 统一启停排程类通知,本发送器不引入独立事件名(避免各环境事件表漂移)。
|
||||
WECOM_EVENT_TYPE = "schedule_completed"
|
||||
|
||||
_STATUS_LABELS = {
|
||||
"success": "全部成功",
|
||||
"partial_failed": "部分失败",
|
||||
"failed": "失败",
|
||||
"matching": "匹配中",
|
||||
}
|
||||
|
||||
|
||||
class WecomSummarySender:
|
||||
"""企微汇总通知发送器(协议见 notification.WeComSender)。
|
||||
|
||||
Args 约定:recipients 为 HXOPS 用户 id 列表(字符串/整数均可),由排程参数
|
||||
notify_user_ids(options_source=users)下发;未绑定企微的用户跳过。
|
||||
excel_path 为协议占位,当前不发送附件(异常明细以管理端已执行区块为准)。
|
||||
"""
|
||||
|
||||
def send_summary(self, *, run_no: str, summary: dict[str, Any],
|
||||
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
|
||||
"""向通知人逐一发送一条 Run 汇总 textcard。
|
||||
|
||||
Args:
|
||||
run_no: 调拨 Run 编号(RUN-YYYYMMDD-XXXXXX)。
|
||||
summary: notify_run_summary 组装的汇总(run_no/status/business_date/counts)。
|
||||
recipients: 用户 id 列表。
|
||||
excel_path: 协议占位;当前不发送附件。
|
||||
Returns:
|
||||
{"status": "success", "delivered": n} 或
|
||||
{"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str};
|
||||
由 notify_run_summary 写入 run.notification_* 字段。
|
||||
"""
|
||||
counts = summary.get("counts") if isinstance(summary.get("counts"), dict) else {}
|
||||
status = str(summary.get("status") or "")
|
||||
title = f"在途自动调拨 {run_no}"
|
||||
content = "\n".join([
|
||||
f"状态: {_STATUS_LABELS.get(status, status or '未知')}",
|
||||
f"业务日期: {summary.get('business_date') or '-'}",
|
||||
"文件票数: {tickets} 已匹配: {matched} 待查库存: {pending}".format(
|
||||
tickets=counts.get("file_invoice_count", 0),
|
||||
matched=counts.get("matched_count", 0),
|
||||
pending=counts.get("pending_stock_check_count", 0),
|
||||
),
|
||||
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
|
||||
executable=counts.get("executable_count", 0),
|
||||
blocked=counts.get("blocked_count", 0),
|
||||
not_matured=counts.get("not_matured_count", 0),
|
||||
),
|
||||
])
|
||||
|
||||
user_ids = [int(item) for item in (recipients or []) if str(item).strip().isdigit()]
|
||||
users = []
|
||||
if user_ids:
|
||||
from app.models import User
|
||||
|
||||
users = User.query.filter(User.id.in_(user_ids)).all()
|
||||
|
||||
# [STEP 1] 逐收件人投递;send_wecom_event_message 内部完成事件门禁与审计落库。
|
||||
delivered = 0
|
||||
last_error = ""
|
||||
for user in users:
|
||||
if not user.wecom_userid:
|
||||
continue
|
||||
outcome = send_wecom_event_message(
|
||||
event_type=WECOM_EVENT_TYPE, user=user, title=title, content=content,
|
||||
jump_path="/workspace",
|
||||
)
|
||||
if outcome.get("ok"):
|
||||
delivered += 1
|
||||
else:
|
||||
last_error = str(outcome.get("reason") or "send_failed")
|
||||
|
||||
if delivered:
|
||||
return {"status": "success", "delivered": delivered}
|
||||
return {
|
||||
"status": "failed",
|
||||
"error_code": "WECOM_SEND_FAILED",
|
||||
"error_message": last_error or "no wecom-bound recipients",
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/lean_training_schedule_seed.py
|
||||
|
||||
用途:幂等创建精益培训默认排程(每日逾期提醒扫描 + 每周一 09:00 视频推送)。
|
||||
依赖:ScheduleTask、User、上海时区 next_run 计算。
|
||||
逻辑:应用启动时在存在管理员和排程表后创建两个默认任务,管理员可在排程中心停用或调整。
|
||||
依赖:ScheduleTask、permission_roles.service.first_platform_admin_user、上海时区 next_run 计算。
|
||||
逻辑:应用启动时在存在平台管理员和排程表后创建两个默认任务,管理员可在排程中心停用或调整。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,13 +11,14 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_platform_admin_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
def ensure_default_lean_training_schedule(*, commit: bool = True) -> list[ScheduleTask]:
|
||||
"""幂等创建精益培训默认排程:每日 09:00 提醒扫描 + 每周一 09:00 视频推送。"""
|
||||
owner = db.session.query(User).filter(User.role == "admin").order_by(User.id.asc()).first()
|
||||
owner = first_platform_admin_user()
|
||||
if not owner:
|
||||
return []
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
services/permission_roles/__init__.py
|
||||
|
||||
用途:可配置权限组服务包入口。
|
||||
依赖:catalog、service。
|
||||
逻辑:api/admin/permission_roles 与 user_service 按需 import service。
|
||||
"""
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
services/permission_roles/catalog.py
|
||||
|
||||
用途:角色包可勾选的应用内能力目录,以及按 Agent 属性匹配种子应用。
|
||||
依赖:Agent.handler_config.content_profile、agent_code。
|
||||
逻辑:角色编辑按已选 Agent 在应用卡片内展示能力;bind 支持 always / content_profile: / agent_code: / kind:;迁移种子用 match 规则给标准包勾入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 与 User.get_feature_permissions 输出键对齐。
|
||||
KNOWN_FEATURE_KEYS: tuple[str, ...] = (
|
||||
'training_hr_manage',
|
||||
'shipping_notice_force_create',
|
||||
'shipping_notice.audit_sensitive_read',
|
||||
'shipping_notice.xfa_split_rule_edit',
|
||||
'shipping_notice.xfa_split_rule_preview',
|
||||
'shipping_notice.xfa_split_rule_publish',
|
||||
'maintenance.ledger_write',
|
||||
)
|
||||
|
||||
FEATURE_CATALOG: tuple[dict[str, Any], ...] = (
|
||||
{
|
||||
'key': 'training_hr_manage',
|
||||
'bind': 'content_profile:training',
|
||||
'name': 'HR 管理',
|
||||
'hint': '查看统计、筛选记录并导出 Excel',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice_force_create',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '强制新建重复单据',
|
||||
'hint': '跳过重复拦截,新建发货通知',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.audit_sensitive_read',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '读取敏感审计',
|
||||
'hint': '查看 before / after / Diff 正文',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_edit',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '编辑 XFA 拆分规则',
|
||||
'hint': '维护字段拆分规则',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_preview',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '预览拆分',
|
||||
'hint': '预览拆分结果',
|
||||
},
|
||||
{
|
||||
'key': 'shipping_notice.xfa_split_rule_publish',
|
||||
'bind': 'agent_code:shipping_notice',
|
||||
'name': '发布拆分规则',
|
||||
'hint': '审核并发布规则',
|
||||
},
|
||||
{
|
||||
'key': 'maintenance.ledger_write',
|
||||
'bind': 'kind:maintenance',
|
||||
'name': '台账与维修维护',
|
||||
'hint': '维护设备台账与维修记录',
|
||||
},
|
||||
)
|
||||
|
||||
# 现网 users.role 枚举对应的标准权限组。admin/user/hr 为内置;rd/shipping 可后续增删应用。
|
||||
SYSTEM_ROLE_SEEDS: tuple[dict[str, Any], ...] = (
|
||||
{
|
||||
'code': 'user',
|
||||
'name': '普通用户',
|
||||
'description': '新建用户默认。勾通用入口即可使用企业知识库。',
|
||||
'is_default': True,
|
||||
'is_system': True,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 10,
|
||||
'features': {},
|
||||
'agent_match': ('entrance',),
|
||||
},
|
||||
{
|
||||
'code': 'rd',
|
||||
'name': '研发应用',
|
||||
'description': '通用入口,以及研发侧应用(如专利)。本地尚未接入的应用,之后勾进本组即可。',
|
||||
'is_default': False,
|
||||
'is_system': False,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 20,
|
||||
'features': {},
|
||||
'agent_match': ('entrance', 'patent'),
|
||||
},
|
||||
{
|
||||
'code': 'hr',
|
||||
'name': '培训 HR',
|
||||
'description': '可进员工培训,并打开 HR 管理。',
|
||||
'is_default': False,
|
||||
'is_system': True,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 30,
|
||||
'features': {'training_hr_manage': True},
|
||||
'agent_match': ('entrance', 'training'),
|
||||
},
|
||||
{
|
||||
'code': 'shipping',
|
||||
'name': '货代专员',
|
||||
'description': '聊天与工作台共用货代应用入口。',
|
||||
'is_default': False,
|
||||
'is_system': False,
|
||||
'is_platform_admin': False,
|
||||
'sort_order': 40,
|
||||
'features': {'shipping_notice_force_create': True},
|
||||
'agent_match': ('entrance', 'shipping'),
|
||||
},
|
||||
{
|
||||
'code': 'admin',
|
||||
'name': '管理员',
|
||||
'description': '内置角色。应用入口隐式全开,可进入 /admin。',
|
||||
'is_default': False,
|
||||
'is_system': True,
|
||||
'is_platform_admin': True,
|
||||
'sort_order': 90,
|
||||
'features': {key: True for key in KNOWN_FEATURE_KEYS},
|
||||
'agent_match': (),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def agent_content_profile(agent: Any) -> str:
|
||||
"""读取 Agent.handler_config.content_profile。"""
|
||||
raw = getattr(agent, 'handler_config', None)
|
||||
if not isinstance(raw, dict):
|
||||
return ''
|
||||
return str(raw.get('content_profile') or '').strip()
|
||||
|
||||
|
||||
def agent_matches_kind(agent: Any, kind: str) -> bool:
|
||||
"""
|
||||
判断 Agent 是否属于种子包中的一类入口。
|
||||
|
||||
kind: entrance / training / shipping / patent / maintenance
|
||||
"""
|
||||
code = str(getattr(agent, 'agent_code', '') or '').strip()
|
||||
name = str(getattr(agent, 'name', '') or '')
|
||||
profile = agent_content_profile(agent)
|
||||
if kind == 'entrance':
|
||||
return profile == 'generic_entrance'
|
||||
if kind == 'training':
|
||||
return profile == 'training'
|
||||
if kind == 'shipping':
|
||||
return code == 'shipping_notice'
|
||||
if kind == 'patent':
|
||||
return '专利' in name
|
||||
if kind == 'maintenance':
|
||||
return '维保' in name or '维修' in name or code == 'maintenance'
|
||||
return False
|
||||
|
||||
|
||||
def feature_visible_for_agents(feature: dict[str, Any], agents: list[Any]) -> bool:
|
||||
"""已选应用是否展示该应用内能力。"""
|
||||
bind = str(feature.get('bind') or '')
|
||||
if bind == 'always':
|
||||
return True
|
||||
if bind.startswith('content_profile:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(agent_content_profile(agent) == want for agent in agents)
|
||||
if bind.startswith('agent_code:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(str(getattr(agent, 'agent_code', '') or '') == want for agent in agents)
|
||||
if bind.startswith('kind:'):
|
||||
want = bind.split(':', 1)[1]
|
||||
return any(agent_matches_kind(agent, want) for agent in agents)
|
||||
return False
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
services/permission_roles/service.py
|
||||
|
||||
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
||||
依赖:PermissionRole、User、Agent、catalog。
|
||||
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
||||
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models.permission_role import PermissionRole
|
||||
from app.services.permission_roles.catalog import (
|
||||
FEATURE_CATALOG,
|
||||
KNOWN_FEATURE_KEYS,
|
||||
agent_matches_kind,
|
||||
feature_visible_for_agents,
|
||||
)
|
||||
|
||||
_ROLE_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,62}$')
|
||||
PLATFORM_ADMIN_CODE = 'admin'
|
||||
|
||||
|
||||
def roles_configured() -> bool:
|
||||
"""库中是否已有权限组;无则走历史按人授权。"""
|
||||
return db.session.query(PermissionRole.id).first() is not None
|
||||
|
||||
|
||||
def assert_direct_grants_allowed() -> None:
|
||||
"""权限组启用后禁止按人改应用授权,须改角色包或调整成员。"""
|
||||
if roles_configured():
|
||||
raise ValidationError(
|
||||
'Direct agent grants are disabled; assign a permission role instead',
|
||||
code='ROLE.DIRECT_GRANT_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
def get_role_by_code(code: str | None) -> PermissionRole | None:
|
||||
"""按 code 取权限组;不存在返回 None。"""
|
||||
value = str(code or '').strip()
|
||||
if not value:
|
||||
return None
|
||||
return db.session.query(PermissionRole).filter(PermissionRole.code == value).one_or_none()
|
||||
|
||||
|
||||
def get_default_role() -> PermissionRole | None:
|
||||
"""新建用户预填的默认权限组。"""
|
||||
return (
|
||||
db.session.query(PermissionRole)
|
||||
.filter(PermissionRole.is_default.is_(True))
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def default_role_code() -> str:
|
||||
"""默认角色 code,未配置时回退 user。"""
|
||||
role = get_default_role()
|
||||
return role.code if role else 'user'
|
||||
|
||||
|
||||
def list_role_name_map() -> dict[str, str]:
|
||||
"""code → 显示名,供用户列表带出。"""
|
||||
rows = db.session.query(PermissionRole).all()
|
||||
return {row.code: row.name for row in rows}
|
||||
|
||||
|
||||
def _orm_session(sess: Any | None):
|
||||
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
||||
return sess if sess is not None else db.session
|
||||
|
||||
|
||||
def _permission_roles_exist(sess: Any) -> bool:
|
||||
"""当前会话里是否已有权限组行。"""
|
||||
return sess.query(PermissionRole.id).first() is not None
|
||||
|
||||
|
||||
def platform_admin_users_query(sess: Any | None = None):
|
||||
"""
|
||||
启用中的平台管理员查询。
|
||||
|
||||
核心逻辑:已种子权限组时 join is_platform_admin;否则回退 users.role=admin。
|
||||
"""
|
||||
session = _orm_session(sess)
|
||||
query = session.query(User)
|
||||
if _permission_roles_exist(session):
|
||||
query = query.join(PermissionRole, PermissionRole.code == User.role).filter(
|
||||
PermissionRole.is_platform_admin.is_(True),
|
||||
)
|
||||
else:
|
||||
query = query.filter(User.role == PLATFORM_ADMIN_CODE)
|
||||
return query.filter(User.status == 'active').order_by(User.id.asc())
|
||||
|
||||
|
||||
def first_platform_admin_user(sess: Any | None = None) -> User | None:
|
||||
"""
|
||||
取 id 最小的启用中平台管理员,供排程种子写 owner。
|
||||
|
||||
Args:
|
||||
sess: 可选独立 Session;缺省用 Flask-SQLAlchemy 会话。
|
||||
|
||||
Returns:
|
||||
找到则返回 User,否则 None。
|
||||
"""
|
||||
return platform_admin_users_query(sess).first()
|
||||
|
||||
|
||||
def list_platform_admin_users(
|
||||
sess: Any | None = None,
|
||||
*,
|
||||
wecom_bound: bool = False,
|
||||
limit: int | None = None,
|
||||
) -> list[User]:
|
||||
"""
|
||||
列出启用中的平台管理员。
|
||||
|
||||
核心逻辑:告警接收人可再筛已绑企微,并限制条数。
|
||||
|
||||
Args:
|
||||
sess: 可选独立 Session。
|
||||
wecom_bound: True 时只要 wecom_userid 非空。
|
||||
limit: 可选上限。
|
||||
|
||||
Returns:
|
||||
按 id 升序的用户列表。
|
||||
"""
|
||||
query = platform_admin_users_query(sess)
|
||||
if wecom_bound:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
if limit is not None:
|
||||
query = query.limit(int(limit))
|
||||
return query.all()
|
||||
|
||||
|
||||
def first_schedule_owner_user(sess: Any | None = None) -> User | None:
|
||||
"""
|
||||
排程种子 owner:优先平台管理员,否则任意用户。
|
||||
|
||||
核心逻辑:没有管理员时仍要能种平台 Job,与历史「没 admin 就拿 id 最小用户」一致。
|
||||
"""
|
||||
owner = first_platform_admin_user(sess)
|
||||
if owner is not None:
|
||||
return owner
|
||||
return _orm_session(sess).query(User).order_by(User.id.asc()).first()
|
||||
|
||||
|
||||
def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
||||
"""
|
||||
判断用户是否属于 is_platform_admin 权限组。
|
||||
|
||||
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||
|
||||
Args:
|
||||
user: 当前用户;None 视为否。
|
||||
sess: 可选独立 Session。
|
||||
|
||||
Returns:
|
||||
True 表示平台管理员。
|
||||
"""
|
||||
if user is None:
|
||||
return False
|
||||
session = _orm_session(sess)
|
||||
role_code = str(getattr(user, 'role', '') or '').strip()
|
||||
cached = getattr(user, '_is_platform_admin_cached', None)
|
||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
||||
return bool(cached[1])
|
||||
if not role_code:
|
||||
user._is_platform_admin_cached = (role_code, False)
|
||||
return False
|
||||
if _permission_roles_exist(session):
|
||||
role = (
|
||||
session.query(PermissionRole)
|
||||
.filter(PermissionRole.code == role_code)
|
||||
.one_or_none()
|
||||
)
|
||||
result = bool(role and role.is_platform_admin)
|
||||
else:
|
||||
result = role_code == PLATFORM_ADMIN_CODE
|
||||
user._is_platform_admin_cached = (role_code, result)
|
||||
return result
|
||||
|
||||
|
||||
def platform_admin_role_codes(sess: Any | None = None) -> list[str]:
|
||||
"""当前所有平台管理组的 code;未种子时回退 ['admin']。"""
|
||||
session = _orm_session(sess)
|
||||
if not _permission_roles_exist(session):
|
||||
return [PLATFORM_ADMIN_CODE]
|
||||
rows = (
|
||||
session.query(PermissionRole.code)
|
||||
.filter(PermissionRole.is_platform_admin.is_(True))
|
||||
.all()
|
||||
)
|
||||
return [str(row[0]) for row in rows if row[0]]
|
||||
|
||||
|
||||
def _normalize_feature_map(raw: Any) -> dict[str, bool]:
|
||||
source = raw if isinstance(raw, dict) else {}
|
||||
return {key: bool(source.get(key)) for key in KNOWN_FEATURE_KEYS if key in source}
|
||||
|
||||
|
||||
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
||||
"""
|
||||
若已配置权限组,返回该用户角色包的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return None
|
||||
role = get_role_by_code(user.role)
|
||||
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
||||
if role and role.is_platform_admin:
|
||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
return result
|
||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
return result
|
||||
|
||||
|
||||
def sync_user_grants_from_role(user: User) -> None:
|
||||
"""
|
||||
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
||||
|
||||
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
||||
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
||||
未配置权限组时不改。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return
|
||||
role = get_role_by_code(user.role)
|
||||
if role is None:
|
||||
fallback = get_default_role()
|
||||
if fallback is None:
|
||||
return
|
||||
user.role = fallback.code
|
||||
role = fallback
|
||||
user.feature_permissions = {}
|
||||
if role.is_platform_admin:
|
||||
return
|
||||
user.agents = list(role.agents)
|
||||
|
||||
|
||||
def _count_members(code: str) -> int:
|
||||
return db.session.query(User).filter(User.role == code).count()
|
||||
|
||||
|
||||
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
||||
agent_ids = [agent.id for agent in role.agents] if with_agents else []
|
||||
return {
|
||||
'id': role.id,
|
||||
'code': role.code,
|
||||
'name': role.name,
|
||||
'description': role.description or '',
|
||||
'is_default': bool(role.is_default),
|
||||
'is_system': bool(role.is_system),
|
||||
'is_platform_admin': bool(role.is_platform_admin),
|
||||
'sort_order': role.sort_order,
|
||||
'member_count': _count_members(role.code),
|
||||
'agent_ids': agent_ids,
|
||||
'agent_names': [agent.name for agent in role.agents] if with_agents else [],
|
||||
'feature_permissions': _normalize_feature_map(role.feature_permissions),
|
||||
}
|
||||
|
||||
|
||||
def list_roles() -> list[dict[str, Any]]:
|
||||
"""权限组列表(含人数与已选应用)。"""
|
||||
rows = (
|
||||
db.session.query(PermissionRole)
|
||||
.options(joinedload(PermissionRole.agents))
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_role(row) for row in rows]
|
||||
|
||||
|
||||
def get_role_detail(code: str) -> dict[str, Any]:
|
||||
"""单个权限组详情。"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
return _serialize_role(role)
|
||||
|
||||
|
||||
def grantable_catalog() -> dict[str, Any]:
|
||||
"""
|
||||
角色编辑可选应用与能力。
|
||||
|
||||
Returns:
|
||||
agents: 启用中的全部 Agent(含 description / conversation_mode);features: 能力目录(含 bind / hint)。
|
||||
"""
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
items = []
|
||||
for agent in agents:
|
||||
handler = agent.handler_config if isinstance(agent.handler_config, dict) else {}
|
||||
items.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': str(agent.description or '').strip(),
|
||||
'agent_code': agent.agent_code,
|
||||
'content_profile': str(handler.get('content_profile') or ''),
|
||||
'conversation_mode': agent.conversation_mode,
|
||||
})
|
||||
return {
|
||||
'agents': items,
|
||||
'features': [
|
||||
{
|
||||
'key': item['key'],
|
||||
'bind': item['bind'],
|
||||
'name': item['name'],
|
||||
'hint': str(item.get('hint') or ''),
|
||||
}
|
||||
for item in FEATURE_CATALOG
|
||||
],
|
||||
'default_role_code': default_role_code(),
|
||||
}
|
||||
|
||||
|
||||
def _unset_other_defaults(keep_id: int | None) -> None:
|
||||
query = db.session.query(PermissionRole).filter(PermissionRole.is_default.is_(True))
|
||||
if keep_id is not None:
|
||||
query = query.filter(PermissionRole.id != keep_id)
|
||||
for row in query.all():
|
||||
row.is_default = False
|
||||
|
||||
|
||||
def _load_agents(agent_ids: Iterable[Any]) -> list[Agent]:
|
||||
ids = []
|
||||
for raw in agent_ids or []:
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value > 0:
|
||||
ids.append(value)
|
||||
if not ids:
|
||||
return []
|
||||
return db.session.query(Agent).filter(Agent.id.in_(ids)).all()
|
||||
|
||||
|
||||
def _apply_package(role: PermissionRole, data: dict[str, Any], *, allow_agents: bool) -> None:
|
||||
if 'name' in data:
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('Role name is required', code='ROLE.NAME_REQUIRED')
|
||||
role.name = name
|
||||
if 'description' in data:
|
||||
role.description = str(data.get('description') or '').strip() or None
|
||||
if 'sort_order' in data:
|
||||
try:
|
||||
role.sort_order = int(data.get('sort_order') or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('Invalid sort_order', code='ROLE.SORT_INVALID')
|
||||
if data.get('is_default'):
|
||||
_unset_other_defaults(role.id)
|
||||
role.is_default = True
|
||||
elif 'is_default' in data:
|
||||
if role.is_default and not data.get('is_default'):
|
||||
raise ValidationError('Keep at least one default role', code='ROLE.DEFAULT_REQUIRED')
|
||||
role.is_default = False
|
||||
if 'feature_permissions' in data:
|
||||
role.feature_permissions = _normalize_feature_map(data.get('feature_permissions'))
|
||||
if allow_agents and 'agent_ids' in data:
|
||||
role.agents = _load_agents(data.get('agent_ids') or [])
|
||||
role.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _enabled_feature_keys(raw: Any) -> set[str]:
|
||||
return {key for key, enabled in _normalize_feature_map(raw).items() if enabled}
|
||||
|
||||
|
||||
def _incoming_agent_ids(raw: Any) -> set[int]:
|
||||
ids: set[int] = set()
|
||||
for item in raw or []:
|
||||
try:
|
||||
value = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value > 0:
|
||||
ids.add(value)
|
||||
return ids
|
||||
|
||||
|
||||
def _grants_changed(role: PermissionRole, data: dict[str, Any], *, allow_agents: bool) -> bool:
|
||||
"""应用勾选或已打开的能力是否相对当前角色包有变化。"""
|
||||
if allow_agents and 'agent_ids' in data:
|
||||
current = {agent.id for agent in role.agents}
|
||||
if _incoming_agent_ids(data.get('agent_ids')) != current:
|
||||
return True
|
||||
if 'feature_permissions' in data:
|
||||
if _enabled_feature_keys(data.get('feature_permissions')) != _enabled_feature_keys(role.feature_permissions):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def create_role(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""新建权限组。"""
|
||||
code = str(data.get('code') or '').strip().lower()
|
||||
if not _ROLE_CODE_RE.match(code):
|
||||
raise ValidationError('Invalid role code', code='ROLE.CODE_INVALID')
|
||||
if code == PLATFORM_ADMIN_CODE:
|
||||
raise ValidationError('Cannot create another platform admin role', code='ROLE.CODE_RESERVED')
|
||||
if get_role_by_code(code):
|
||||
raise ConflictError('Role code already exists', code='ROLE.CODE_EXISTS')
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValidationError('Role name is required', code='ROLE.NAME_REQUIRED')
|
||||
role = PermissionRole(
|
||||
code=code,
|
||||
name=name,
|
||||
description=str(data.get('description') or '').strip() or None,
|
||||
is_default=False,
|
||||
is_system=False,
|
||||
is_platform_admin=False,
|
||||
sort_order=int(data.get('sort_order') or 100),
|
||||
feature_permissions={},
|
||||
)
|
||||
db.session.add(role)
|
||||
db.session.flush()
|
||||
_apply_package(role, data, allow_agents=True)
|
||||
db.session.commit()
|
||||
return {'id': role.id, 'code': role.code}
|
||||
|
||||
|
||||
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
保存权限组。仅当应用勾选或能力开关变化时,才同步该组用户的应用授权。
|
||||
|
||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
allow_agents = not role.is_platform_admin
|
||||
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
||||
_apply_package(role, data, allow_agents=allow_agents)
|
||||
users = db.session.query(User).filter(User.role == role.code).all() if grants_changed else []
|
||||
for user in users:
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'synced_users': len(users)}
|
||||
|
||||
|
||||
def delete_role(code: str) -> dict[str, Any]:
|
||||
"""删除非内置且无人使用的权限组。"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
if role.is_system or role.is_platform_admin:
|
||||
raise ForbiddenError('System role cannot be deleted', code='ROLE.SYSTEM_LOCKED')
|
||||
if _count_members(role.code):
|
||||
raise ConflictError('Role still has members', code='ROLE.HAS_MEMBERS')
|
||||
if role.is_default:
|
||||
raise ValidationError('Cannot delete the default role', code='ROLE.DEFAULT_REQUIRED')
|
||||
db.session.delete(role)
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': role_names.get(user.role) or user.role,
|
||||
'wecom_bound': bool(user.wecom_userid),
|
||||
}
|
||||
|
||||
|
||||
def list_picker_people() -> list[dict[str, Any]]:
|
||||
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
||||
role_names = list_role_name_map()
|
||||
query = db.session.query(User).filter(User.status == 'active')
|
||||
admin_codes = platform_admin_role_codes()
|
||||
if admin_codes:
|
||||
query = query.filter(User.role.notin_(admin_codes))
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
return [_person_payload(user, role_names) for user in users]
|
||||
|
||||
|
||||
def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||
seen: set[int] = set()
|
||||
result: list[int] = []
|
||||
for item in raw or []:
|
||||
try:
|
||||
value = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if value <= 0 or value in seen:
|
||||
continue
|
||||
seen.add(value)
|
||||
result.append(value)
|
||||
return result
|
||||
|
||||
|
||||
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
计算勾选草稿相对当前成员的增减,供确认框展示来源角色。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
raise NotFoundError('Permission role not found', code='ROLE.NOT_FOUND')
|
||||
if role.is_platform_admin:
|
||||
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
||||
default_code = default_role_code()
|
||||
selected = set(_normalize_selected_ids(selected_ids))
|
||||
current_members = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == role.code)
|
||||
.filter(User.status == 'active')
|
||||
.all()
|
||||
)
|
||||
current_ids = {user.id for user in current_members}
|
||||
added_ids = [item for item in selected if item not in current_ids]
|
||||
removed_ids = [item for item in current_ids if item not in selected]
|
||||
if role.code == default_code:
|
||||
removed_ids = []
|
||||
users_by_id = {
|
||||
user.id: user
|
||||
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
||||
} if added_ids or removed_ids else {}
|
||||
role_names = list_role_name_map()
|
||||
|
||||
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
||||
rows = []
|
||||
for user_id in ids:
|
||||
user = users_by_id.get(user_id)
|
||||
if not user or user_is_platform_admin(user):
|
||||
continue
|
||||
rows.append(_person_payload(user, role_names))
|
||||
return rows
|
||||
|
||||
added = _rows(added_ids)
|
||||
removed = _rows(removed_ids)
|
||||
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
||||
return {
|
||||
'role_code': role.code,
|
||||
'role_name': role.name,
|
||||
'default_role_code': default_code,
|
||||
'added': added,
|
||||
'removed': removed,
|
||||
'stolen': stolen,
|
||||
'ignored_admin': 0,
|
||||
}
|
||||
|
||||
|
||||
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
确认后写回成员:勾选的人改入本角色;取消勾选的人回到默认角色。
|
||||
排除管理员;默认角色忽略移出。
|
||||
"""
|
||||
preview = preview_role_members(code, selected_ids)
|
||||
role = get_role_by_code(code)
|
||||
default_code = preview['default_role_code']
|
||||
skipped_admin = 0
|
||||
for row in preview['added']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = role.code
|
||||
sync_user_grants_from_role(user)
|
||||
for row in preview['removed']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = default_code
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'added': len(preview['added']),
|
||||
'removed': len(preview['removed']),
|
||||
'skipped_admin': skipped_admin,
|
||||
}
|
||||
|
||||
|
||||
def assert_role_assignable(code: str | None, *, allow_admin: bool) -> str:
|
||||
"""
|
||||
校验将要写入 users.role 的 code。
|
||||
|
||||
Args:
|
||||
allow_admin: 用户编辑表单可为 True;选人弹窗必须 False。
|
||||
"""
|
||||
value = str(code or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('Role is required', code='ROLE.REQUIRED')
|
||||
if not roles_configured():
|
||||
return value
|
||||
role = get_role_by_code(value)
|
||||
if not role:
|
||||
raise ValidationError('Unknown role', code='ROLE.NOT_FOUND')
|
||||
if role.is_platform_admin and not allow_admin:
|
||||
raise ForbiddenError('Platform admin cannot be assigned here', code='ROLE.ADMIN_LOCKED')
|
||||
return role.code
|
||||
|
||||
|
||||
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
||||
"""禁止撤掉最后一名启用中的平台管理员。"""
|
||||
if not user_is_platform_admin(user):
|
||||
return
|
||||
incoming = get_role_by_code(new_role)
|
||||
if incoming and incoming.is_platform_admin:
|
||||
return
|
||||
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
||||
return
|
||||
others = platform_admin_users_query().filter(User.id != user.id).first()
|
||||
if others is None:
|
||||
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
||||
|
||||
|
||||
def visible_features_for_role(role: PermissionRole) -> list[str]:
|
||||
"""当前角色已选应用下应展示的能力键。"""
|
||||
keys = []
|
||||
for item in FEATURE_CATALOG:
|
||||
if feature_visible_for_agents(item, list(role.agents)):
|
||||
keys.append(item['key'])
|
||||
return keys
|
||||
|
||||
|
||||
def match_seed_agent_ids(kind: str) -> list[int]:
|
||||
"""迁移种子:按 catalog 规则找出启用 Agent id。"""
|
||||
agents = db.session.query(Agent).filter(Agent.is_active.is_(True)).all()
|
||||
return [agent.id for agent in agents if agent_matches_kind(agent, kind)]
|
||||
@@ -1,4 +1,10 @@
|
||||
"""独立收料 RPA 排程等待态收口辅助。"""
|
||||
"""
|
||||
backend/app/services/schedule/freight_receipt_rpa_finalize.py
|
||||
|
||||
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。
|
||||
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
|
||||
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -46,8 +52,142 @@ def apply_deferred_receipt_schedule_run_state(
|
||||
return run
|
||||
|
||||
|
||||
def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
|
||||
"""
|
||||
收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
|
||||
|
||||
核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入
|
||||
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
|
||||
终态仍由 finalize_receipt_schedule_run_if_complete 负责。
|
||||
|
||||
Args:
|
||||
schedule_run_id: 排程执行记录主键。
|
||||
|
||||
Returns:
|
||||
dict: updated=True/False 及当前计数;非等待态返回 reason。
|
||||
"""
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if run is None:
|
||||
return {'updated': False, 'reason': 'schedule_run_not_found'}
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
|
||||
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
|
||||
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
|
||||
success_count = sum(unit.status == 'success' for unit in units)
|
||||
skipped_count = sum(unit.status == 'empty' for unit in units)
|
||||
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
|
||||
|
||||
# [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。
|
||||
run.success_count = max(int(run.success_count or 0), success_count)
|
||||
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
|
||||
run.failed_count = max(int(run.failed_count or 0), failed_count)
|
||||
if run.total_count is None or int(run.total_count or 0) < len(units):
|
||||
run.total_count = len(units)
|
||||
summary = dict(summary)
|
||||
summary['progress'] = {
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'processing_count': sum(unit.status == 'processing' for unit in units),
|
||||
'updated_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
return {
|
||||
'updated': True,
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
}
|
||||
|
||||
|
||||
def report_receipt_batch_progress(payload: dict) -> dict:
|
||||
"""
|
||||
Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
|
||||
|
||||
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升
|
||||
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
|
||||
|
||||
Args:
|
||||
payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。
|
||||
|
||||
Returns:
|
||||
dict: updated / rejected 及当前计数。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
return {'updated': False, 'reason': 'callback_schema_invalid'}
|
||||
try:
|
||||
schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None
|
||||
except (TypeError, ValueError):
|
||||
schedule_run_id = None
|
||||
if not schedule_run_id:
|
||||
return {'updated': False, 'reason': 'schedule_run_id_required'}
|
||||
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if run is None:
|
||||
return {'updated': False, 'reason': 'schedule_run_not_found'}
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
|
||||
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
|
||||
incoming = {
|
||||
'success_count': max(0, int(payload.get('success_count') or 0)),
|
||||
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
|
||||
'failed_count': max(0, int(payload.get('failed_count') or 0)),
|
||||
}
|
||||
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
|
||||
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
|
||||
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
|
||||
summary = dict(summary)
|
||||
summary['progress'] = {
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''),
|
||||
'updated_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
return {
|
||||
'updated': True,
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
}
|
||||
|
||||
|
||||
def mark_receipt_unit_processing(payload: dict) -> dict:
|
||||
"""
|
||||
Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。
|
||||
|
||||
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
return {'updated': False, 'reason': 'callback_schema_invalid'}
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
return {'updated': False, 'reason': 'callback_id_required'}
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None:
|
||||
return {'updated': False, 'reason': 'unit_not_found'}
|
||||
if unit.status in {'success', 'empty', 'failed', 'cancelled'}:
|
||||
return {'updated': False, 'reason': 'already_terminal', 'status': unit.status}
|
||||
if unit.status == 'processing':
|
||||
return {'updated': True, 'status': 'processing', 'idempotent': True}
|
||||
unit.status = 'processing'
|
||||
db.session.commit()
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
|
||||
|
||||
|
||||
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
"""当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。"""
|
||||
"""
|
||||
当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。
|
||||
|
||||
核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。
|
||||
"""
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if run is None:
|
||||
return {'finalized': False, 'reason': 'schedule_run_not_found'}
|
||||
@@ -69,9 +209,35 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
|
||||
|
||||
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
|
||||
archive_summary = {
|
||||
'raw_receipt_zip_available': False,
|
||||
'raw_receipt_zip_path': None,
|
||||
'raw_receipt_file_count': 0,
|
||||
'raw_receipt_file_ids': [],
|
||||
'raw_receipt_zip_size': 0,
|
||||
}
|
||||
try:
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive
|
||||
|
||||
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
|
||||
except Exception as archive_exc:
|
||||
current_app.logger.error(
|
||||
'[schedule-run] receipt RPA zip archive failed for run %s: %s',
|
||||
run.run_no, archive_exc,
|
||||
)
|
||||
|
||||
run.response_summary_json = {
|
||||
**summary,
|
||||
'awaiting_receipt_rpa': False,
|
||||
'success_count': success_count,
|
||||
'empty_count': skipped_count,
|
||||
'failed_count': failed_count,
|
||||
**archive_summary,
|
||||
}
|
||||
db.session.commit()
|
||||
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。
|
||||
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。
|
||||
try:
|
||||
task = run.task
|
||||
if task is not None and task.notify_enabled:
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。"""
|
||||
"""
|
||||
backend/app/services/schedule/freight_receipt_rpa_job.py
|
||||
|
||||
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
|
||||
依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、
|
||||
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
|
||||
ScheduleTask/Run。
|
||||
逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast;
|
||||
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -6,8 +15,13 @@ import uuid
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_receipt_rpa_worker_ready,
|
||||
)
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
@@ -24,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
|
||||
|
||||
|
||||
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
|
||||
"""读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。"""
|
||||
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
|
||||
wanted = _wanted_source_codes(task)
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
@@ -32,20 +46,27 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]:
|
||||
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
|
||||
return [
|
||||
dict(item) for item in (config.query_parameters_json or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
|
||||
|
||||
def _build_unit(
|
||||
source: ShippingInventorySource, config: ShippingReceiptReportConfig,
|
||||
warehouse_id: str | None, schedule_run_id: int,
|
||||
source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int,
|
||||
) -> ShippingReceiptRpaUnitRun:
|
||||
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
|
||||
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
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': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
|
||||
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
|
||||
connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id,
|
||||
status='awaiting_rpa', config_snapshot_json=snapshot,
|
||||
)
|
||||
|
||||
@@ -78,15 +99,35 @@ def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
for source, config in _eligible_sources(task):
|
||||
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id))
|
||||
"""
|
||||
写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。
|
||||
|
||||
核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed,
|
||||
不创建 unit、不进入 awaiting_receipt_rpa。
|
||||
"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = [
|
||||
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
|
||||
]
|
||||
if not units:
|
||||
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
|
||||
|
||||
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
|
||||
try:
|
||||
assert_receipt_rpa_worker_ready()
|
||||
except ServiceUnavailableError as exc:
|
||||
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
|
||||
detail_message = str((exc.details or {}).get('detail_message') or message)
|
||||
return len(units), 0, len(units), 0, [], [detail_message], [{
|
||||
'step': 'freight_receipt_rpa',
|
||||
'status': 'failed',
|
||||
'detail': {
|
||||
'message': message,
|
||||
'detail_message': detail_message,
|
||||
'error_code': exc.code,
|
||||
'reasons': (exc.details or {}).get('reasons') or [],
|
||||
},
|
||||
}]
|
||||
|
||||
db.session.add_all(units)
|
||||
db.session.flush()
|
||||
try:
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""独立收料文件抓取排程(08:00)。
|
||||
|
||||
用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。
|
||||
依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。
|
||||
逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
def _wanted_sources(task: ScheduleTask) -> list[str]:
|
||||
"""提取结构化 source_codes;留空代表全部启用来源。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
values = params.get("source_codes") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
return [str(item).strip() for item in values if str(item).strip()]
|
||||
|
||||
|
||||
def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""08:00 收料文件抓取;按来源实例独立执行。"""
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
sources = _wanted_sources(task) or []
|
||||
business_date = str(business_date_now())
|
||||
total = success = failed = empty = 0
|
||||
results: list[dict[str, Any]] = []
|
||||
warnings: list[str] = []
|
||||
errors: list[str] = []
|
||||
for source_code in sources:
|
||||
total += 1
|
||||
try:
|
||||
prepared = ensure_receipt_file_ready(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
repository=deps.file_repository,
|
||||
rpa_trigger=deps.rpa_trigger,
|
||||
)
|
||||
results.append({"source_code": source_code, "stage": prepared.stage})
|
||||
if prepared.stage == "file_ready":
|
||||
success += 1
|
||||
elif prepared.stage == "waiting_rpa_callback":
|
||||
empty += 1
|
||||
else:
|
||||
failed += 1
|
||||
errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}")
|
||||
except Exception as exc: # noqa: BLE001 —— 来源隔离
|
||||
failed += 1
|
||||
errors.append(f"{source_code}: {exc}")
|
||||
return (total, success, failed, empty, results, warnings, errors)
|
||||
@@ -1,8 +1,12 @@
|
||||
"""自动调拨排程(09:00)。
|
||||
"""自动调拨排程。
|
||||
|
||||
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
|
||||
依赖:auto_transfer、transfer deps、ScheduleExecuteResult。
|
||||
逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。
|
||||
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
|
||||
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
|
||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
|
||||
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
|
||||
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
|
||||
抑制框架卡;硬失败不置标记以便框架兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,42 +15,90 @@ from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
|
||||
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
def _task_params(task: ScheduleTask) -> dict[str, Any]:
|
||||
"""读取排程结构化参数(job_params 非字典时回落空对象)。"""
|
||||
return task.job_params if isinstance(task.job_params, dict) else {}
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""09:00 自动调拨:恢复 + 预检 + 执行 + 通知。"""
|
||||
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
||||
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。
|
||||
Returns:
|
||||
去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。
|
||||
"""
|
||||
params = _task_params(task)
|
||||
source_codes = params.get("source_codes") or []
|
||||
if isinstance(source_codes, str):
|
||||
source_codes = [source_codes]
|
||||
values = params.get("source_codes") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
codes = [str(item).strip() for item in values if str(item).strip()]
|
||||
if not codes:
|
||||
codes = list_receipt_capable_source_codes()
|
||||
return codes
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
|
||||
|
||||
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
|
||||
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
|
||||
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
|
||||
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
|
||||
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
|
||||
Returns:
|
||||
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
|
||||
"""
|
||||
params = _task_params(task)
|
||||
source_codes = _wanted_source_codes(task)
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
recipients = params.get("notify_user_ids") or []
|
||||
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
|
||||
|
||||
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
|
||||
sender = WecomSummarySender() if recipients else None
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = run_auto_transfer(
|
||||
business_date=str(business_date_now()),
|
||||
deps=deps,
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
source_codes=source_codes,
|
||||
recover_history=recover_history,
|
||||
sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果)
|
||||
recipients=[str(item) for item in recipients],
|
||||
sender=sender,
|
||||
recipients=recipients,
|
||||
)
|
||||
|
||||
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
|
||||
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
|
||||
if recipients and (outcome.run_no or not outcome.errors):
|
||||
run.response_summary_json = {
|
||||
**(run.response_summary_json or {}),
|
||||
"domain_notification_managed": True,
|
||||
}
|
||||
results: list[dict[str, Any]] = []
|
||||
errors: list[str] = list(outcome.errors)
|
||||
recovery = outcome.recovery
|
||||
warnings: list[str] = [
|
||||
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
|
||||
]
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
"notification_status": outcome.notification_status,
|
||||
})
|
||||
recovery = outcome.recovery
|
||||
elif not outcome.errors:
|
||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||
warnings.append("no executable items; execution and notification skipped")
|
||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
||||
return (
|
||||
success + recovery.recovered_count,
|
||||
@@ -54,6 +106,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
recovery.still_blocked_count,
|
||||
0,
|
||||
results,
|
||||
[f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"],
|
||||
warnings,
|
||||
errors,
|
||||
)
|
||||
@@ -64,11 +64,31 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _users_options() -> list[dict[str, Any]]:
|
||||
"""启用中的用户列表(value=user.id),供排程通知人类参数选择。"""
|
||||
from app.models import User
|
||||
|
||||
users = (
|
||||
User.query.filter(User.status == "active")
|
||||
.order_by(User.username.asc())
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
"label": user.real_name or user.username,
|
||||
"value": user.id,
|
||||
"description": None if not user.wecom_userid else "wecom",
|
||||
}
|
||||
for user in users
|
||||
]
|
||||
|
||||
|
||||
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
|
||||
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
"shipping_receipt_sources": _shipping_receipt_sources_options,
|
||||
"users": _users_options,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -193,7 +193,6 @@ def _register_builtin_platform_jobs() -> None:
|
||||
description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。",
|
||||
category="procurement",
|
||||
))
|
||||
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
|
||||
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
@@ -472,35 +471,15 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults=dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-receipt-file",
|
||||
label="在途收料文件抓取",
|
||||
handler=run_in_transit_receipt_file_schedule,
|
||||
description=(
|
||||
"每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。"
|
||||
"09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
"label": "来源实例",
|
||||
"label_key": "admin.schedule.form.transferSourceCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "shipping_inventory_sources",
|
||||
},
|
||||
),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-transfer",
|
||||
label="在途自动调拨",
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"每日 09:00 自动处理新增可调拨项与历史可恢复异常;"
|
||||
"每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。"
|
||||
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
|
||||
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
|
||||
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
|
||||
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
|
||||
@@ -10,6 +10,7 @@ from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.core.response import utc_iso
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
from app.services.schedule.timezone_util import (
|
||||
DEFAULT_SCHEDULE_TIMEZONE,
|
||||
compute_next_run_at,
|
||||
@@ -85,6 +86,7 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
'excel_file_name': run.excel_file_name,
|
||||
'excel_file_size': run.excel_file_size,
|
||||
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
|
||||
'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary),
|
||||
'kb_sync_status': run.kb_sync_status,
|
||||
'kb_group_id': run.kb_group_id,
|
||||
'kb_document_id': run.kb_document_id,
|
||||
|
||||
@@ -103,10 +103,11 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
"""
|
||||
构造排程企微 textcard 跳转 query 参数。
|
||||
|
||||
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图,
|
||||
由前端在登录后自动触发一次下载,失败时保留手动下载入口。
|
||||
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
|
||||
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
|
||||
"""
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
params: dict[str, Any] = {
|
||||
@@ -116,6 +117,9 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
params['raw_zip'] = '1'
|
||||
params['download'] = 'inventory_raw_zip'
|
||||
elif receipt_raw_zip_available_from_summary(summary):
|
||||
params['raw_zip'] = '1'
|
||||
params['download'] = 'receipt_raw_zip'
|
||||
return params
|
||||
|
||||
|
||||
@@ -123,9 +127,9 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
|
||||
"""
|
||||
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
|
||||
|
||||
核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom),
|
||||
本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run
|
||||
全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。
|
||||
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
|
||||
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
|
||||
本函数保留给管理员单文件重发等旁路读取。
|
||||
"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
@@ -154,7 +158,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
组装排程完成企微 textcard 正文。
|
||||
|
||||
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
|
||||
有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。
|
||||
有原始库存/收料归档时提示包已随通知发送或可点击下载。
|
||||
"""
|
||||
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
|
||||
skipped_count = int(run.skipped_count or 0)
|
||||
@@ -168,12 +172,12 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
|
||||
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
|
||||
receipt_files = _receipt_report_files_for_run(run)
|
||||
if receipt_files:
|
||||
description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送'
|
||||
if receipt_raw_zip_available_from_summary(summary):
|
||||
description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载'
|
||||
return description
|
||||
|
||||
|
||||
@@ -183,7 +187,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
|
||||
则跳过以免与领域缺件/失败告警重复。
|
||||
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
|
||||
收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。
|
||||
收料附加该 run 的原始收料 ZIP(不再逐文件推送)。
|
||||
"""
|
||||
from app.services.integrations.wecom.notify import (
|
||||
upload_wecom_temp_media,
|
||||
@@ -244,20 +248,20 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
receipt_media: list[tuple[str, str]] = []
|
||||
for receipt_file in _receipt_report_files_for_run(run):
|
||||
try:
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
receipt_zip_media_id = None
|
||||
receipt_zip_file_name = None
|
||||
try:
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
|
||||
|
||||
receipt_media_id = upload_wecom_temp_media(
|
||||
file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename,
|
||||
)
|
||||
receipt_media.append((receipt_media_id, receipt_file.original_filename))
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
'[wecom-schedule] receipt file media upload failed for run %s file %s: %s',
|
||||
run.run_no, receipt_file.id, exc,
|
||||
)
|
||||
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
|
||||
receipt_zip_media_id = upload_wecom_temp_media(
|
||||
receipt_zip_path.read_bytes(), receipt_zip_file_name,
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.info(
|
||||
'[wecom-schedule] raw receipt zip media skipped for run %s: %s',
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
textcard_ok_count = 0
|
||||
errors = []
|
||||
@@ -314,21 +318,23 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
|
||||
|
||||
for receipt_media_id, receipt_filename in receipt_media:
|
||||
if receipt_zip_media_id:
|
||||
try:
|
||||
receipt_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_receipt_file', u,
|
||||
title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex,
|
||||
receipt_zip_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u,
|
||||
title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex,
|
||||
)
|
||||
receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id)
|
||||
if receipt_data.get('errcode') == 0:
|
||||
receipt_audit.status = 'sent'
|
||||
receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id)
|
||||
if receipt_zip_data.get('errcode') == 0:
|
||||
receipt_zip_audit.status = 'sent'
|
||||
else:
|
||||
receipt_audit.error_code = str(receipt_data.get('errcode'))
|
||||
receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}')
|
||||
receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode'))
|
||||
receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(
|
||||
f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}'
|
||||
)
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: receipt file exception={exc}')
|
||||
errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}')
|
||||
|
||||
if textcard_ok_count > 0:
|
||||
run.wecom_notified = True
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_receipt_rpa_archive.py
|
||||
|
||||
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
|
||||
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
|
||||
file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。
|
||||
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
|
||||
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
|
||||
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
|
||||
|
||||
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
|
||||
|
||||
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
|
||||
'raw_receipt_zip_available': False,
|
||||
'raw_receipt_zip_path': None,
|
||||
'raw_receipt_file_count': 0,
|
||||
'raw_receipt_file_ids': [],
|
||||
'raw_receipt_zip_size': 0,
|
||||
}
|
||||
|
||||
|
||||
def get_receipt_archive_dir() -> str:
|
||||
"""
|
||||
返回收料 RPA 原始 ZIP 归档根目录(自动创建)。
|
||||
|
||||
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
|
||||
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
|
||||
"""
|
||||
configured = ''
|
||||
if current_app:
|
||||
raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
|
||||
configured = str(raw).strip() if raw is not None else ''
|
||||
if not configured:
|
||||
from app.core.config.settings import Config
|
||||
|
||||
configured = str(Config.FREIGHT_RPA_RECEIPT_ARCHIVE_DIR or '').strip()
|
||||
archive_dir = Path(configured)
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(archive_dir)
|
||||
|
||||
|
||||
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
|
||||
"""
|
||||
推导企微/下载展示名中的当地时刻。
|
||||
|
||||
核心逻辑:与库存归档同构——started_at → created_at → finished_at →
|
||||
解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。
|
||||
"""
|
||||
when_utc: datetime | None = None
|
||||
for value in (run.started_at, run.created_at, run.finished_at):
|
||||
if isinstance(value, datetime):
|
||||
when_utc = value
|
||||
break
|
||||
if when_utc is None:
|
||||
match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip())
|
||||
if match:
|
||||
try:
|
||||
when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S')
|
||||
except ValueError:
|
||||
when_utc = None
|
||||
if when_utc is None:
|
||||
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
task = getattr(run, 'task', None)
|
||||
tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None
|
||||
tz = resolve_schedule_tzinfo(tz_name)
|
||||
if when_utc.tzinfo is None:
|
||||
when_utc = when_utc.replace(tzinfo=timezone.utc)
|
||||
return when_utc.astimezone(tz)
|
||||
|
||||
|
||||
def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
|
||||
"""
|
||||
收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
|
||||
|
||||
Args:
|
||||
run: 排程执行记录。
|
||||
|
||||
Returns:
|
||||
不含角色后缀与扩展名的展示名前缀。
|
||||
"""
|
||||
when = _attachment_when_from_run(run)
|
||||
return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
|
||||
|
||||
|
||||
def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
|
||||
"""
|
||||
收料 ZIP 的企微/浏览器下载展示名。
|
||||
|
||||
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
|
||||
"""
|
||||
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
|
||||
|
||||
|
||||
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
|
||||
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
|
||||
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
|
||||
|
||||
|
||||
def _iter_packable_receipt_files(run: ScheduleRun):
|
||||
"""
|
||||
遍历该 run 下可打包的收料归档文件。
|
||||
|
||||
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
|
||||
|
||||
Yields:
|
||||
ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。
|
||||
"""
|
||||
if not is_freight_receipt_rpa_task(getattr(run, 'task', None)):
|
||||
return
|
||||
rows = (
|
||||
ShippingReceiptReportFile.query.join(
|
||||
ShippingReceiptRpaUnitRun,
|
||||
ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.id.asc())
|
||||
.all()
|
||||
)
|
||||
for report_file in rows:
|
||||
yield report_file
|
||||
|
||||
|
||||
def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
|
||||
"""
|
||||
从 response_summary_json 读取原始收料 ZIP 是否可下载。
|
||||
|
||||
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
|
||||
"""
|
||||
if not isinstance(summary, dict):
|
||||
return False
|
||||
return bool(summary.get('raw_receipt_zip_available'))
|
||||
|
||||
|
||||
def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
|
||||
"""
|
||||
finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。
|
||||
|
||||
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
|
||||
(含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。
|
||||
|
||||
Args:
|
||||
run: 收料 RPA ScheduleRun。
|
||||
|
||||
Returns:
|
||||
dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。
|
||||
"""
|
||||
packable_files = list(_iter_packable_receipt_files(run))
|
||||
if not packable_files:
|
||||
return dict(_EMPTY_ARCHIVE_SUMMARY)
|
||||
|
||||
archive_path = _receipt_raw_zip_archive_path(run.run_no)
|
||||
files_manifest: list[dict[str, Any]] = []
|
||||
|
||||
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for zip_index, report_file in enumerate(packable_files, start=1):
|
||||
unit = report_file.unit_run
|
||||
source_code = str(getattr(unit, 'source_code', None) or '').strip()
|
||||
warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip()
|
||||
original_name = str(report_file.original_filename or '').strip() or 'receipt.xlsx'
|
||||
suffix = Path(original_name).suffix or '.xlsx'
|
||||
entry_name = _build_zip_entry_name(
|
||||
index=zip_index,
|
||||
source_code=source_code,
|
||||
warehouse_id=warehouse_id,
|
||||
original_suffix=suffix,
|
||||
)
|
||||
# [STEP] 收料归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。
|
||||
data = file_asset_storage.get_bytes(report_file.storage_key)
|
||||
archive.writestr(entry_name, data)
|
||||
files_manifest.append({
|
||||
'file_id': report_file.id,
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
'file_name': entry_name,
|
||||
'original_file_name': original_name,
|
||||
'sha256': report_file.sha256,
|
||||
})
|
||||
|
||||
manifest = {
|
||||
'run_no': run.run_no,
|
||||
'total_count': int(run.total_count or 0),
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'files': files_manifest,
|
||||
}
|
||||
archive.writestr(
|
||||
'manifest.json',
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2),
|
||||
)
|
||||
|
||||
return {
|
||||
'raw_receipt_zip_available': True,
|
||||
'raw_receipt_zip_path': str(archive_path.resolve()),
|
||||
'raw_receipt_file_count': len(files_manifest),
|
||||
'raw_receipt_file_ids': [item['file_id'] for item in files_manifest],
|
||||
'raw_receipt_zip_size': int(archive_path.stat().st_size),
|
||||
}
|
||||
|
||||
|
||||
def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
|
||||
"""
|
||||
校验归档 ZIP 路径是否安全可下载。
|
||||
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。
|
||||
"""
|
||||
resolved = zip_path.resolve()
|
||||
if resolved.suffix.lower() != '.zip':
|
||||
return False
|
||||
if not resolved.is_file():
|
||||
return False
|
||||
|
||||
archive_dir = Path(get_receipt_archive_dir()).resolve()
|
||||
try:
|
||||
resolved.relative_to(archive_dir)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
"""
|
||||
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
|
||||
|
||||
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
|
||||
且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
|
||||
Returns:
|
||||
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
|
||||
|
||||
Raises:
|
||||
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
|
||||
"""
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not receipt_raw_zip_available_from_summary(summary):
|
||||
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
|
||||
|
||||
zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip()
|
||||
if not zip_path_raw:
|
||||
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
|
||||
|
||||
zip_path = Path(zip_path_raw)
|
||||
if not _is_allowed_receipt_archive_path(zip_path):
|
||||
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
|
||||
|
||||
return zip_path.resolve(), receipt_raw_zip_download_name(run)
|
||||
|
||||
|
||||
def _sanitize_zip_segment(value: str) -> str:
|
||||
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
|
||||
cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip())
|
||||
return cleaned or 'unknown'
|
||||
|
||||
|
||||
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
|
||||
"""
|
||||
包内短标签:优先 source_code;无则回退仓码;再否则 receipt。
|
||||
|
||||
warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。
|
||||
"""
|
||||
source = str(source_code or '').strip()
|
||||
if source:
|
||||
return source
|
||||
warehouse = str(warehouse_id or '').strip()
|
||||
if warehouse and warehouse.lower() not in {'unknown', 'na'}:
|
||||
return warehouse
|
||||
return 'receipt'
|
||||
|
||||
|
||||
def _build_zip_entry_name(
|
||||
*,
|
||||
index: int,
|
||||
source_code: str,
|
||||
warehouse_id: str,
|
||||
original_suffix: str,
|
||||
) -> str:
|
||||
"""
|
||||
生成 ZIP 内单文件条目名(不含目录)。
|
||||
|
||||
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
|
||||
"""
|
||||
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
|
||||
suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}'
|
||||
return f'{index:03d}_{label}{suffix}'
|
||||
@@ -721,8 +721,6 @@ def can_force_create_shipping_duplicate(user: User | None) -> bool:
|
||||
"""判断用户是否可强制新建重复发货通知。"""
|
||||
if user is None:
|
||||
return False
|
||||
if str(getattr(user, 'role', '') or '') == 'admin':
|
||||
return True
|
||||
return bool(user.has_feature_permission('shipping_notice_force_create'))
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_configuration_test.py
|
||||
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析和自动启用判定。
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。
|
||||
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
|
||||
逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。
|
||||
逻辑:管理端发起批量/单站测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不自动启用站点、不关联订单任务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -347,9 +347,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'confirmed_profile_checksum': source.parsing_profile.checksum,
|
||||
}
|
||||
run.completed_at = datetime.utcnow()
|
||||
# 空库存同样证明当前配置可查询;全部必要条件满足时自动投入正式运行。
|
||||
from app.services.admin.shipping_inventory_service import activate_source_if_ready
|
||||
activate_source_if_ready(source, actor_id=run.created_by)
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
if status != 'success':
|
||||
@@ -401,7 +398,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
), None)
|
||||
run.analysis_id = analysis.id; run.status = 'completed'
|
||||
if current_profile_candidate is not None:
|
||||
# 当前绑定的方案已验证时,测试应直接成为站点启用证据,无需管理员重复确认相同方案。
|
||||
# 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。
|
||||
run.stage = 'current_profile_verified'
|
||||
run.result_json = {
|
||||
'analysis': serialize_analysis(analysis),
|
||||
@@ -410,9 +407,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'current_profile_verified': True,
|
||||
'profile_match_level': current_profile_candidate.get('level'),
|
||||
}
|
||||
# 当前绑定解析已由本次文件验证,无需管理员重复确认或手动启用。
|
||||
from app.services.admin.shipping_inventory_service import activate_source_if_ready
|
||||
activate_source_if_ready(source, actor_id=run.created_by)
|
||||
else:
|
||||
run.stage = 'ready_for_confirmation'
|
||||
run.result_json = {'analysis': serialize_analysis(analysis)}
|
||||
|
||||
@@ -62,7 +62,11 @@ _WAREHOUSE_ID_HEADER_ALIASES = {
|
||||
|
||||
|
||||
def inventory_snapshot_ttl_hours() -> int:
|
||||
"""库存快照 TTL(小时);默认 24。"""
|
||||
"""库存快照 TTL(小时);默认 24。
|
||||
|
||||
唯一权威来源为全局配置 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS;
|
||||
不读取站点字段 snapshot_ttl_seconds(该字段已退出管理端配置面)。
|
||||
"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS", 24)
|
||||
try:
|
||||
return max(int(raw), 1)
|
||||
|
||||
@@ -86,7 +86,7 @@ def _resolve_cancellation_operation_id(run: ShippingOrderProcessingRun, explicit
|
||||
|
||||
def _is_admin(actor: User) -> bool:
|
||||
"""判断操作者是否具备管理员取消权限。"""
|
||||
return str(getattr(actor, 'role', '') or '') == 'admin'
|
||||
return bool(actor.is_platform_admin())
|
||||
|
||||
|
||||
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderProcessingRun:
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
"""确保订单识别进度事件清理的每日默认排程存在。"""
|
||||
"""
|
||||
services/shipping_notice/order_extraction_progress_cleanup_schedule.py
|
||||
|
||||
用途:确保订单识别进度事件清理的每日默认排程存在。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:无用户时跳过;owner 优先平台管理员。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
@@ -6,7 +12,8 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -24,7 +31,7 @@ def ensure_default_order_extraction_progress_cleanup_schedule(*, commit: bool =
|
||||
).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
owner = sess.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info('skip seed order-extraction progress cleanup schedule: no users yet')
|
||||
return None
|
||||
|
||||
@@ -154,7 +154,7 @@ def save_quality_label(*, batch_id: int, run_no: str, actor_id: int, payload: An
|
||||
if batch is None:
|
||||
raise NotFoundError('Quality batch not found')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
if actor is None or not actor.is_platform_admin():
|
||||
raise ValidationError('Quality reviewer must be an administrator')
|
||||
if (
|
||||
batch.status in {'approved', 'rejected'}
|
||||
@@ -215,7 +215,7 @@ def approve_quality_batch(*, batch_id: int, role: str, actor_id: int) -> Shippin
|
||||
if batch.status == 'rejected':
|
||||
raise ConflictError('Quality batch was rejected')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
if actor is None or not actor.is_platform_admin():
|
||||
raise ValidationError('Quality approver must be an administrator')
|
||||
if not quality_metrics(batch)['eligible']:
|
||||
raise ConflictError(
|
||||
|
||||
@@ -562,7 +562,7 @@ def _require_owner_agent(*, user: User, agent_id: int) -> Agent:
|
||||
'agent_id must reference an active shipping notice agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
)
|
||||
if str(user.role or '').lower() != 'admin' and agent not in user.agents:
|
||||
if not user.is_platform_admin() and agent not in user.agents:
|
||||
raise ForbiddenError(
|
||||
'Permission denied for this agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_FORBIDDEN',
|
||||
|
||||
@@ -147,9 +147,17 @@ class PerSourcePrepareResult:
|
||||
|
||||
|
||||
def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str:
|
||||
"""构造 per-source 三元组唯一 run_no:PSR-<task_no>-<SOURCE>-<attempt_no>-<uuid8>。"""
|
||||
suffix = uuid.uuid4().hex[:8].upper()
|
||||
return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.task_no}-{attempt.source_code}-A{attempt.attempt_no}-{suffix}'
|
||||
"""
|
||||
构造 per-source 唯一 run_no:PSR-<attempt_id>(dumb ID)。
|
||||
|
||||
[设计] 编号只承担唯一标识与回调回显匹配,不嵌入业务语义——task_no/source_code/
|
||||
attempt_no 已是 Attempt 行的结构化列,嵌入只会让长度被最长的语义段绑架
|
||||
(2026-09-27:65 字符组合超 varchar(64) 致门禁 Attempt 终态失败;迁移
|
||||
we9f0a1b2c3d 已加宽到 128,兜底旧格式与外部变化)。Worker 侧将该编号当作
|
||||
不透明标签透传(文件命名/回调回显),不做解析,缩短对 Worker 零影响。
|
||||
PSR- 前缀保留,用于与 legacy T-xxx 全局 run_no 家族区分。
|
||||
"""
|
||||
return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.id}'
|
||||
|
||||
|
||||
def _latest_attempt(
|
||||
@@ -649,7 +657,7 @@ def per_source_callback_handler(
|
||||
|
||||
# [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态
|
||||
consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess)
|
||||
# Run no format: PSR-<task>-<SOURCE>-A<N>-<uuid> → 排序按 attempt_no 前缀即可
|
||||
# 迟到判断按 attempt_no 数值比较(run_no 自身为 PSR-<attempt_id>,不含序号语义)
|
||||
try:
|
||||
current_attempt_no = int(attempt.attempt_no)
|
||||
except (TypeError, ValueError):
|
||||
|
||||
@@ -35,7 +35,7 @@ def is_shipping_admin(user: User) -> bool:
|
||||
Returns:
|
||||
True 表示管理员。
|
||||
"""
|
||||
return str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
return bool(user.is_platform_admin())
|
||||
|
||||
|
||||
def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set[int]:
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
|
||||
def _is_admin(user: User) -> bool:
|
||||
"""判断用户是否为收料报表管理角色。"""
|
||||
return str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
return bool(user.is_platform_admin())
|
||||
|
||||
|
||||
def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, user: User) -> bool:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""收料报表企微通知的管理员重发通道。
|
||||
|
||||
用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送
|
||||
textcard 汇总 + 全部收料文件(scheduler_service._notify_schedule_run_wecom,
|
||||
textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom,
|
||||
与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的
|
||||
强制重发能力(POST /receipt-report-files/<id>/resend),不触发 RPA。
|
||||
依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
"""收料 RPA callback 的原样归档服务。
|
||||
|
||||
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线);
|
||||
每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。
|
||||
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
|
||||
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)、
|
||||
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.receipt_callback_bridge(惰性导入)、
|
||||
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
|
||||
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
|
||||
success 分支再触发调拨证据同步(sync_and_commit_for_callback);两座桥都是记账
|
||||
不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data);
|
||||
有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步;
|
||||
两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -85,19 +87,36 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
if status in {'empty', 'no_data'}:
|
||||
unit.status = 'empty'; unit.error_code = None; unit.error_message = None; unit.finished_at = datetime.utcnow()
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
|
||||
unit.status = 'empty'
|
||||
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
|
||||
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
|
||||
before=before, after={'status': 'empty', 'callback_id': unit.callback_id},
|
||||
metadata={'callback_status': status},
|
||||
before=before,
|
||||
after={
|
||||
'status': 'empty',
|
||||
'callback_id': unit.callback_id,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
},
|
||||
metadata={'callback_status': status, 'skip_reason': unit.error_code},
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
|
||||
error_message=unit.error_message or 'no_receipt_data',
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
@@ -111,9 +130,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_receipt_callback_file(str(payload.get('file_path') or ''))
|
||||
@@ -147,9 +170,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
@@ -1,4 +1,11 @@
|
||||
"""独立收料 RPA trigger 的目录和载荷构造服务。"""
|
||||
"""
|
||||
backend/app/services/shipping_notice/receipt_rpa.py
|
||||
|
||||
用途:独立收料 RPA trigger 的目录解析与批量载荷原子写入。
|
||||
依赖:Flask current_app 配置 FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR。
|
||||
逻辑:freight_receipt_rpa_job / receipt_trigger_service 调用写 trigger;
|
||||
Worker 仅消费 shipping_receipt_rpa.v1,绝不回落到库存 trigger 目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,35 +25,6 @@ def receipt_trigger_dir() -> Path | None:
|
||||
return Path(value) if value else None
|
||||
|
||||
|
||||
def receipt_warehouse_values(config: Any) -> list[str]:
|
||||
"""从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。
|
||||
|
||||
Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单);
|
||||
排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。
|
||||
"""
|
||||
values: list[str] = []
|
||||
for item in (config.query_parameters_json or []):
|
||||
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
|
||||
continue
|
||||
for raw in (item.get('values') or []):
|
||||
cleaned = str(raw or '').strip()
|
||||
if cleaned and cleaned not in values:
|
||||
values.append(cleaned)
|
||||
return values
|
||||
|
||||
|
||||
def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]:
|
||||
"""构建单个执行单元的受控条件:剥离 Warehouse 条件。
|
||||
|
||||
Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件,
|
||||
快照里保留用户维护的 Warehouse 条件会与之重复冲突。
|
||||
"""
|
||||
return [
|
||||
dict(item) for item in (config.query_parameters_json or [])
|
||||
if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse')
|
||||
]
|
||||
|
||||
|
||||
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
|
||||
trigger_dir = receipt_trigger_dir()
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload trigger 前强制就绪检查;
|
||||
AUTO_UPLOAD 开启时由 create_app 与履约链调用货代上传就绪校验(Worker/凭据/共享目录/环境隔离)。
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
|
||||
shipping_notice.receipt_rpa(收料 trigger 目录)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,6 +33,9 @@ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
|
||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
||||
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
|
||||
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
|
||||
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
|
||||
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
|
||||
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
|
||||
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
||||
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
||||
@@ -354,10 +358,15 @@ def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str
|
||||
return None, "shared_sentinel_unreadable"
|
||||
|
||||
|
||||
def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]:
|
||||
def _verify_shared_trigger_mount(
|
||||
trigger_dir: Path | None, *, require_sentinel: bool = True,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。
|
||||
核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。
|
||||
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
|
||||
|
||||
Args:
|
||||
trigger_dir: 共享 trigger 目录。
|
||||
require_sentinel: 为 True 时在 test/prod 或配置了 scope 时校验哨兵。
|
||||
"""
|
||||
reasons: list[str] = []
|
||||
if trigger_dir is None:
|
||||
@@ -368,7 +377,7 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s
|
||||
return False, ["trigger_dir_not_accessible"]
|
||||
|
||||
expected_scope = shared_scope_id()
|
||||
if _shared_mount_check_required():
|
||||
if require_sentinel and _shared_mount_check_required():
|
||||
sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir)
|
||||
if sentinel_reason:
|
||||
reasons.append(sentinel_reason)
|
||||
@@ -391,6 +400,27 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断心跳是否来自收料 Worker。
|
||||
|
||||
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
|
||||
"""
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
|
||||
return True
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
expected = receipt_trigger_dir()
|
||||
actual = str(worker.get("trigger_dir") or "").strip()
|
||||
if expected is None or not actual:
|
||||
return False
|
||||
try:
|
||||
return Path(actual).resolve() == expected.resolve()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
|
||||
expected_scope = shared_scope_id()
|
||||
if not expected_scope:
|
||||
@@ -472,14 +502,18 @@ def _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir: Path | None,
|
||||
required_capability: str,
|
||||
extra_reasons: list[str] | None = None,
|
||||
worker_predicate: Any | None = None,
|
||||
require_sentinel: bool = True,
|
||||
) -> RpaWorkerReadiness:
|
||||
"""
|
||||
通用 Worker 就绪检查:心跳存储、共享挂载、能力声明与环境隔离。
|
||||
|
||||
Args:
|
||||
trigger_dir: 待校验的共享 trigger 目录。
|
||||
required_capability: 必选 Worker 能力。
|
||||
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
||||
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
||||
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
|
||||
require_sentinel: 是否要求共享哨兵(收料为 False)。
|
||||
|
||||
Returns:
|
||||
RpaWorkerReadiness。
|
||||
@@ -496,7 +530,9 @@ def _check_rpa_worker_ready_for_capability(
|
||||
if _heartbeat_redis_required() and _redis_client() is None:
|
||||
reasons.append("heartbeat_storage_unavailable")
|
||||
|
||||
_mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir)
|
||||
_mount_ok, mount_reasons = _verify_shared_trigger_mount(
|
||||
trigger_dir, require_sentinel=require_sentinel,
|
||||
)
|
||||
reasons.extend(mount_reasons)
|
||||
|
||||
backend_env = resolve_backend_rpa_environment()
|
||||
@@ -505,6 +541,8 @@ def _check_rpa_worker_ready_for_capability(
|
||||
workers, storage_read_failed = list_rpa_worker_heartbeats()
|
||||
if storage_read_failed:
|
||||
reasons.append("heartbeat_storage_unavailable")
|
||||
if worker_predicate is not None:
|
||||
workers = [worker for worker in workers if worker_predicate(worker)]
|
||||
eligible_workers: list[dict[str, Any]] = []
|
||||
enriched_workers: list[dict[str, Any]] = []
|
||||
|
||||
@@ -590,6 +628,60 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
)
|
||||
|
||||
|
||||
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
|
||||
|
||||
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
|
||||
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=receipt_trigger_dir(),
|
||||
required_capability=RECEIPT_EXPORT_CAPABILITY,
|
||||
worker_predicate=is_receipt_rpa_worker,
|
||||
require_sentinel=True,
|
||||
)
|
||||
|
||||
|
||||
def assert_receipt_rpa_worker_ready() -> None:
|
||||
"""
|
||||
写收料 trigger 前的强制就绪检查。
|
||||
|
||||
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
|
||||
排程不得进入 awaiting_receipt_rpa。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
if result.ready:
|
||||
return
|
||||
code = 'RPA.WORKER_OFFLINE'
|
||||
if 'heartbeat_storage_unavailable' in result.reasons:
|
||||
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
|
||||
logger.warning(
|
||||
'[rpa-heartbeat] receipt readiness blocked code=%s reasons=%s detail=%s',
|
||||
code,
|
||||
result.reasons,
|
||||
result.detail_message,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
result.message,
|
||||
code=code,
|
||||
details={
|
||||
'reasons': result.reasons,
|
||||
'detail_message': result.detail_message,
|
||||
'checked_at': result.checked_at,
|
||||
'shared_scope_id': shared_scope_id(),
|
||||
'trigger_dir': str(receipt_trigger_dir() or ''),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _freight_upload_config_reasons() -> list[str]:
|
||||
"""
|
||||
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
|
||||
@@ -749,11 +841,25 @@ def assert_inventory_rpa_worker_ready() -> None:
|
||||
)
|
||||
|
||||
|
||||
def serialize_rpa_worker_status() -> dict[str, Any]:
|
||||
"""管理端展示:在线 worker 列表与库存/货代上传就绪摘要(含详细 reasons)。"""
|
||||
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
|
||||
"""
|
||||
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
|
||||
|
||||
Args:
|
||||
scope: inventory(默认)或 receipt。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
|
||||
normalized = str(scope or "inventory").strip().lower()
|
||||
if normalized == "receipt":
|
||||
readiness = check_receipt_rpa_worker_ready()
|
||||
trigger_path = str(receipt_trigger_dir() or "")
|
||||
else:
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
trigger_path = str(inventory_trigger_dir() or "")
|
||||
normalized = "inventory"
|
||||
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
freight_readiness = check_freight_upload_rpa_ready()
|
||||
ttl_seconds = _heartbeat_ttl_seconds()
|
||||
workers = []
|
||||
@@ -777,6 +883,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]:
|
||||
"ineligible_reasons": worker.get("ineligible_reasons") or [],
|
||||
})
|
||||
return {
|
||||
"scope": normalized,
|
||||
"ready": readiness.ready,
|
||||
"message": readiness.message,
|
||||
"detail_message": readiness.detail_message,
|
||||
@@ -785,7 +892,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]:
|
||||
"backend_environment": resolve_backend_rpa_environment(),
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"shared_sentinel_name": shared_sentinel_name(),
|
||||
"trigger_dir": str(inventory_trigger_dir() or ""),
|
||||
"trigger_dir": trigger_path,
|
||||
"upload_trigger_dir": str(upload_trigger_dir() or ""),
|
||||
"reasons": readiness.reasons,
|
||||
"workers": workers,
|
||||
|
||||
@@ -20,6 +20,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.permission_roles.service import list_platform_admin_users
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
@@ -65,7 +66,7 @@ def _alert_fallback_admin_enabled() -> bool:
|
||||
def _alert_recipients() -> list[User]:
|
||||
"""
|
||||
解析告警接收人。
|
||||
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
|
||||
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的平台管理员。
|
||||
"""
|
||||
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_USERNAMES") or "").strip()
|
||||
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
|
||||
@@ -82,13 +83,7 @@ def _alert_recipients() -> list[User]:
|
||||
names,
|
||||
)
|
||||
if _alert_fallback_admin_enabled():
|
||||
admins = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == "admin", User.wecom_userid.isnot(None))
|
||||
.order_by(User.id.asc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
admins = list_platform_admin_users(wecom_bound=True, limit=20)
|
||||
if admins:
|
||||
logger.info(
|
||||
"[rpa-heartbeat-alert] using admin fallback recipients count=%d",
|
||||
@@ -106,7 +101,7 @@ def _log_recipient_gap_once() -> None:
|
||||
_RECIPIENT_GAP_LOGGED = True
|
||||
logger.warning(
|
||||
"[rpa-heartbeat-alert] no wecom recipients: set FREIGHT_RPA_WORKER_ALERT_USERNAMES "
|
||||
"or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
|
||||
"or bind wecom_userid for at least one platform admin (FALLBACK_ADMIN=true)"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保立账凭证检核(周二 06:00)、PO 订单生成(周二 05:00)、销货放行单拉取(周二 05:30)默认 ScheduleTask 存在。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config。
|
||||
依赖:ScheduleTask/User、permission_roles.service.first_schedule_owner_user、timezone_util、voucher_check.config。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;检核排程剥离 schema 外的旧 job_params。
|
||||
"""
|
||||
|
||||
@@ -18,6 +18,7 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
from app.services.voucher_check.config import (
|
||||
DEFAULT_JOB_PARAMS,
|
||||
@@ -116,14 +117,7 @@ def ensure_default_voucher_check_schedule(
|
||||
sess.commit()
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
owner = _pick_schedule_owner(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed accounting-voucher-check schedule: no users yet")
|
||||
return None
|
||||
@@ -178,16 +172,8 @@ def ensure_default_voucher_check_schedule(
|
||||
|
||||
|
||||
def _pick_schedule_owner(sess: Any) -> Any | None:
|
||||
"""优先管理员,否则任意用户;尚无用户时返回 None。"""
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
return owner
|
||||
"""优先平台管理员,否则任意用户;尚无用户时返回 None。"""
|
||||
return first_schedule_owner_user(sess)
|
||||
|
||||
|
||||
def ensure_default_voucher_po_print_schedule(
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
backend/migrations/versions/0f1e2d3c4b5a_add_general_feedback_status.py
|
||||
|
||||
用途:给 general_feedbacks 增加处理状态字段,支撑「用户反馈与回答评价」的三张概览卡
|
||||
(待处理 / 本月已关闭 / 最多反馈应用)。
|
||||
依赖:Alembic revision a0b1c2d3e4f5(当前唯一 head)。
|
||||
逻辑:新增 status(默认 pending)与 closed_at(可空)两列;仅 DDL,不回填历史数据。
|
||||
|
||||
Revision ID: 0f1e2d3c4b5a
|
||||
Revises: a0b1c2d3e4f5
|
||||
Create Date: 2026-08-28 09:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0f1e2d3c4b5a"
|
||||
down_revision = "a0b1c2d3e4f5"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
'general_feedbacks',
|
||||
sa.Column('status', sa.String(20), nullable=False, server_default='pending'),
|
||||
)
|
||||
op.create_index('ix_general_feedbacks_status', 'general_feedbacks', ['status'])
|
||||
op.add_column(
|
||||
'general_feedbacks',
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('general_feedbacks', 'closed_at')
|
||||
op.drop_index('ix_general_feedbacks_status', table_name='general_feedbacks')
|
||||
op.drop_column('general_feedbacks', 'status')
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge feedback status and lean training heads
|
||||
|
||||
Revision ID: 353ebb6187ce
|
||||
Revises: 0f1e2d3c4b5a, fb26bc033d27
|
||||
Create Date: 2026-09-14 08:29:33.122865
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '353ebb6187ce'
|
||||
down_revision = ('0f1e2d3c4b5a', 'fb26bc033d27')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge snow feedback status and dev transfer naming heads
|
||||
|
||||
Revision ID: 6d7b0d04ac25
|
||||
Revises: 353ebb6187ce, 43a8179cdd88
|
||||
Create Date: 2026-09-23 13:45:05.502424
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '6d7b0d04ac25'
|
||||
down_revision = ('353ebb6187ce', '43a8179cdd88')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,30 @@
|
||||
"""合并 role、snow 反馈与库存回调三条 Alembic 头。
|
||||
|
||||
用途:``pr9d0e1f2031``(权限组 × 收料配置)、``6d7b0d04ac25``(snow 反馈状态 × 调拨命名)
|
||||
与 ``p1b2c3d4e5f6``(调用日志 wire_json × 库存 RPA 回调)在把 ``role`` 合入 ``dev`` 后
|
||||
并列成三个 head,导致 ``flask db upgrade`` 无法解析默认 ``head``。
|
||||
依赖:``pr9d0e1f2031``、``6d7b0d04ac25``、``p1b2c3d4e5f6``。
|
||||
逻辑:不修改业务表,只声明三条已完成迁移线在此收敛。
|
||||
|
||||
Revision ID: mh3b4c5d6e7f
|
||||
Revises: 6d7b0d04ac25, p1b2c3d4e5f6, pr9d0e1f2031
|
||||
Create Date: 2026-09-29 14:30:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "mh3b4c5d6e7f"
|
||||
down_revision = ("6d7b0d04ac25", "p1b2c3d4e5f6", "pr9d0e1f2031")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并三条迁移头,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚三个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Seed configurable permission roles.
|
||||
|
||||
Revision ID: pr7b8c9d0e1f
|
||||
Revises: vc6a7b8c9d0e
|
||||
Create Date: 2026-09-17 13:30:00.000000
|
||||
|
||||
用途:新增 permission_roles / permission_role_agents;按现网 users.role 套标准包并重写授权。
|
||||
依赖:users、agents、user_agent_permissions。
|
||||
逻辑:user/hr/admin 映射内置组,另种子研发应用与货代专员;个人勾选的额外应用按确认策略丢弃。
|
||||
不再种子设备维保专员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "pr7b8c9d0e1f"
|
||||
down_revision = "vc6a7b8c9d0e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
KNOWN_FEATURES = (
|
||||
"training_hr_manage",
|
||||
"shipping_notice_force_create",
|
||||
"shipping_notice.audit_sensitive_read",
|
||||
"shipping_notice.xfa_split_rule_edit",
|
||||
"shipping_notice.xfa_split_rule_preview",
|
||||
"shipping_notice.xfa_split_rule_publish",
|
||||
"maintenance.ledger_write",
|
||||
)
|
||||
|
||||
|
||||
def _content_profile(handler_config) -> str:
|
||||
raw = handler_config
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except Exception:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
return ""
|
||||
return str(raw.get("content_profile") or "").strip()
|
||||
|
||||
|
||||
def _matches(kind: str, agent_code: str, name: str, profile: str) -> bool:
|
||||
code = str(agent_code or "").strip()
|
||||
label = str(name or "")
|
||||
if kind == "entrance":
|
||||
return profile == "generic_entrance"
|
||||
if kind == "training":
|
||||
return profile == "training"
|
||||
if kind == "shipping":
|
||||
return code == "shipping_notice"
|
||||
if kind == "patent":
|
||||
return "专利" in label
|
||||
if kind == "maintenance":
|
||||
return "维保" in label or "维修" in label or code == "maintenance"
|
||||
return False
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""建表、加宽 users.role、种子权限组并按角色重写 user_agent_permissions。"""
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
tables = inspector.get_table_names()
|
||||
|
||||
if "permission_roles" not in tables:
|
||||
op.create_table(
|
||||
"permission_roles",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("code", sa.String(length=64), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("is_system", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("is_platform_admin", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("feature_permissions", sa.JSON(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("code", name="uq_permission_roles_code"),
|
||||
)
|
||||
op.create_index("ix_permission_roles_code", "permission_roles", ["code"])
|
||||
|
||||
if "permission_role_agents" not in tables:
|
||||
op.create_table(
|
||||
"permission_role_agents",
|
||||
sa.Column("role_id", sa.Integer(), sa.ForeignKey("permission_roles.id", ondelete="CASCADE"), primary_key=True),
|
||||
sa.Column("agent_id", sa.Integer(), sa.ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True),
|
||||
)
|
||||
|
||||
user_columns = {col["name"]: col for col in inspector.get_columns("users")}
|
||||
role_col = user_columns.get("role")
|
||||
if role_col is not None:
|
||||
op.alter_column(
|
||||
"users",
|
||||
"role",
|
||||
existing_type=role_col["type"],
|
||||
type_=sa.String(length=64),
|
||||
existing_nullable=True,
|
||||
)
|
||||
|
||||
now = datetime.utcnow()
|
||||
roles = bind.execute(sa.text("SELECT code FROM permission_roles")).fetchall()
|
||||
existing = {row[0] for row in roles}
|
||||
|
||||
seeds = [
|
||||
("user", "普通用户", "新建用户默认。勾通用入口即可使用企业知识库。", True, True, False, 10, {}, ("entrance",)),
|
||||
("rd", "研发人员", "通用入口,以及研发侧应用(如专利)。", False, False, False, 20, {}, ("entrance", "patent")),
|
||||
("hr", "培训 HR", "可进员工培训,并打开 HR 管理。", False, True, False, 30, {"training_hr_manage": True}, ("entrance", "training")),
|
||||
("shipping", "货代专员", "聊天与工作台共用货代应用入口。", False, False, False, 40, {"shipping_notice_force_create": True}, ("entrance", "shipping")),
|
||||
("admin", "管理员", "内置角色。应用入口隐式全开,可进入 /admin。", False, True, True, 90, {key: True for key in KNOWN_FEATURES}, ()),
|
||||
]
|
||||
|
||||
insert_role = sa.text(
|
||||
"""
|
||||
INSERT INTO permission_roles
|
||||
(code, name, description, is_default, is_system, is_platform_admin, sort_order, feature_permissions, created_at, updated_at)
|
||||
VALUES
|
||||
(:code, :name, :description, :is_default, :is_system, :is_platform_admin, :sort_order, :feature_permissions, :created_at, :updated_at)
|
||||
"""
|
||||
).bindparams(sa.bindparam("feature_permissions", type_=sa.JSON()))
|
||||
for code, name, desc, is_default, is_system, is_admin, sort_order, features, _match in seeds:
|
||||
if code in existing:
|
||||
continue
|
||||
bind.execute(
|
||||
insert_role,
|
||||
{
|
||||
"code": code,
|
||||
"name": name,
|
||||
"description": desc,
|
||||
"is_default": is_default,
|
||||
"is_system": is_system,
|
||||
"is_platform_admin": is_admin,
|
||||
"sort_order": sort_order,
|
||||
"feature_permissions": features,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
role_id_rows = bind.execute(sa.text("SELECT id, code FROM permission_roles")).fetchall()
|
||||
role_ids = {row[1]: row[0] for row in role_id_rows}
|
||||
|
||||
agents = bind.execute(
|
||||
sa.text("SELECT id, name, agent_code, handler_config, is_active FROM agents")
|
||||
).fetchall()
|
||||
active = [row for row in agents if bool(row[4])]
|
||||
|
||||
def ids_for(*kinds: str) -> list[int]:
|
||||
found: list[int] = []
|
||||
for row in active:
|
||||
profile = _content_profile(row[3])
|
||||
for kind in kinds:
|
||||
if _matches(kind, row[2], row[1], profile):
|
||||
found.append(int(row[0]))
|
||||
break
|
||||
return found
|
||||
|
||||
match_map = {
|
||||
"user": ("entrance",),
|
||||
"rd": ("entrance", "patent"),
|
||||
"hr": ("entrance", "training"),
|
||||
"shipping": ("entrance", "shipping"),
|
||||
"admin": (),
|
||||
}
|
||||
existing_links = {
|
||||
(int(row[0]), int(row[1]))
|
||||
for row in bind.execute(sa.text("SELECT role_id, agent_id FROM permission_role_agents")).fetchall()
|
||||
}
|
||||
insert_link = sa.text(
|
||||
"INSERT INTO permission_role_agents (role_id, agent_id) VALUES (:role_id, :agent_id)"
|
||||
)
|
||||
for code, kinds in match_map.items():
|
||||
role_id = role_ids.get(code)
|
||||
if not role_id:
|
||||
continue
|
||||
for agent_id in ids_for(*kinds):
|
||||
pair = (int(role_id), int(agent_id))
|
||||
if pair in existing_links:
|
||||
continue
|
||||
bind.execute(insert_link, {"role_id": role_id, "agent_id": agent_id})
|
||||
existing_links.add(pair)
|
||||
|
||||
# 未知 role(含已废弃的 maintenance_manager)收口到默认普通用户。
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE users
|
||||
SET role = 'user'
|
||||
WHERE role IS NULL OR role NOT IN ('user', 'hr', 'admin', 'rd', 'shipping')
|
||||
"""
|
||||
)
|
||||
)
|
||||
empty_json = sa.text("UPDATE users SET feature_permissions = :empty").bindparams(
|
||||
sa.bindparam("empty", type_=sa.JSON())
|
||||
)
|
||||
bind.execute(empty_json, {"empty": {}})
|
||||
|
||||
# 非管理员:用角色包全量替换个人 Agent 勾选。
|
||||
bind.execute(sa.text(
|
||||
"""
|
||||
DELETE FROM user_agent_permissions
|
||||
WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin')
|
||||
"""
|
||||
))
|
||||
bind.execute(sa.text(
|
||||
"""
|
||||
INSERT INTO user_agent_permissions (user_id, agent_id)
|
||||
SELECT u.id, pra.agent_id
|
||||
FROM users u
|
||||
JOIN permission_roles pr ON pr.code = u.role
|
||||
JOIN permission_role_agents pra ON pra.role_id = pr.id
|
||||
WHERE u.role <> 'admin'
|
||||
"""
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除权限组表;不回写已丢弃的个人 Agent 勾选。"""
|
||||
op.drop_table("permission_role_agents")
|
||||
op.drop_index("ix_permission_roles_code", table_name="permission_roles")
|
||||
op.drop_table("permission_roles")
|
||||
op.alter_column(
|
||||
"users",
|
||||
"role",
|
||||
existing_type=sa.String(length=64),
|
||||
type_=sa.String(length=20),
|
||||
existing_nullable=True,
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""合并权限组种子与客户 ODM 两条 Alembic 头。
|
||||
|
||||
用途:``pr7b8c9d0e1f``(权限组种子)与 ``dd22ee33ff44``(ODM × 凭证通知配置 merge)
|
||||
并列成双 head,导致 ``flask db upgrade`` 无法解析默认 ``head``。
|
||||
依赖:``pr7b8c9d0e1f``(permission_roles 种子)、
|
||||
``dd22ee33ff44``(aa11bb22cc33 × vc6a7b8c9d0e 图合并)。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
|
||||
Revision ID: pr8c9d0e1f20
|
||||
Revises: dd22ee33ff44, pr7b8c9d0e1f
|
||||
Create Date: 2026-09-18 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "pr8c9d0e1f20"
|
||||
down_revision = ("dd22ee33ff44", "pr7b8c9d0e1f")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并权限组种子与 ODM merge 节点,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,30 @@
|
||||
"""合并权限组 head 与收料配置两条 Alembic 头。
|
||||
|
||||
用途:``pr8c9d0e1f20``(权限组 × ODM merge)与 ``rc2b3c4d5e6f``(删除收料仓库清单)
|
||||
在把 ``role`` 合入 ``dev`` 后并列成双 head,导致 ``flask db upgrade`` 无法解析默认 ``head``。
|
||||
依赖:``pr8c9d0e1f20``(permission_roles 与 ODM 图合并)、
|
||||
``rc2b3c4d5e6f``(shipping_receipt_report_configs.warehouse_ids_json 删除)。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
|
||||
Revision ID: pr9d0e1f2031
|
||||
Revises: pr8c9d0e1f20, rc2b3c4d5e6f
|
||||
Create Date: 2026-09-22 18:30:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "pr9d0e1f2031"
|
||||
down_revision = ("pr8c9d0e1f20", "rc2b3c4d5e6f")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并权限组 head 与收料配置 head,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Add parse failure markers to shipping_receipt_report_files.
|
||||
|
||||
用途:shipping_receipt_report_files 新增三个可空列 parse_failed_at /
|
||||
parse_error_code / parse_error_message,为在途调拨来源错误分层提供
|
||||
「parse 失败」归档标记。
|
||||
依赖:shipping_receipt_report_files 表(收料原样归档文件);
|
||||
模型 backend/app/models/shipping_receipt_report.py 的
|
||||
ShippingReceiptReportFile 同步声明同名列。
|
||||
逻辑:解析失败时写入失败时间与错误码(≤64)/错误详情(Text);
|
||||
三列均为可空且无默认值,三者全空表示未失败或已清除,历史行
|
||||
与正常解析行不受影响;downgrade 直接 drop 三列。
|
||||
|
||||
Revision ID: q4c5d6e7f8a9
|
||||
Revises: mh3b4c5d6e7f
|
||||
Create Date: 2026-09-29 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "q4c5d6e7f8a9"
|
||||
down_revision = "mh3b4c5d6e7f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("shipping_receipt_report_files", sa.Column("parse_failed_at", sa.DateTime(), nullable=True))
|
||||
op.add_column("shipping_receipt_report_files", sa.Column("parse_error_code", sa.String(length=64), nullable=True))
|
||||
op.add_column("shipping_receipt_report_files", sa.Column("parse_error_message", sa.Text(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("shipping_receipt_report_files", "parse_error_message")
|
||||
op.drop_column("shipping_receipt_report_files", "parse_error_code")
|
||||
op.drop_column("shipping_receipt_report_files", "parse_failed_at")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Add inventory_checked_at to transfer_invoice_items.
|
||||
|
||||
用途:transfer_invoice_items 新增可空列 inventory_checked_at,承载「当前
|
||||
external_quantity 的 ERP 取数时刻」,修复 stale 徽标判定时钟被证据同步
|
||||
换戳续期污染的问题(此前 stale 挂 updated_at,每日收料文件同步会把
|
||||
老行新鲜度续期,徽标对最需要提示的行永不触发)。
|
||||
依赖:transfer_invoice_items 表(调拨明细行);模型
|
||||
backend/app/models/in_transit_transfer.py 的 TransferInvoiceItem
|
||||
同步声明同名列。
|
||||
逻辑:仅匹配评估/重查/执行写前复查在真实取数时写入;证据同步换戳/
|
||||
存续分支不续期本字段,置空库存时同步置空。回填口径:存量行中
|
||||
external_quantity 非空者以 updated_at 近似(历史取数时刻未单独
|
||||
记录,取行最后一次变更是可得的最优近似);无库存数据行保持
|
||||
NULL。downgrade 直接 drop。
|
||||
|
||||
Revision ID: t5a6b7c8d9e0f
|
||||
Revises: q4c5d6e7f8a9
|
||||
Create Date: 2026-09-29 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "t5a6b7c8d9e0f"
|
||||
down_revision = "q4c5d6e7f8a9"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("transfer_invoice_items", sa.Column("inventory_checked_at", sa.DateTime(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE transfer_invoice_items SET inventory_checked_at = updated_at "
|
||||
"WHERE external_quantity IS NOT NULL"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("transfer_invoice_items", "inventory_checked_at")
|
||||
@@ -506,6 +506,125 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 4:retry-rpa 对 parse_failed 先本地重解析(成功 200+ready / 仍失败 ok=False;
|
||||
# 两条路径均不触发 RPA、不返回 202/fetching)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_parse_failed_receipt_file(source_code: str):
|
||||
"""造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。
|
||||
|
||||
与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数:
|
||||
来源须在全局 app 夹具种子中(DSV360_AWSDU);文件 created_at 取默认当前 UTC
|
||||
(当日业务日窗口内 → 可用门禁命中),返回该文件供测试断言。
|
||||
"""
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from app.models import (
|
||||
ShippingInventorySource,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).one()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id,
|
||||
callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success",
|
||||
config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=f"shipping/receipt/retry-{unit.id}.xlsx",
|
||||
original_filename="retry.xlsx", file_size=16,
|
||||
sha256=hashlib.sha256(b"retry workbook").hexdigest(),
|
||||
parse_failed_at=datetime.utcnow(),
|
||||
parse_error_code="TRANSFER_FILE_SCHEMA_INVALID", parse_error_message="schema",
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
|
||||
|
||||
def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_headers, monkeypatch):
|
||||
"""parse_failed 且有可用文件 → retry 先本地重解析(sync),不触发 RPA(200 非 202)。"""
|
||||
called = {"sync": 0, "rpa": 0}
|
||||
_seed_parse_failed_receipt_file("DSV360_AWSDU")
|
||||
|
||||
def fake_sync(*, source_code, business_date, now):
|
||||
# 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回
|
||||
# ready(请求会话内重查后清除并 commit,保证端点再解析可见)。
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.source_file_status import clear_receipt_parse_failure
|
||||
|
||||
called["sync"] += 1
|
||||
file = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code))
|
||||
.first()
|
||||
)
|
||||
if file is not None:
|
||||
clear_receipt_parse_failure(report=file)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
|
||||
fake_sync,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
|
||||
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
|
||||
)
|
||||
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
|
||||
# 断言意图:重解析成功返回 200(非 202/fetching),payload 恰为四键契约,
|
||||
# 且 RPA 触发 0 次(本地重解析不落 RPA 单元)。
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()["data"]
|
||||
assert body == {
|
||||
"source_code": "DSV360_AWSDU", "ok": True,
|
||||
"file_status": "ready", "reparsed": True,
|
||||
}
|
||||
assert called["sync"] == 1
|
||||
assert called["rpa"] == 0
|
||||
|
||||
|
||||
def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_headers, monkeypatch):
|
||||
"""sync 返回 True 但投影仍 parse_failed → ok=False(不触发 RPA、不回 202)。"""
|
||||
called = {"sync": 0, "rpa": 0}
|
||||
_seed_parse_failed_receipt_file("DSV360_AWSDU")
|
||||
|
||||
def fake_sync(*, source_code, business_date, now):
|
||||
# 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报
|
||||
# 失败(ok=False + parse_failed),由用户感知仍不可用。
|
||||
called["sync"] += 1
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
|
||||
fake_sync,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
|
||||
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
|
||||
)
|
||||
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
|
||||
# 断言意图:仍失败也返回 200(业务结果在 ok 字段),RPA 0 次不兜底重抓。
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()["data"]
|
||||
assert body == {
|
||||
"source_code": "DSV360_AWSDU", "ok": False,
|
||||
"file_status": "parse_failed", "reparsed": True,
|
||||
}
|
||||
assert called["sync"] == 1
|
||||
assert called["rpa"] == 0
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
@@ -755,15 +874,17 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
data = run.get_json()["data"]
|
||||
orders = data["orders"]
|
||||
assert len(orders) == 3
|
||||
# 断言意图:单序稳定(created_at/id 升序 = 组建单的组键升序:收料日期升序)。
|
||||
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源,
|
||||
# 收料日期升序,与建单的组键序一致)。
|
||||
assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
|
||||
|
||||
by_status = {t["status"]: t for t in orders}
|
||||
assert set(by_status) == {"success", "business_failed", "result_unknown"}
|
||||
|
||||
success = by_status["success"]
|
||||
# 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含六键
|
||||
# (含 reason:框线图失败行原因展示契约,控制器裁决扩充,T13-3)。
|
||||
# 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含七键
|
||||
# (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图
|
||||
# 失败行原因展示契约,控制器裁决扩充,T13-3)。
|
||||
assert set(success.keys()) == {
|
||||
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
|
||||
"status", "erp_document_no", "error_message", "lines",
|
||||
@@ -777,6 +898,7 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
# 断言意图:行数量为 6 位小数字符串(D14 快照口径),unit 原值透传非空;
|
||||
# 成功行 reason 为 None(键恒出现)。
|
||||
assert success["lines"] == [{
|
||||
"invoice_no": "HOM-A",
|
||||
"material_no": "MAT-001", "material_name": "物料MAT-001", "lot_no": "LOT-10",
|
||||
"quantity": "500.000000", "unit": "EA", "reason": None,
|
||||
}]
|
||||
@@ -784,8 +906,9 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
failed = by_status["business_failed"]
|
||||
assert failed["erp_document_no"] is None
|
||||
# 断言意图:单据级 error_message 恒 null(T11 裁决契约:失败/未知原因只在
|
||||
# 行级 reason 与 run exceptions 透出,单据级不落原因文本)。
|
||||
# 行级 reason 与 orders 卡片透出,单据级不落原因文本)。
|
||||
assert failed["error_message"] is None
|
||||
assert failed["lines"][0]["invoice_no"] == "HOX-B"
|
||||
assert failed["lines"][0]["quantity"] == "700.000000"
|
||||
# 断言意图:失败行 reason=行级 result_message(框线图「原因」展示数据源)。
|
||||
assert failed["lines"][0]["reason"] == "rejected by external system"
|
||||
@@ -800,10 +923,9 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
# 断言意图:未知行 reason 回落 error_code(result_message 为空时引擎已写入)。
|
||||
assert unknown["lines"][0]["reason"] == "EXTERNAL_TIMEOUT_AFTER_COMMIT"
|
||||
|
||||
# 断言意图:exceptions 既有口径不变——成功族行不进异常清单,失败/未知行逐行进。
|
||||
exceptions = data["result"]["exceptions"]
|
||||
assert len(exceptions) == 2
|
||||
assert {exc["reason"] for exc in exceptions} == {"business_failed", "result_unknown"}
|
||||
# 断言意图:[2026-09-29 口径收窄] exceptions 仅收未建单阻断行——失败/未知行
|
||||
# 已建单,不再进异常清单(原因/动作由 orders 卡片承载)。
|
||||
assert data["result"]["exceptions"] == []
|
||||
# 断言意图:external_documents 既有口径不变——仅成功单聚合出单据视图。
|
||||
assert len(data["result"]["external_documents"]) == 1
|
||||
|
||||
@@ -973,9 +1095,10 @@ def test_list_documents_group_counts_always_full(app, transfer_db, client, admin
|
||||
assert data["total"] == 7 # cancelled 不进列表
|
||||
assert data["page"] == 1
|
||||
assert data["page_size"] == 20
|
||||
# 断言意图:列表 created_at 倒序(无筛选=全部未关闭单)。
|
||||
# 断言意图:列表按 收料日期→数据源→库位 升序(2026-09-29 统一口径;本组
|
||||
# 造数同日同源,按拨入库位字典序升序)。
|
||||
assert [t["doc_no"] for t in data["orders"]] == [
|
||||
"D-UNK-1", "D-EXEC-2", "D-EXEC-1", "D-FAIL-2", "D-FAIL-1", "D-SUC-2", "D-SUC-1",
|
||||
"D-EXEC-1", "D-EXEC-2", "D-FAIL-1", "D-FAIL-2", "D-SUC-1", "D-SUC-2", "D-UNK-1",
|
||||
]
|
||||
|
||||
# 过滤 failed:groups 计数不变(恒全量),列表仅失败族。
|
||||
@@ -1030,7 +1153,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm
|
||||
|
||||
|
||||
def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs_matching):
|
||||
"""分页:默认 page_size=20;created_at 倒序;page/page_size 翻页取片;上限 100。"""
|
||||
"""分页:默认 page_size=20;收料日期→数据源→库位升序;page/page_size 翻页取片;上限 100。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
with app.app_context():
|
||||
@@ -1045,22 +1168,23 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs
|
||||
first_page = client.get(f"{API_PREFIX}/documents?status_group=failed", headers=admin_headers).get_json()["data"]
|
||||
assert first_page["total"] == 25
|
||||
assert len(first_page["orders"]) == 20
|
||||
# 断言意图:列表 created_at 倒序——第一页含最新的 24~5 号单。
|
||||
assert first_page["orders"][0]["doc_no"] == "D-PG-24"
|
||||
assert first_page["orders"][-1]["doc_no"] == "D-PG-05"
|
||||
# 断言意图:列表升序(2026-09-29 统一口径;本组造数同日同源,按拨入库位
|
||||
# 字典序 = doc_no 序)——第一页含最早的 00~19 号单。
|
||||
assert first_page["orders"][0]["doc_no"] == "D-PG-00"
|
||||
assert first_page["orders"][-1]["doc_no"] == "D-PG-19"
|
||||
|
||||
second_page = client.get(
|
||||
f"{API_PREFIX}/documents?status_group=failed&page=2", headers=admin_headers,
|
||||
).get_json()["data"]
|
||||
assert len(second_page["orders"]) == 5
|
||||
assert second_page["orders"][0]["doc_no"] == "D-PG-04"
|
||||
assert second_page["orders"][0]["doc_no"] == "D-PG-20"
|
||||
|
||||
sized = client.get(
|
||||
f"{API_PREFIX}/documents?status_group=failed&page=2&page_size=10", headers=admin_headers,
|
||||
).get_json()["data"]
|
||||
assert sized["page"] == 2
|
||||
assert sized["page_size"] == 10
|
||||
assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(14, 4, -1)]
|
||||
assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(10, 20)]
|
||||
|
||||
# page_size 上限 100:超限收口到 100(防大页拖库)。
|
||||
capped = client.get(
|
||||
@@ -1070,26 +1194,29 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs
|
||||
|
||||
|
||||
def test_list_documents_date_range_filters_list_only(app, transfer_db, client, admin_headers, docs_matching):
|
||||
"""时间范围仅作用 orders 列表(groups 恒全量);历史单(30 天前失败单)计入且可查出。"""
|
||||
"""时间范围(收料日期口径,2026-09-29 切换)仅作用 orders 列表(groups 恒全量);
|
||||
历史收料日期的失败单计入且可查出。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
with app.app_context():
|
||||
now = datetime(2026, 9, 24, 10, 0, 0)
|
||||
_seed_document(transfer_db, docs_matching, "D-OLD-1", "2026-08-06 09:00:00", "business_failed",
|
||||
group={"receipt_date": "2026-08-25"},
|
||||
created_at=now - timedelta(days=30))
|
||||
_seed_document(transfer_db, docs_matching, "D-NEW-1", "2026-08-06 10:00:00", "business_failed",
|
||||
group={"receipt_date": "2026-09-23"},
|
||||
created_at=now - timedelta(days=1))
|
||||
transfer_db.session.commit()
|
||||
|
||||
unfiltered = client.get(f"{API_PREFIX}/documents", headers=admin_headers).get_json()["data"]
|
||||
# 断言意图:历史失败单(30 天前)计入分组计数且默认列表可查(created_at 倒序在前)。
|
||||
# 断言意图:历史收料日期失败单计入分组计数且默认列表可查(收料日期升序在前)。
|
||||
assert unfiltered["groups"]["failed"] == 2
|
||||
assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-NEW-1", "D-OLD-1"]
|
||||
assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-OLD-1", "D-NEW-1"]
|
||||
|
||||
ranged = client.get(
|
||||
f"{API_PREFIX}/documents?date_from=2026-09-20&date_to=2026-09-30", headers=admin_headers,
|
||||
).get_json()["data"]
|
||||
# 断言意图:时间窗只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。
|
||||
# 断言意图:时间窗按收料日期只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。
|
||||
assert [t["doc_no"] for t in ranged["orders"]] == ["D-NEW-1"]
|
||||
assert ranged["groups"]["failed"] == 2
|
||||
|
||||
|
||||
@@ -226,7 +226,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
|
||||
|
||||
def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。"""
|
||||
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
|
||||
@@ -234,7 +234,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
|
||||
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
assert draft['activation']['ready'] is False
|
||||
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
payload['enabled'] = True
|
||||
saved = shipping_inventory_service.save_source(
|
||||
@@ -245,11 +245,11 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.activate_source(draft['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
|
||||
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
|
||||
def test_activation_status_exposes_only_hard_gate_checks(app):
|
||||
"""启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
|
||||
@@ -267,14 +267,13 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc
|
||||
|
||||
checks = {item['code']: item for item in draft['activation']['checks']}
|
||||
|
||||
# 关键断言:未进行测试时,解析/仓库验证被展示为待测试而非额外阻断门禁。
|
||||
assert checks['configuration_test']['blocking'] is True
|
||||
assert checks['configuration_test']['evidence'] == {'state': 'not_started'}
|
||||
assert checks['parsing_validation']['status'] == 'pending'
|
||||
assert checks['parsing_validation']['blocking'] is False
|
||||
assert checks['warehouse_mapping']['status'] == 'pending'
|
||||
assert checks['warehouse_mapping']['blocking'] is False
|
||||
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
# 关键断言:测试导出与可选准备项已退出启用门禁;仅硬门槛阻断。
|
||||
assert set(checks) == {'rpa_profile', 'parsing_profile', 'excel_template', 'template_validation'}
|
||||
assert 'configuration_test' not in checks
|
||||
assert checks['rpa_profile']['blocking'] is False
|
||||
assert checks['parsing_profile']['blocking'] is True
|
||||
assert checks['excel_template']['blocking'] is True
|
||||
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
@@ -355,8 +354,8 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
|
||||
assert history[0]['source_config_version_after'] == bound[0]['config_version']
|
||||
|
||||
|
||||
def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
"""批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。"""
|
||||
def test_bulk_parsing_profile_binding_allows_enabled_sites(app):
|
||||
"""批量绑定允许包含已启用站点;全部预检通过后原子写入。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
|
||||
@@ -366,16 +365,16 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
|
||||
profile = _parsing_profile()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
|
||||
reason='批量迁移同类报表', operation='bulk',
|
||||
)
|
||||
bound = shipping_inventory_service.bind_source_parsing_profile(
|
||||
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
|
||||
reason='批量迁移同类报表', operation='bulk',
|
||||
)
|
||||
|
||||
# 关键断言:任一站点不可变更时,停用站点也不得留下部分绑定或审计。
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED'
|
||||
assert db.session.get(ShippingInventorySource, disabled['id']).parsing_profile_id is None
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
|
||||
# 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。
|
||||
assert {row['id'] for row in bound} == {disabled['id'], enabled['id']}
|
||||
assert all(row['parsing_profile_id'] == profile['id'] for row in bound)
|
||||
assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 2
|
||||
|
||||
|
||||
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
|
||||
|
||||
@@ -34,6 +34,22 @@ def _stub_doc_sequence(monkeypatch):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _pin_maturity_lag_legacy(request):
|
||||
"""在途套件钉成熟滞后=1(T+1)。
|
||||
|
||||
用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期
|
||||
2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_
|
||||
LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项
|
||||
用例显式覆盖,不被本钉值掩盖。
|
||||
逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例
|
||||
(如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。
|
||||
"""
|
||||
if "app" in getattr(request, "fixturenames", []):
|
||||
app = request.getfixturevalue("app")
|
||||
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fixed_clock() -> FakeClock:
|
||||
"""固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。"""
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""自动调拨编排(run_auto_transfer)测试:空数据日跳过与正常执行透传。
|
||||
|
||||
用途:锁定 09:00 自动排程编排的阶段语义——匹配后无可执行行(含恢复后仍为 0)
|
||||
时不建票、不写 ERP、不通知、不记 error(产品决策 C5);有可执行行时把
|
||||
执行结果透传给调用方。
|
||||
依赖:auto_transfer(monkeypatch create_matching / execute_matching_items)。
|
||||
逻辑:纯单元用例,不触库;恢复阶段用 recover_history=False 关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import app.services.in_transit_transfer.auto_transfer as at
|
||||
from app.services.in_transit_transfer.contracts import MatchingCountsDTO, MatchingSummaryDTO
|
||||
|
||||
|
||||
def _summary(executable_count: int) -> MatchingSummaryDTO:
|
||||
return MatchingSummaryDTO(
|
||||
matching_id="MTG-20260928-ABC123",
|
||||
status="matched",
|
||||
business_date="2026-09-28",
|
||||
eligible_receipt_date_to="2026-09-27",
|
||||
expires_at="2026-09-28T10:00:00",
|
||||
counts=MatchingCountsDTO(executable_count=executable_count),
|
||||
estimated_transfer_quantity="0",
|
||||
estimated_external_write_count=executable_count,
|
||||
matching_hash="hash-x",
|
||||
)
|
||||
|
||||
|
||||
def test_skips_execution_when_no_executable_items(monkeypatch):
|
||||
"""空数据日:不执行、不通知、不记 error,clean no-op。"""
|
||||
monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(0))
|
||||
|
||||
def _must_not_execute(**kwargs):
|
||||
raise AssertionError("execute_matching_items must not be called on empty day")
|
||||
|
||||
monkeypatch.setattr(at, "execute_matching_items", _must_not_execute)
|
||||
|
||||
outcome = at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
)
|
||||
assert outcome.run_no is None
|
||||
assert outcome.run_status is None
|
||||
assert outcome.errors == []
|
||||
|
||||
|
||||
def test_executes_and_propagates_result_when_executable(monkeypatch):
|
||||
"""有可执行行:按匹配执行并透传 run_no/status。"""
|
||||
monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(3))
|
||||
captured = {}
|
||||
|
||||
def _fake_execute(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return SimpleNamespace(run_no="RUN-20260928-XYZ789", status="success")
|
||||
|
||||
monkeypatch.setattr(at, "execute_matching_items", _fake_execute)
|
||||
|
||||
outcome = at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
)
|
||||
assert captured["matching_id"] == "MTG-20260928-ABC123"
|
||||
assert outcome.run_no == "RUN-20260928-XYZ789"
|
||||
assert outcome.run_status == "success"
|
||||
assert outcome.errors == []
|
||||
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user